View Javadoc

1   /**
2    *
3    * Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
4    *
5    * ====================================================================
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   * ====================================================================
18   */
19  package org.jclouds.vcloud.util;
20  
21  import javax.annotation.Resource;
22  import javax.inject.Inject;
23  import javax.inject.Provider;
24  import javax.inject.Singleton;
25  
26  import org.jclouds.http.HttpRequest;
27  import org.jclouds.http.HttpResponse;
28  import org.jclouds.http.functions.ParseSax;
29  import org.jclouds.http.functions.ParseSax.Factory;
30  import org.jclouds.logging.Logger;
31  import org.jclouds.vcloud.VCloudMediaType;
32  import org.jclouds.vcloud.domain.VCloudError;
33  import org.jclouds.vcloud.xml.ErrorHandler;
34  
35  /**
36   * Needed to sign and verify requests and responses.
37   * 
38   * @author Adrian Cole
39   */
40  @Singleton
41  public class VCloudUtils {
42     private final ParseSax.Factory factory;
43     private final Provider<ErrorHandler> errorHandlerProvider;
44     @Resource
45     protected Logger logger = Logger.NULL;
46  
47     @Inject
48     VCloudUtils(Factory factory, Provider<ErrorHandler> errorHandlerProvider) {
49        this.factory = factory;
50        this.errorHandlerProvider = errorHandlerProvider;
51     }
52  
53     public VCloudError parseErrorFromContent(HttpRequest request, HttpResponse response) {
54        // HEAD has no content
55        if (response.getPayload() == null)
56           return null;
57        if (VCloudMediaType.ERROR_XML.equals(response.getPayload().getContentMetadata().getContentType())) {
58           try {
59              return (VCloudError) factory.create(errorHandlerProvider.get()).setContext(request).apply(response);
60           } catch (RuntimeException e) {
61              logger.warn(e, "error parsing error");
62           }
63        }
64        return null;
65     }
66  }