2  * Copyright 2016 Huawei Technologies Co., Ltd.
 
   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
 
   8  *     http://www.apache.org/licenses/LICENSE-2.0
 
  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.
 
  17 package org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient;
 
  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;
 
  26 import java.util.zip.GZIPInputStream;
 
  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;
 
  39  * ContentExchange implementation classe to provide access to response.
 
  45  * @version 28-May-2016
 
  47 public class RestHttpContentExchange extends ContentExchange {
 
  49     private static final Logger LOGGER = LoggerFactory.getLogger(RestHttpContentExchange.class);
 
  51     private static final String PATH = "path:";
 
  53     private boolean gzip = false;
 
  55     private RestfulAsyncCallback callback = null;
 
  63      * @param cacheFields whether to cache response header.
 
  64      * @param asyncCallback callback method.
 
  66     RestHttpContentExchange(final boolean cacheFields, final RestfulAsyncCallback asyncCallback) {
 
  68         this.callback = asyncCallback;
 
  75      * @param data GZipped data.
 
  76      * @return Uncompressed data.
 
  80     public String decompressGzipToStr(final byte[] data) throws IOException {
 
  84         final StringBuilder out = new StringBuilder();
 
  85         try (ByteArrayInputStream input = new ByteArrayInputStream(data);
 
  86              GZIPInputStream gzis = new GZIPInputStream(input);
 
  87              InputStreamReader reader = new InputStreamReader(gzis, Charset.forName(RestfulClientConst.ENCODING));) {
 
  88             final char[] buff = new char[1024];
 
  89             for(int n; (n = reader.read(buff)) != -1;) {
 
  90                 out.append(new String(buff, 0, n));
 
  93         return out.toString();
 
  98      * View response headers Content-Encoding values if you need to extract data.<br/>
 
 102      * @throws IOException
 
 106     protected synchronized void onResponseHeader(final Buffer name, final Buffer value) throws IOException {
 
 107         super.onResponseHeader(name, value);
 
 108         final int header = HttpHeaders.CACHE.getOrdinal(name);
 
 109         if(header == HttpHeaders.CONTENT_ENCODING_ORDINAL) {
 
 110             final String encoding = StringUtil.asciiToLowerCase(value.toString());
 
 111             gzip = encoding != null && StringUtils.contains(encoding, "gzip");
 
 117     protected void onResponseComplete() throws IOException {
 
 118         if(LOGGER.isInfoEnabled()) {
 
 119             LOGGER.info("Response has Complete:" + PATH + this.getRequestURI().replace("\n", "0x0A"));
 
 121         super.onResponseComplete();
 
 122         if(callback != null) {
 
 123             final RestfulResponse rsp = getResponse();
 
 124             callback.callback(rsp);
 
 129     protected void onRequestCommitted() throws IOException {
 
 130         if(LOGGER.isInfoEnabled()) {
 
 131             LOGGER.info("Request Header has been send:" + PATH + this.getRequestURI().replace("\n", "0x0A"));
 
 133         super.onRequestCommitted();
 
 137     protected void onRequestComplete() throws IOException {
 
 138         if(LOGGER.isInfoEnabled()) {
 
 139             LOGGER.info("Request has bend send complete:" + PATH + this.getRequestURI().replace("\n", "0x0A"));
 
 141         super.onRequestComplete();
 
 145     protected void onException(final Throwable x) {
 
 146         LOGGER.warn("onException:", x);
 
 147         super.onException(x);
 
 148         if(callback != null) {
 
 149             callback.handleExcepion(x);
 
 154     protected void onConnectionFailed(final Throwable x) {
 
 155         LOGGER.warn("onConnectionFailed:", x);
 
 156         super.onConnectionFailed(x);
 
 157         if(callback != null) {
 
 158             callback.handleExcepion(x);
 
 164     protected void expire(final HttpDestination destination) {
 
 165         super.expire(destination);
 
 166         if(callback != null) {
 
 167             callback.handleExcepion(new ServiceException("request is expired, status:" + toState(getStatus())));
 
 171     public boolean isGzip() {
 
 176      * Get the response as RestfulResponse.
 
 179      * @return response object.
 
 180      * @throws IOException
 
 183     public RestfulResponse getResponse() throws IOException {
 
 184         final RestfulResponse rsp = new RestfulResponse();
 
 185         rsp.setStatus(this.getResponseStatus());
 
 187             final String responseString = decompressGzipToStr(getResponseContentBytes());
 
 188             rsp.setResponseJson(responseString);
 
 190             rsp.setResponseJson(this.getResponseContent());
 
 193         final HttpFields field = this.getResponseFields();
 
 195             final Map<String, String> header = new HashMap<>();
 
 197             final Enumeration<String> names = field.getFieldNames();
 
 198             for(final Enumeration<String> e = names; e.hasMoreElements();) {
 
 199                 final String fieldName = e.nextElement();
 
 200                 final String fieldValue = field.getStringField(fieldName);
 
 201                 header.put(fieldName, fieldValue);
 
 204             rsp.setRespHeaderMap(header);