summaryrefslogtreecommitdiffstats
path: root/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpBaseRest.java
blob: 0672715d4329db588e39c4144388c7268b4519b9 (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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
 * Copyright 2016 Huawei Technologies Co., Ltd.
 *
 * 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.
 */

package org.onap.vfc.nfvo.multivimproxy.common.util.restclient;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.jetty.client.Address;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.http.HttpMethods;

/**
 * <br/>
 * <p>
 * </p>
 *
 * @author
 * @version Aug 9, 2016
 */
public abstract class HttpBaseRest implements Restful {

    private static final Logger LOG = LogManager.getLogger(HttpRest.class);

    final AtomicInteger requestId = new AtomicInteger(0);

    protected HttpClient client = null;

    private static final String LOCAL_HOST = Inet4Address.getLoopbackAddress().getHostAddress();

    static final String HTTP_PATCH = "PATCH";

    String defaultIP = LOCAL_HOST;

    int defaultPort = -10000;

    int defaultTimeout = 30000;

    final String procenameRouteID = "RouteID-" + System.currentTimeMillis() + "-";

    /**
     * Constructor<br/>
     * <p>
     * </p>
     *
     * @since
     */
    public HttpBaseRest() {
        super();
    }

    protected void createHttpClient() {
        client = new HttpClient();
    }

    protected RestHttpContentExchange createRestHttpContentExchange(final RestfulAsyncCallback callback) {
        final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
        exchange.setScheme("http");
        return exchange;
    }

    private String encodeParams(final RestfulParametes restParametes) throws ServiceException {
        final Map<String, String> parm = restParametes.getParamMap();
        String value = null;
        boolean bHasParma = false;
        final StringBuilder builder = new StringBuilder();
        try {
            for(final String key : parm.keySet()) {
                value = parm.get(key);
                if(value == null) {
                    value = "";
                }
                String str;
                if(bHasParma) {
                    str = String.format("&%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
                            URLEncoder.encode(value, RestfulClientConst.ENCODING));
                } else {
                    bHasParma = true;
                    str = String.format("%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
                            URLEncoder.encode(value, RestfulClientConst.ENCODING));
                }
                builder.append(str);
            }
        } catch(final UnsupportedEncodingException ex) {
            LOG.error("unsupported encoding: ", ex);
            throw new ServiceException("Broken VM does not support UTF-8");
        }
        return builder.toString();
    }

    private void processHeader(final RestHttpContentExchange contentExchange, final Map<String, String> headerMap) {
        for(final String key : headerMap.keySet()) {
            final String value = headerMap.get(key);
            contentExchange.addRequestHeader(key, value);
        }

    }

    private void setContentExchangeParams(final RestHttpContentExchange contentExchange) {
        final String contentType = contentExchange.getRequestFields().getStringField("Content-Type");
        if(null == contentType || contentType.isEmpty()) {
            // application/json;charset=utf-8
            contentExchange.setRequestContentType(RestfulClientConst.APPLICATION_FORM_URLENCODED);
        }
        final String encoding = contentExchange.getRequestFields().getStringField("Accept-Encoding");
        if(null == encoding || encoding.isEmpty()) {
            // compress,gzip
            contentExchange.setRequestHeader("Accept-Encoding", "*/*");
        }
        contentExchange.setVersion(11);
    }

    /**
     * <br/>
     *
     * @param method
     * @param servicePath
     * @param restParametes
     * @param options
     * @param callback
     * @return
     * @throws ServiceException
     * @since
     */
    protected RestfulResponse sendHttpRequest(final String method, final String servicePath,
            final RestfulParametes restParametes, final RestfulOptions options, final RestfulAsyncCallback callback)
            throws ServiceException {
        final RestHttpContentExchange contentExchange = createRestHttpContentExchange(callback);
        if(null == restParametes) {
            return new RestfulResponse();
        }
        final String requestTrace = this.getReuqestIdString();
        restParametes.putHttpContextHeader(RestfulClientConst.REQUEST_ID, requestTrace);

        RestfulResponse rsp = null;
        try {
            contentExchange.setMethod(method);
            final String str = encodeParams(restParametes);
            final StringBuilder builder = new StringBuilder();
            builder.append(servicePath);
            if(str.length() > 0 && (method.equals(HttpMethods.GET) || method.equals(HttpMethods.DELETE)
                    || method.equals(HttpMethods.HEAD))) {
                builder.append('?');
                builder.append(str);
            }
            setDefaultUrl(contentExchange, options, builder);
            processHeader(contentExchange, restParametes.getHeaderMap());
            setContentExchangeParams(contentExchange);

            setPostPutParam(method, restParametes, contentExchange, str);
            setTimeout(options, contentExchange);

            client.send(contentExchange);
            rsp = callbackExecute(callback, contentExchange);
        } catch(final Exception e) {
            LOG.error("request reply message have exception:status is "
                    + RestHttpContentExchange.toState(contentExchange.getStatus()));
            throw new ServiceException(e);
        }
        return rsp;
    }

    private void setDefaultUrl(final RestHttpContentExchange contentExchange, final RestfulOptions options,
            final StringBuilder url) {
        // server
        if(url.toString().startsWith("http")) {
            contentExchange.setURL(url.toString());
        } else {
            String host = defaultIP;
            int iPort = defaultPort;
            if(options != null) {
                host = options.getHost();
                if(host.isEmpty()) {
                    host = defaultIP;
                }
                iPort = options.getPort();
                if(iPort == 0) {
                    iPort = defaultPort;
                }
            }
            // Integer.getInteger(".http.client.maxThread",30)
            contentExchange.setAddress(new Address(host, iPort));
            contentExchange.setRequestURI(url.toString());
        }
    }

    private String getReuqestIdString() {
        if(this.requestId.get() == 0x7FFFFFFF) {
            this.requestId.set(1);
        }
        final int reqId = this.requestId.getAndIncrement();
        final StringBuilder builder = new StringBuilder(this.procenameRouteID);
        // time
        final SimpleDateFormat dateFormate = new SimpleDateFormat("yyMMdd");
        final SimpleDateFormat timeFormate = new SimpleDateFormat("HHmmss");
        final Date date = Calendar.getInstance().getTime();
        builder.append(dateFormate.format(date) + timeFormate.format(date));
        builder.append('-');
        builder.append(reqId);
        return builder.toString();
    }

    private void setPostPutParam(final String method, final RestfulParametes restParametes,
            final RestHttpContentExchange contentExchange, final String str) throws UnsupportedEncodingException {
        if(HttpMethods.POST.equals(method) || HttpMethods.PUT.equals(method) || HTTP_PATCH.equals(method)) {
            ByteArrayInputStream buff;
            final String tmpRaw = restParametes.getRawData();
            if(tmpRaw == null) {
                buff = new ByteArrayInputStream(str.getBytes(RestfulClientConst.ENCODING));
            } else {
                buff = new ByteArrayInputStream(tmpRaw.getBytes(RestfulClientConst.ENCODING));
            }
            final int len = buff.available();
            contentExchange.setRequestContentSource(buff);
            contentExchange.setRequestHeader("content-length", String.valueOf(len));
        }
    }

    private void setTimeout(final RestfulOptions options, final RestHttpContentExchange contentExchange) {
        if(options != null) {
            final long timeout = options.getRestTimeout();
            if(timeout != 0) {
                contentExchange.setTimeout(timeout);
            } else {
                contentExchange.setTimeout(defaultTimeout);
            }
        } else {
            contentExchange.setTimeout(defaultTimeout);
        }
    }

    private RestfulResponse callbackExecute(final RestfulAsyncCallback callback,
            final RestHttpContentExchange contentExchange) throws InterruptedException, IOException, ServiceException {
        if(callback == null) {
            final int exchangeState = contentExchange.waitForDone();
            if(exchangeState == HttpExchange.STATUS_COMPLETED) {
                return contentExchange.getResponse();
            } else if(exchangeState == HttpExchange.STATUS_EXCEPTED) {
                throw new ServiceException(
                        "request is exception: " + RestHttpContentExchange.toState(HttpExchange.STATUS_EXCEPTED));
            } else if(exchangeState == HttpExchange.STATUS_EXPIRED) {
                throw new ServiceException(
                        "request is expierd: " + RestHttpContentExchange.toState(HttpExchange.STATUS_EXPIRED));
            }
        }
        return null;
    }

}