summaryrefslogtreecommitdiffstats
path: root/openstack-client-connectors/resteasy-connector/src/main/java/com/woorea/openstack/connector/RESTEasyConnector.java
blob: b804e69c3163e828741b948a35ed3ff003f47837 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*-
 * ============LICENSE_START=======================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package com.woorea.openstack.connector;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.ContextResolver;

// bwj: changed the HttpStatus package
//import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpStatus;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.InputStreamProvider;
import org.jboss.resteasy.spi.ResteasyProviderFactory;

import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.woorea.openstack.base.client.OpenStackClientConnector;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.base.client.OpenStackResponse;
import com.woorea.openstack.base.client.OpenStackResponseException;

public class RESTEasyConnector implements OpenStackClientConnector {

    public static ObjectMapper DEFAULT_MAPPER;

    public static ObjectMapper WRAPPED_MAPPER;

    static class OpenStackProviderFactory extends ResteasyProviderFactory {

        private JacksonJsonProvider jsonProvider;
        private InputStreamProvider streamProvider;

        public OpenStackProviderFactory() {
            super();

            addContextResolver(new ContextResolver<ObjectMapper>() {
                @Override
                public ObjectMapper getContext(Class<?> type) {
                    return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
                }
            });

            jsonProvider = new JacksonJsonProvider();
            addMessageBodyReader(jsonProvider);
            addMessageBodyWriter(jsonProvider);

            streamProvider = new InputStreamProvider();
            addMessageBodyReader(streamProvider);
            addMessageBodyWriter(streamProvider);
        }

    }

    private static OpenStackProviderFactory providerFactory;

    static {
        DEFAULT_MAPPER = new ObjectMapper();

        DEFAULT_MAPPER.setSerializationInclusion(Include.NON_NULL);
        DEFAULT_MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
        DEFAULT_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        DEFAULT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        DEFAULT_MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        WRAPPED_MAPPER = new ObjectMapper();

        WRAPPED_MAPPER.setSerializationInclusion(Include.NON_NULL);
        WRAPPED_MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
        WRAPPED_MAPPER.enable(SerializationFeature.WRAP_ROOT_VALUE);
        WRAPPED_MAPPER.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
        WRAPPED_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        WRAPPED_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        WRAPPED_MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        providerFactory = new OpenStackProviderFactory();
    }

    @Override
    public <T> OpenStackResponse request(OpenStackRequest<T> request) {
        ClientRequest client = new ClientRequest(UriBuilder.fromUri(request.endpoint() + "/" + request.path()),
                ClientRequest.getDefaultExecutor(), providerFactory);

        for(Map.Entry<String, List<Object> > entry : request.queryParams().entrySet()) {
            for (Object o : entry.getValue()) {
                client = client.queryParameter(entry.getKey(), String.valueOf(o));
            }
        }

        for (Entry<String, List<Object>> h : request.headers().entrySet()) {
            StringBuilder sb = new StringBuilder();
            for (Object v : h.getValue()) {
                sb.append(String.valueOf(v));
            }
            client.header(h.getKey(), sb);
        }

        if (request.entity() != null) {
            client.body(request.entity().getContentType(), request.entity().getEntity());
        }

        ClientResponse<T> response;

        try {
            response = client.httpMethod(request.method().name(), request.returnType());
        } catch (Exception e) {
            throw new RuntimeException("Unexpected client exception", e);
        }

        if (response.getStatus() == HttpStatus.SC_OK
                || response.getStatus() == HttpStatus.SC_CREATED
                || response.getStatus() == HttpStatus.SC_NO_CONTENT
                || response.getStatus() == HttpStatus.SC_ACCEPTED) {
            return new RESTEasyResponse(client, response);
        }

        response.releaseConnection();

        throw new OpenStackResponseException(response.getResponseStatus()
                .getReasonPhrase(), response.getStatus());
    }

}