Fix invalid versions in pom.xml
[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 static final String PATH = "path:";
52
53     private boolean gzip = false;
54
55     private RestfulAsyncCallback callback = null;
56
57     /**
58      * Constructor<br/>
59      * <p>
60      * </p>
61      * 
62      * @since
63      * @param cacheFields whether to cache response header.
64      * @param asyncCallback callback method.
65      */
66     RestHttpContentExchange(final boolean cacheFields, final RestfulAsyncCallback asyncCallback) {
67         super(cacheFields);
68         this.callback = asyncCallback;
69     }
70
71     /**
72      * Extract message.
73      * <br/>
74      * 
75      * @param data GZipped data.
76      * @return Uncompressed data.
77      * @throws IOException
78      * @since
79      */
80     public String decompressGzipToStr(final byte[] data) throws IOException {
81         if(data == null) {
82             return "";
83         }
84         ByteArrayInputStream input = null;
85         GZIPInputStream gzis = null;
86         InputStreamReader reader = null;
87         final StringBuilder out = new StringBuilder();
88         try {
89             input = new ByteArrayInputStream(data);
90             gzis = new GZIPInputStream(input);
91             reader = new InputStreamReader(gzis, Charset.forName(RestfulClientConst.ENCODING));
92             final char[] buff = new char[1024];
93             for(int n; (n = reader.read(buff)) != -1;) {
94                 out.append(new String(buff, 0, n));
95             }
96         } finally {
97             if(reader != null) {
98                 try {
99                     reader.close();
100                 } catch(final IOException e) {
101                     LOGGER.error("decompress Gzip reader exception:", e);
102                 }
103             }
104             if(gzis != null) {
105                 try {
106                     gzis.close();
107                 } catch(final IOException e) {
108                     LOGGER.error("decompress Gzip exception:", e);
109                 }
110             }
111             if(input != null) {
112                 try {
113                     input.close();
114                 } catch(final IOException e) {
115                     LOGGER.error("decompress Gzip input exception:", e);
116                 }
117             }
118         }
119         return out.toString();
120
121     }
122
123     /**
124      * View response headers Content-Encoding values if you need to extract data.<br/>
125      * 
126      * @param name buffer
127      * @param value value
128      * @throws IOException
129      * @since
130      */
131     @Override
132     protected synchronized void onResponseHeader(final Buffer name, final Buffer value) throws IOException {
133         super.onResponseHeader(name, value);
134         final int header = HttpHeaders.CACHE.getOrdinal(name);
135         if(header == HttpHeaders.CONTENT_ENCODING_ORDINAL) {
136             final String encoding = StringUtil.asciiToLowerCase(value.toString());
137             gzip = encoding != null && StringUtils.contains(encoding, "gzip");
138         }
139
140     }
141
142     @Override
143     protected void onResponseComplete() throws IOException {
144         if(LOGGER.isInfoEnabled()) {
145             LOGGER.info("Response has Complete:" + PATH + this.getRequestURI().replace("\n", "0x0A"));
146         }
147         super.onResponseComplete();
148         if(callback != null) {
149             final RestfulResponse rsp = getResponse();
150             callback.callback(rsp);
151         }
152     }
153
154     @Override
155     protected void onRequestCommitted() throws IOException {
156         if(LOGGER.isInfoEnabled()) {
157             LOGGER.info("Request Header has been send:" + PATH + this.getRequestURI().replace("\n", "0x0A"));
158         }
159         super.onRequestCommitted();
160     }
161
162     @Override
163     protected void onRequestComplete() throws IOException {
164         if(LOGGER.isInfoEnabled()) {
165             LOGGER.info("Request has bend send complete:" + PATH + this.getRequestURI().replace("\n", "0x0A"));
166         }
167         super.onRequestComplete();
168     }
169
170     @Override
171     protected void onException(final Throwable x) {
172         LOGGER.warn("onException:", x);
173         super.onException(x);
174         if(callback != null) {
175             callback.handleExcepion(x);
176         }
177     }
178
179     @Override
180     protected void onConnectionFailed(final Throwable x) {
181         LOGGER.warn("onConnectionFailed:", x);
182         super.onConnectionFailed(x);
183         if(callback != null) {
184             callback.handleExcepion(x);
185         }
186
187     }
188
189     @Override
190     protected void expire(final HttpDestination destination) {
191         super.expire(destination);
192         if(callback != null) {
193             callback.handleExcepion(new ServiceException("request is expired, status:" + toState(getStatus())));
194         }
195     }
196
197     public boolean isGzip() {
198         return gzip;
199     }
200
201     /**
202      * Get the response as RestfulResponse.
203      * <br/>
204      * 
205      * @return response object.
206      * @throws IOException
207      * @since
208      */
209     public RestfulResponse getResponse() throws IOException {
210         final RestfulResponse rsp = new RestfulResponse();
211         rsp.setStatus(this.getResponseStatus());
212         if(isGzip()) {
213             final String responseString = decompressGzipToStr(getResponseContentBytes());
214             rsp.setResponseJson(responseString);
215         } else {
216             rsp.setResponseJson(this.getResponseContent());
217         }
218
219         final HttpFields field = this.getResponseFields();
220         if(field != null) {
221             final Map<String, String> header = new HashMap<>();
222
223             final Enumeration<String> names = field.getFieldNames();
224             for(final Enumeration<String> e = names; e.hasMoreElements();) {
225                 final String fieldName = e.nextElement();
226                 final String fieldValue = field.getStringField(fieldName);
227                 header.put(fieldName, fieldValue);
228             }
229
230             rsp.setRespHeaderMap(header);
231         }
232         return rsp;
233     }
234
235 }