Modify svnfm pom file for build docker
[vfc/nfvo/driver/vnfm/svnfm.git] / huawei / vnfmadapter / VnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / svnfm / vnfmadapter / common / restclient / RestHttpContentExchange.java
1 /*
2  * Copyright 2016 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient;
18
19 import java.io.ByteArrayInputStream;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.nio.charset.Charset;
23 import java.util.Enumeration;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.zip.GZIPInputStream;
27
28 import org.apache.commons.lang.StringUtils;
29 import org.eclipse.jetty.client.ContentExchange;
30 import org.eclipse.jetty.client.HttpDestination;
31 import org.eclipse.jetty.http.HttpFields;
32 import org.eclipse.jetty.http.HttpHeaders;
33 import org.eclipse.jetty.io.Buffer;
34 import org.eclipse.jetty.util.StringUtil;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * ContentExchange implementation classe to provide access to response.
40  * <br/>
41  * <p>
42  * </p>
43  * 
44  * @author
45  * @version 28-May-2016
46  */
47 public class RestHttpContentExchange extends ContentExchange {
48
49     private static final Logger LOGGER = LoggerFactory.getLogger(RestHttpContentExchange.class);
50
51     private boolean gzip = false;
52
53     private RestfulAsyncCallback callback = null;
54
55     /**
56      * Constructor<br/>
57      * <p>
58      * </p>
59      * 
60      * @since
61      * @param cacheFields whether to cache response header.
62      * @param asyncCallback callback method.
63      */
64     RestHttpContentExchange(final boolean cacheFields, final RestfulAsyncCallback asyncCallback) {
65         super(cacheFields);
66         this.callback = asyncCallback;
67     }
68
69     /**
70      * Extract message.
71      * <br/>
72      * 
73      * @param data GZipped data.
74      * @return Uncompressed data.
75      * @throws IOException
76      * @since
77      */
78     public String decompressGzipToStr(final byte[] data) throws IOException {
79         if(data == null) {
80             return "";
81         }
82         ByteArrayInputStream input = null;
83         GZIPInputStream gzis = null;
84         InputStreamReader reader = null;
85         final StringBuilder out = new StringBuilder();
86         try {
87             input = new ByteArrayInputStream(data);
88             gzis = new GZIPInputStream(input);
89             reader = new InputStreamReader(gzis, Charset.forName(RestfulClientConst.ENCODING));
90             final char[] buff = new char[1024];
91             for(int n; (n = reader.read(buff)) != -1;) {
92                 out.append(new String(buff, 0, n));
93             }
94         } finally {
95             if(reader != null) {
96                 try {
97                     reader.close();
98                 } catch(final IOException e) {
99                     LOGGER.error("decompress Gzip reader exception:", e);
100                 }
101             }
102             if(gzis != null) {
103                 try {
104                     gzis.close();
105                 } catch(final IOException e) {
106                     LOGGER.error("decompress Gzip exception:", e);
107                 }
108             }
109             if(input != null) {
110                 try {
111                     input.close();
112                 } catch(final IOException e) {
113                     LOGGER.error("decompress Gzip input exception:", e);
114                 }
115             }
116         }
117         return out.toString();
118
119     }
120
121     /**
122      * View response headers Content-Encoding values if you need to extract data.<br/>
123      * 
124      * @param name buffer
125      * @param value value
126      * @throws IOException
127      * @since
128      */
129     @Override
130     protected synchronized void onResponseHeader(final Buffer name, final Buffer value) throws IOException {
131         super.onResponseHeader(name, value);
132         final int header = HttpHeaders.CACHE.getOrdinal(name);
133         if(header == HttpHeaders.CONTENT_ENCODING_ORDINAL) {
134             final String encoding = StringUtil.asciiToLowerCase(value.toString());
135             gzip = encoding != null && StringUtils.contains(encoding, "gzip");
136         }
137
138     }
139
140     @Override
141     protected void onResponseComplete() throws IOException {
142         if(LOGGER.isInfoEnabled()) {
143             LOGGER.info("Response has Complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
144         }
145         super.onResponseComplete();
146         if(callback != null) {
147             final RestfulResponse rsp = getResponse();
148             callback.callback(rsp);
149         }
150     }
151
152     @Override
153     protected void onRequestCommitted() throws IOException {
154         if(LOGGER.isInfoEnabled()) {
155             LOGGER.info("Request Header has been send:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
156         }
157         super.onRequestCommitted();
158     }
159
160     @Override
161     protected void onRequestComplete() throws IOException {
162         if(LOGGER.isInfoEnabled()) {
163             LOGGER.info("Request has bend send complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
164         }
165         super.onRequestComplete();
166     }
167
168     @Override
169     protected void onException(final Throwable x) {
170         LOGGER.warn("onException:", x);
171         super.onException(x);
172         if(callback != null) {
173             callback.handleExcepion(x);
174         }
175     }
176
177     @Override
178     protected void onConnectionFailed(final Throwable x) {
179         LOGGER.warn("onConnectionFailed:", x);
180         super.onConnectionFailed(x);
181         if(callback != null) {
182             callback.handleExcepion(x);
183         }
184
185     }
186
187     @Override
188     protected void expire(final HttpDestination destination) {
189         super.expire(destination);
190         if(callback != null) {
191             callback.handleExcepion(new ServiceException("request is expired, status:" + toState(getStatus())));
192         }
193     }
194
195     public boolean isGzip() {
196         return gzip;
197     }
198
199     /**
200      * Get the response as RestfulResponse.
201      * <br/>
202      * 
203      * @return response object.
204      * @throws IOException
205      * @since
206      */
207     public RestfulResponse getResponse() throws IOException {
208         final RestfulResponse rsp = new RestfulResponse();
209         rsp.setStatus(this.getResponseStatus());
210         if(isGzip()) {
211             final String responseString = decompressGzipToStr(getResponseContentBytes());
212             rsp.setResponseJson(responseString);
213         } else {
214             rsp.setResponseJson(this.getResponseContent());
215         }
216
217         final HttpFields field = this.getResponseFields();
218         if(field != null) {
219             final Map<String, String> header = new HashMap<>();
220
221             final Enumeration<String> names = field.getFieldNames();
222             for(final Enumeration<String> e = names; e.hasMoreElements();) {
223                 final String fieldName = e.nextElement();
224                 final String fieldValue = field.getStringField(fieldName);
225                 header.put(fieldName, fieldValue);
226             }
227
228             rsp.setRespHeaderMap(header);
229         }
230         return rsp;
231     }
232
233 }