Code Smells in jujuvnfmadapter utils
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / gvnfm / jujuvnfmadapter / 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.gvnfm.jujuvnfmadapter.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         final StringBuilder out = new StringBuilder();
83         try (
84             ByteArrayInputStream    input = new ByteArrayInputStream(data);
85             GZIPInputStream  gzis = new GZIPInputStream(input);
86             InputStreamReader reader = new InputStreamReader(gzis, Charset.forName(RestfulClientConst.ENCODING))){
87             final char[] buff = new char[1024];
88             for(int n; (n = reader.read(buff)) != -1;) {
89                 out.append(new String(buff, 0, n));
90             }
91         } 
92         return out.toString();
93
94     }
95
96     /**
97      * View response headers Content-Encoding values if you need to extract data.<br/>
98      * 
99      * @param name buffer
100      * @param value value
101      * @throws IOException
102      * @since
103      */
104     @Override
105     protected synchronized void onResponseHeader(final Buffer name, final Buffer value) throws IOException {
106         super.onResponseHeader(name, value);
107         final int header = HttpHeaders.CACHE.getOrdinal(name);
108         if(header == HttpHeaders.CONTENT_ENCODING_ORDINAL) {
109             final String encoding = StringUtil.asciiToLowerCase(value.toString());
110             gzip = encoding != null && StringUtils.contains(encoding, "gzip");
111         }
112
113     }
114
115     @Override
116     protected void onResponseComplete() throws IOException {
117         if(LOGGER.isInfoEnabled()) {
118             LOGGER.info("Response has Complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
119         }
120         super.onResponseComplete();
121         if(callback != null) {
122             final RestfulResponse rsp = getResponse();
123             callback.callback(rsp);
124         }
125     }
126
127     @Override
128     protected void onRequestCommitted() throws IOException {
129         if(LOGGER.isInfoEnabled()) {
130             LOGGER.info("Request Header has been send:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
131         }
132         super.onRequestCommitted();
133     }
134
135     @Override
136     protected void onRequestComplete() throws IOException {
137         if(LOGGER.isInfoEnabled()) {
138             LOGGER.info("Request has bend send complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
139         }
140         super.onRequestComplete();
141     }
142
143     @Override
144     protected void onException(final Throwable x) {
145         LOGGER.warn("onException:", x);
146         super.onException(x);
147         if(callback != null) {
148             callback.handleExcepion(x);
149         }
150     }
151
152     @Override
153     protected void onConnectionFailed(final Throwable x) {
154         LOGGER.warn("onConnectionFailed:", x);
155         super.onConnectionFailed(x);
156         if(callback != null) {
157             callback.handleExcepion(x);
158         }
159
160     }
161
162     @Override
163     protected void expire(final HttpDestination destination) {
164         super.expire(destination);
165         if(callback != null) {
166             callback.handleExcepion(new ServiceException("request is expired, status:" + toState(getStatus())));
167         }
168     }
169
170     public boolean isGzip() {
171         return gzip;
172     }
173
174     /**
175      * Get the response as RestfulResponse.
176      * <br/>
177      * 
178      * @return response object.
179      * @throws IOException
180      * @since
181      */
182     public RestfulResponse getResponse() throws IOException {
183         final RestfulResponse rsp = new RestfulResponse();
184         rsp.setStatus(this.getResponseStatus());
185         if(isGzip()) {
186             final String responseString = decompressGzipToStr(getResponseContentBytes());
187             rsp.setResponseJson(responseString);
188         } else {
189             rsp.setResponseJson(this.getResponseContent());
190         }
191
192         final HttpFields field = this.getResponseFields();
193         if(field != null) {
194             final Map<String, String> header = new HashMap<>();
195
196             final Enumeration<String> names = field.getFieldNames();
197             for(final Enumeration<String> e = names; e.hasMoreElements();) {
198                 final String fieldName = e.nextElement();
199                 final String fieldValue = field.getStringField(fieldName);
200                 header.put(fieldName, fieldValue);
201             }
202
203             rsp.setRespHeaderMap(header);
204         }
205         return rsp;
206     }
207
208 }