diff options
author | victor.gao <victor.gao@huawei.com> | 2018-03-28 14:09:30 +0800 |
---|---|---|
committer | victor.gao <victor.gao@huawei.com> | 2018-03-28 14:09:30 +0800 |
commit | d0fdea0fe26cce07924606dbcefa21b9116a7f0c (patch) | |
tree | e91f42288023deaf74cc8bdf08d3206081f4b6f4 /service | |
parent | fd6abf9f3c76a4e2eedc45f007e001427b8b0eae (diff) |
Add multivimproxy util code
Change-Id: I969f6b0fd05bc6706461e60a93235ee5d6bf81db
Issue-ID: VFC-644
Signed-off-by: victor.gao <victor.gao@huawei.com>
Diffstat (limited to 'service')
22 files changed, 3245 insertions, 0 deletions
diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/request/RequestUtil.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/request/RequestUtil.java new file mode 100644 index 0000000..3bda627 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/request/RequestUtil.java @@ -0,0 +1,174 @@ +/* + * 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.request; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulClientConst; +import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulParametes; +import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * Utility used for request + * </p> + * + * @author + * @version VFC 1.0 2016-3-17 + */ +public final class RequestUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class); + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since VFC 1.0 + */ + private RequestUtil() { + } + + /** + * Get context string from http context + * + * @param context + * http context + * @return the needed string in http context + */ + public static String getStringRequestBody(HttpServletRequest context) { + try { + InputStream input = context.getInputStream(); + return IOUtils.toString(input); + } catch(IOException e) { + LOGGER.error("function=getStringRequestBody, get httpservletrequest body exception: {}", e); + return null; + } + } + + /** + * Get json parameter from http context + * + * @param context + * http context + * @return JSONObject + */ + public static JSONObject getJsonRequestBody(HttpServletRequest context) { + try { + String bodyStr = getStringRequestBody(context); + return JSONObject.fromObject(bodyStr); + } catch(JSONException e) { + LOGGER.error("function=getJsonRequestBody, maybe request param is not a jsonobject exception: {}", e); + return null; + } + } + + /** + * Get the body of all request in json format<br/> + * + * @param context + * The http context + * @return JSONObject The body of all request in json format + * @since VFC 1.0 + */ + public static JSONObject getAllJsonRequestBody(HttpServletRequest context) { + JSONObject requestBody = getJsonRequestBody(context); + if(null == requestBody) { + LOGGER.error("get httpservletrequest body exception"); + requestBody = new JSONObject(); + } + LOGGER.warn("function=getAllJsonRequestBody; msg=get request data is:[{}]", requestBody.toString()); + requestBody.put("header", getContextHeader(context)); + return requestBody; + } + + /** + * Get the context header<br/> + * + * @param context + * The http context + * @return Map context header + * @since VFC 1.0 + */ + @SuppressWarnings("unchecked") + private static Map<String, String> getContextHeader(HttpServletRequest context) { + Map<String, String> header = new HashMap<>(); + Enumeration<String> headerNames = context.getHeaderNames(); + while(headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + String value = context.getHeader(headerName); + header.put(headerName, value); + } + return header; + } + + public static 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) { + LOGGER.error("unsupported encoding: ", ex); + throw new ServiceException("Broken VM does not support UTF-8"); + } + return builder.toString(); + } + + public static Map<String, String> getAAIHeaderMap() { + HashMap<String, String> headerMap = new HashMap<>(); + headerMap.put("X-TransactionId", "9999"); + headerMap.put("X-FromAppId", "jimmy"); + headerMap.put("Real-Time", "true"); + headerMap.put("Authorization", "Basic QUFJOkFBSQ=="); + headerMap.put("Accept", "application/json"); + headerMap.put("Content-Type", "application/json"); + return headerMap; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/response/ResponseUtil.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/response/ResponseUtil.java new file mode 100644 index 0000000..0e1a109 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/response/ResponseUtil.java @@ -0,0 +1,130 @@ +/* + * 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.response; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import javax.servlet.http.HttpServletRequest; + +import net.sf.json.JSONObject; + +/** + * + * Response utility class.<br> + * <p> + * </p> + * + * @author + * @version VFC 1.0 Sep 10, 2016 + */ +public final class ResponseUtil { + + private ResponseUtil() { + } + + /** + * Roa request common return function, default return code 200 <br/> + * + * @param retCode + * The request return code + * @param msg + * The request message + * @return JSONObject The response for http request + * @since VFC 1.0 + */ + public static JSONObject genHttpResponse(int retCode, String msg) { + return genHttpResponse(createCodeMap(-1, retCode), msg, null); + } + + /** + * Roa request common return function, default return code 200<br/> + * + * @param retCode + * The request return code + * @param msg + * The request message + * @param map + * Other request info of this request + * @return JSONObject The response for http request + * @since VFC 1.0 + */ + public static JSONObject genHttpResponse(int retCode, String msg, Map<String, Object> map) { + return genHttpResponse(createCodeMap(-1, retCode), msg, map); + } + + /** + * Roa request common return method <br/> + * + * @param httpStatusCode + * The http response code + * @param retCode + * The http request return code + * @param msg + * The message of request + * @return JSONObject The response for http request + * @since VFC 1.0 + */ + public static JSONObject genHttpResponse(int httpStatusCode, int retCode, String msg) { + return genHttpResponse(createCodeMap(httpStatusCode, retCode), msg, null); + } + + /** + * + * Roa request common return method.<br> + * + * @param codeMap + * @param msg, The message of request + * @param map, Other message of request + * @return + * @since VFC 1.0 + */ + public static JSONObject genHttpResponse(Map<String, Integer> codeMap, String msg, + Map<String, Object> map) { + JSONObject object = new JSONObject(); + + object.put("msg", msg); + if(null != map) { + Iterator<Entry<String, Object>> ite = map.entrySet().iterator(); + if(ite.hasNext()) { + Map.Entry<String, Object> entry = ite.next(); + object.put(entry.getKey(), entry.getValue().toString()); + } + } + return object; + } + + /** + * Create code map to maintenance the relationship between return code and + * http status code <br/> + * + * @param httpStatusCode + * The http response code + * @param retCode + * The http request return code + * @return Map + * @since VFC 1.0 + */ + private static Map<String, Integer> createCodeMap(int httpStatusCode, int retCode) { + Map<String, Integer> codeMap = new HashMap<>(5); + codeMap.put("httpStatusCode", httpStatusCode); + codeMap.put("retCode", retCode); + return codeMap; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/response/RoaResponseUtil.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/response/RoaResponseUtil.java new file mode 100644 index 0000000..4ab7b2a --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/response/RoaResponseUtil.java @@ -0,0 +1,113 @@ +/* + * 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.response; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.vfc.nfvo.multivimproxy.common.constant.HttpConstant; +import org.onap.vfc.nfvo.multivimproxy.common.constant.ParamConstant; +import org.onap.vfc.nfvo.multivimproxy.common.constant.ResponseConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * Utility for generate Roa get/add/update/delete method status + * </p> + * + * @author + * @version VFC 1.0 2016-3-17 + */ +public final class RoaResponseUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(RoaResponseUtil.class); + + private RoaResponseUtil() { + + } + + /** + * Generate get method response<br/> + * + * @param list + * The basic response for get method + * @return JSONObject The response for http request + * @since VFC 1.0 + */ + public static <T> JSONObject get(List<T> list) { + Map<String, Object> map = new HashMap<>(10); + map.put(ParamConstant.PARAM_DATA, list); + LOGGER.info("function=get; msg=get map:{}", map.toString()); + return ResponseUtil.genHttpResponse(HttpConstant.OK_CODE, ResponseConstant.QUERY_SUCESS_MSG, map); + } + + /** + * Generate different response by different parameter for add method <br/> + * + * @param result + * The result + * @return JSONObject + * @since VFC 1.0 + */ + public static JSONObject add(int result) { + LOGGER.info("function=add; msg=add result{}", result); + if(result <= 0) { + return ResponseUtil.genHttpResponse(HttpConstant.ERROR_CODE, ResponseConstant.ADD_FAIL_MSG); + } else { + return ResponseUtil.genHttpResponse(HttpConstant.OK_CODE, ResponseConstant.ADD_SUCESS_MSG); + } + } + + /** + * Generate different response by different parameter for update method <br/> + * + * @param result + * The result + * @return JSONObject The response for http request + * @since VFC 1.0 + */ + public static JSONObject update(int result) { + LOGGER.info("function=update; msg=update result{}", result); + if(result <= 0) { + return ResponseUtil.genHttpResponse(HttpConstant.ERROR_CODE, ResponseConstant.MOD_FAIL_MSG); + } else { + return ResponseUtil.genHttpResponse(HttpConstant.OK_CODE, ResponseConstant.MOD_SUCESS_MSG); + } + } + + /** + * Generate different response by different parameter for delete method <br/> + * + * @param result + * The result + * @return delete JSONObject of the response for http request + * @since VFC 1.0 + */ + public static JSONObject delete(int result) { + LOGGER.info("function=delete; msg=delete result{}", result); + if(result <= 0) { + return ResponseUtil.genHttpResponse(HttpConstant.ERROR_CODE, ResponseConstant.DEL_FAIL_MSG); + } else { + return ResponseUtil.genHttpResponse(HttpConstant.OK_CODE, ResponseConstant.DEL_SUCESS_MSG); + } + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/DefaultAsyncCallback.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/DefaultAsyncCallback.java new file mode 100644 index 0000000..13d0611 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/DefaultAsyncCallback.java @@ -0,0 +1,38 @@ +/* + * 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; + +/** + * Restful Asynchronous call back implentation.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class DefaultAsyncCallback implements RestfulAsyncCallback { + + @Override + public void callback(final RestfulResponse response) { + // default implementation. + } + + @Override + public void handleExcepion(final Throwable e) { + // default implementation + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ExceptionArgs.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ExceptionArgs.java new file mode 100644 index 0000000..b420884 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ExceptionArgs.java @@ -0,0 +1,111 @@ +/* + * 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; + +/** + * ROA exception handling parameters. + * <br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class ExceptionArgs { + + /** + * Exception descriptions. + */ + private String[] descArgs = null; + + /** + * Exception reasons. + */ + private String[] reasonArgs = null; + + /** + * Exception detals. + */ + private String[] detailArgs = null; + + /** + * Exception advices. + */ + private String[] adviceArgs = null; + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + */ + public ExceptionArgs() { + // default constructor. + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param descArgs: descriptions. + * @param reasonArgs: reasons. + * @param detailArgs: details. + * @param adviceArgs: advices. + */ + public ExceptionArgs(final String[] descArgs, final String[] reasonArgs, final String[] detailArgs, + final String[] adviceArgs) { + this.descArgs = descArgs; + this.reasonArgs = reasonArgs; + this.detailArgs = detailArgs; + this.adviceArgs = adviceArgs; + } + + public String[] getDescArgs() { + return descArgs; + } + + public void setDescArgs(final String[] descArgs) { + this.descArgs = descArgs; + } + + public String[] getReasonArgs() { + return reasonArgs; + } + + public void setReasonArgs(final String[] reasonArgs) { + this.reasonArgs = reasonArgs; + } + + public String[] getDetailArgs() { + return detailArgs; + } + + public void setDetailArgs(final String[] detailArgs) { + this.detailArgs = detailArgs; + } + + public String[] getAdviceArgs() { + return adviceArgs; + } + + public void setAdviceArgs(final String[] adviceArgs) { + this.adviceArgs = adviceArgs; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpBaseRest.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpBaseRest.java new file mode 100644 index 0000000..89a5dd6 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpBaseRest.java @@ -0,0 +1,272 @@ +/* + * 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.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.eclipse.jetty.client.Address; +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.HttpExchange; +import org.eclipse.jetty.http.HttpMethods; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version Aug 9, 2016 + */ +public abstract class HttpBaseRest implements Restful { + + private static final Logger LOG = LoggerFactory.getLogger(HttpRest.class); + + final AtomicInteger requestId = new AtomicInteger(0); + + protected HttpClient client = null; + + private static final String LOCAL_HOST = "127.0.0.1"; + + 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; + } + +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpRest.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpRest.java new file mode 100644 index 0000000..30a7c4b --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpRest.java @@ -0,0 +1,253 @@ +/* + * 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 org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.http.HttpMethods; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version Aug 9, 2016 + */ +public class HttpRest extends HttpBaseRest { + + private static final Logger LOG = LoggerFactory.getLogger(HttpRest.class); + + /** + * Initializing Rest options.<br/> + * + * @param options: rest options. + * @throws ServiceException + * @since + */ + public void initHttpRest(final RestfulOptions option) throws ServiceException { + if(option == null) { + client = null; + throw new ServiceException("option is null."); + } + createHttpClient(); + try { + int iValue; + iValue = option.getIntOption(RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME); + // max 200 concurrent,connections to every address + client.setMaxConnectionsPerAddress(iValue); + + iValue = option.getIntOption(RestfulClientConst.THREAD_KEY_NAME); + // max threads + client.setThreadPool(new QueuedThreadPool(iValue)); + iValue = option.getIntOption(RestfulClientConst.CONN_TIMEOUT_KEY_NAME); + client.setConnectTimeout(iValue); + iValue = option.getRestTimeout(); + defaultTimeout = iValue; + client.setTimeout(iValue); + + iValue = option.getIntOption(RestfulClientConst.IDLE_TIMEOUT_KEY_NAME); + client.setIdleTimeout(iValue); + iValue = option.getIntOption(RestfulClientConst.MAX_RESPONSE_HEADER_SIZE); + client.setResponseHeaderSize(iValue); + iValue = option.getIntOption(RestfulClientConst.MAX_REQUEST_HEADER_SIZE); + client.setRequestHeaderSize(iValue); + // HttpClient.CONNECTOR_SOCKET + client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL); + client.start(); + defaultIP = option.getStringOption(RestfulClientConst.HOST_KEY_NAME); + defaultPort = option.getIntOption(RestfulClientConst.PORT_KEY_NAME); + } catch(final Exception e) { + LOG.error("start httpclient error", e); + client = null; + throw new ServiceException("http client init failed."); + } + } + + @Override + public RestfulResponse get(final String servicePath, final RestfulParametes restParametes) throws ServiceException { + return this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse get(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, null); + } + + @Override + public RestfulResponse head(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HttpMethods.HEAD, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse head(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.HEAD, servicePath, restParametes, option, null); + } + + @Override + public void asyncGet(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncGet(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse put(final String servicePath, final RestfulParametes restParametes) throws ServiceException { + return this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse put(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, null); + } + + @Override + public void asyncPut(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncPut(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse post(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse post(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, null); + } + + @Override + public void asyncPost(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncPost(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse delete(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse delete(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, null); + } + + @Override + public void asyncDelete(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncDelete(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse patch(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse patch(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, null); + } + + @Override + public void asyncPatch(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncPatch(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, callback); + } + } + +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpsRest.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpsRest.java new file mode 100644 index 0000000..7190c56 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/HttpsRest.java @@ -0,0 +1,288 @@ +/* + * Copyright 2017 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.IOException; +import java.io.UnsupportedEncodingException; + +import org.eclipse.jetty.client.ContentExchange; +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.HttpExchange; +import org.eclipse.jetty.io.ByteArrayBuffer; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.onap.vfc.nfvo.multivimproxy.common.util.request.RequestUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpsRest extends HttpBaseRest { + + private static final Logger LOG = LoggerFactory.getLogger(HttpsRest.class); + + public void initHttpsRest() { + SslContextFactory sslContextFactory = new SslContextFactory(); + client = new HttpClient(sslContextFactory); + client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL); + client.setMaxConnectionsPerAddress(200); // max 200 concurrent connections to every address + client.setThreadPool(new QueuedThreadPool(250)); // max 250 threads + client.setTimeout(30000); // 30 seconds timeout; if no server reply, the request expires + try { + client.start(); + } catch(Exception e) { + e.printStackTrace(); + } + } + + @Override + public RestfulResponse get(String servicePath, RestfulParametes restParametes) throws ServiceException { + return null; + } + + @Override + public RestfulResponse head(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException { + return null; + } + + @Override + public RestfulResponse head(String servicePath, RestfulParametes restParametes) throws ServiceException { + return null; + } + + @Override + public void asyncGet(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException { + + } + + @Override + public void asyncGet(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException { + + } + + @Override + public RestfulResponse put(String servicePath, RestfulParametes restParametes) throws ServiceException { + return null; + } + + @Override + public void asyncPut(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException { + + } + + @Override + public void asyncPut(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException { + + } + + @Override + public RestfulResponse post(String servicePath, RestfulParametes restParametes) throws ServiceException { + return null; + } + + @Override + public RestfulResponse post(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException { + return null; + } + + @Override + public void asyncPost(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException { + + } + + @Override + public void asyncPost(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException { + + } + + @Override + public RestfulResponse delete(String servicePath, RestfulParametes restParametes) throws ServiceException { + return null; + } + + @Override + public void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException { + + } + + @Override + public void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException { + + } + + @Override + public RestfulResponse patch(String servicePath, RestfulParametes restParametes) throws ServiceException { + return null; + } + + @Override + public RestfulResponse patch(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException { + return null; + } + + @Override + public void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException { + + } + + @Override + public void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException { + + } + + @Override + public RestfulResponse get(String servicePath, RestfulParametes restParametes, RestfulOptions option) + throws ServiceException { + ContentExchange exchange = new ContentExchange(true); + exchange.setURL(servicePath); + exchange.setMethod("GET"); + restParametes.getHeaderMap().entrySet().stream() + .forEach(entry -> exchange.setRequestHeader(entry.getKey(), entry.getValue())); + + try { + client.send(exchange); + } catch(IOException e) { + e.printStackTrace(); + } + try { + int exchangeState = exchange.waitForDone(); + if(exchangeState == HttpExchange.STATUS_COMPLETED) { + String res = exchange.getResponseContent(); + LOG.info(res); + + RestfulResponse restfulResponse = new RestfulResponse(); + restfulResponse.setResponseJson(exchange.getResponseContent()); + restfulResponse.setStatus(exchange.getResponseStatus()); + return restfulResponse; + } 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)); + } + } catch(InterruptedException e) { + e.printStackTrace(); + } catch(UnsupportedEncodingException e) { + e.printStackTrace(); + } + return null; + } + + @Override + public RestfulResponse put(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException { + ContentExchange exchange = new ContentExchange(true); + exchange.setURL(servicePath); + exchange.setMethod("PUT"); + exchange.setRequestContent(new ByteArrayBuffer(restParametes.getRawData())); + + restParametes.getHeaderMap().entrySet().stream() + .forEach(entry -> exchange.setRequestHeader(entry.getKey(), entry.getValue())); + + try { + client.send(exchange); + } catch(IOException e) { + e.printStackTrace(); + } + + try { + int exchangeState = exchange.waitForDone(); + if(exchangeState == HttpExchange.STATUS_COMPLETED) { + String res = exchange.getResponseContent(); + LOG.info(res); + + RestfulResponse restfulResponse = new RestfulResponse(); + restfulResponse.setResponseJson(exchange.getResponseContent()); + restfulResponse.setStatus(exchange.getResponseStatus()); + return restfulResponse; + } 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)); + } + } catch(InterruptedException e) { + e.printStackTrace(); + } catch(UnsupportedEncodingException e) { + e.printStackTrace(); + } + return null; + } + + @Override + public RestfulResponse delete(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException { + ContentExchange exchange = new ContentExchange(true); + + String encodeParams = RequestUtil.encodeParams(restParametes); + if(encodeParams.isEmpty()) { + exchange.setURL(servicePath); + } else { + exchange.setURL(servicePath + "?" + encodeParams); + } + exchange.setMethod("DELETE"); + if(restParametes.getRawData() != null) { + exchange.setRequestContent(new ByteArrayBuffer(restParametes.getRawData())); + } + + restParametes.getHeaderMap().entrySet().stream() + .forEach(entry -> exchange.setRequestHeader(entry.getKey(), entry.getValue())); + + try { + client.send(exchange); + } catch(IOException e) { + e.printStackTrace(); + } + + try { + int exchangeState = exchange.waitForDone(); + if(exchangeState == HttpExchange.STATUS_COMPLETED) { + String res = exchange.getResponseContent(); + LOG.info(res); + + RestfulResponse restfulResponse = new RestfulResponse(); + restfulResponse.setResponseJson(exchange.getResponseContent()); + restfulResponse.setStatus(exchange.getResponseStatus()); + return restfulResponse; + } 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)); + } + } catch(InterruptedException e) { + e.printStackTrace(); + } catch(UnsupportedEncodingException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ReaderHelper.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ReaderHelper.java new file mode 100644 index 0000000..8202d24 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ReaderHelper.java @@ -0,0 +1,62 @@ +/* + * 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.Reader; + +import org.apache.commons.io.LineIterator; + +/** + * Helper for read line.<br/> + * <p> + * </p> + * + * @author + * @version 31-May-2016 + */ +public class ReaderHelper { + + private LineIterator ite = null; + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param reader + */ + public ReaderHelper(final Reader reader) { + if(reader != null) { + ite = new LineIterator(reader); + } + + } + + /** + * Gets the next line.<br/> + * + * @return line if present else null. + * @since + */ + public String getLine() { + if(ite != null && ite.hasNext()) { + return ite.nextLine(); + } + return null; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestHttpContentExchange.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestHttpContentExchange.java new file mode 100644 index 0000000..d6e4643 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestHttpContentExchange.java @@ -0,0 +1,233 @@ +/* + * 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.InputStreamReader; +import java.nio.charset.Charset; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import org.apache.commons.lang.StringUtils; +import org.eclipse.jetty.client.ContentExchange; +import org.eclipse.jetty.client.HttpDestination; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeaders; +import org.eclipse.jetty.io.Buffer; +import org.eclipse.jetty.util.StringUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ContentExchange implementation classe to provide access to response. + * <br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class RestHttpContentExchange extends ContentExchange { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestHttpContentExchange.class); + + private boolean gzip = false; + + private RestfulAsyncCallback callback = null; + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param cacheFields whether to cache response header. + * @param asyncCallback callback method. + */ + RestHttpContentExchange(final boolean cacheFields, final RestfulAsyncCallback asyncCallback) { + super(cacheFields); + this.callback = asyncCallback; + } + + /** + * Extract message. + * <br/> + * + * @param data GZipped data. + * @return Uncompressed data. + * @throws IOException + * @since + */ + public String decompressGzipToStr(final byte[] data) throws IOException { + if(data == null) { + return ""; + } + ByteArrayInputStream input = null; + GZIPInputStream gzis = null; + InputStreamReader reader = null; + final StringBuilder out = new StringBuilder(); + try { + input = new ByteArrayInputStream(data); + gzis = new GZIPInputStream(input); + reader = new InputStreamReader(gzis, Charset.forName(RestfulClientConst.ENCODING)); + final char[] buff = new char[1024]; + for(int n; (n = reader.read(buff)) != -1;) { + out.append(new String(buff, 0, n)); + } + } finally { + if(reader != null) { + try { + reader.close(); + } catch(final IOException e) { + LOGGER.error("decompress Gzip reader exception:", e); + } + } + if(gzis != null) { + try { + gzis.close(); + } catch(final IOException e) { + LOGGER.error("decompress Gzip exception:", e); + } + } + if(input != null) { + try { + input.close(); + } catch(final IOException e) { + LOGGER.error("decompress Gzip input exception:", e); + } + } + } + return out.toString(); + + } + + /** + * View response headers Content-Encoding values if you need to extract data.<br/> + * + * @param name buffer + * @param value value + * @throws IOException + * @since + */ + @Override + protected synchronized void onResponseHeader(final Buffer name, final Buffer value) throws IOException { + super.onResponseHeader(name, value); + final int header = HttpHeaders.CACHE.getOrdinal(name); + if(header == HttpHeaders.CONTENT_ENCODING_ORDINAL) { + final String encoding = StringUtil.asciiToLowerCase(value.toString()); + gzip = encoding != null && StringUtils.contains(encoding, "gzip"); + } + + } + + @Override + protected void onResponseComplete() throws IOException { + if(LOGGER.isInfoEnabled()) { + LOGGER.info("Response has Complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A")); + } + super.onResponseComplete(); + if(callback != null) { + final RestfulResponse rsp = getResponse(); + callback.callback(rsp); + } + } + + @Override + protected void onRequestCommitted() throws IOException { + if(LOGGER.isInfoEnabled()) { + LOGGER.info("Request Header has been send:" + "path:" + this.getRequestURI().replace("\n", "0x0A")); + } + super.onRequestCommitted(); + } + + @Override + protected void onRequestComplete() throws IOException { + if(LOGGER.isInfoEnabled()) { + LOGGER.info("Request has bend send complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A")); + } + super.onRequestComplete(); + } + + @Override + protected void onException(final Throwable x) { + LOGGER.warn("onException:", x); + super.onException(x); + if(callback != null) { + callback.handleExcepion(x); + } + } + + @Override + protected void onConnectionFailed(final Throwable x) { + LOGGER.warn("onConnectionFailed:", x); + super.onConnectionFailed(x); + if(callback != null) { + callback.handleExcepion(x); + } + + } + + @Override + protected void expire(final HttpDestination destination) { + super.expire(destination); + if(callback != null) { + callback.handleExcepion(new ServiceException("request is expired, status:" + toState(getStatus()))); + } + } + + public boolean isGzip() { + return gzip; + } + + /** + * Get the response as RestfulResponse. + * <br/> + * + * @return response object. + * @throws IOException + * @since + */ + public RestfulResponse getResponse() throws IOException { + final RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(this.getResponseStatus()); + if(isGzip()) { + final String responseString = decompressGzipToStr(getResponseContentBytes()); + rsp.setResponseJson(responseString); + } else { + rsp.setResponseJson(this.getResponseContent()); + } + + final HttpFields field = this.getResponseFields(); + if(field != null) { + final Map<String, String> header = new HashMap<>(); + + final Enumeration<String> names = field.getFieldNames(); + for(final Enumeration<String> e = names; e.hasMoreElements();) { + final String fieldName = e.nextElement(); + final String fieldValue = field.getStringField(fieldName); + header.put(fieldName, fieldValue); + } + + rsp.setRespHeaderMap(header); + } + return rsp; + } + +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/Restful.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/Restful.java new file mode 100644 index 0000000..e3d0825 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/Restful.java @@ -0,0 +1,297 @@ +/* + * 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; + +/** + * ReSTful method interface.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public interface Restful { + + /** + * Http GET method.<br/> + * + * @param servicePath: request path. + * @param restParametes: query parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse get(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http HEAD method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse head(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Http HEAD method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse head(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http GET method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse get(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse GET request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncGet(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse GET request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncGet(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http PUT method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse put(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http PUT method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse put(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse PUT request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPut(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse PUT request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPut(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http POST method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse post(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http POST method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse post(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse POST request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPost(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse POST request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPost(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http DELETE method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse delete(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http DELETE method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse delete(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse DELETE request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse DELETE request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http PATCH method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse patch(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http PATCH method.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse patch(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse PATCH request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse PATCH request.<br/> + * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulAsyncCallback.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulAsyncCallback.java new file mode 100644 index 0000000..2a42c04 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulAsyncCallback.java @@ -0,0 +1,44 @@ +/* + * 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; + +/** + * Callback interface for ReST calls.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public interface RestfulAsyncCallback { + + /** + * Response callback.<br/> + * + * @param response: response of ReST call. + * @since + */ + void callback(RestfulResponse response); + + /** + * Exceptoin callback.<br/> + * + * @param e: ReST call exception. + * @since + */ + void handleExcepion(Throwable e); +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulClientConst.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulClientConst.java new file mode 100644 index 0000000..54470da --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulClientConst.java @@ -0,0 +1,64 @@ +/* + * 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; + +/** + * Constants for ReST client.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class RestfulClientConst { + + /** -- json Ecode -- **/ + public static final String APPLICATION_FORM_JSON_EBCIDED = "application/json"; + + /** + * urlencode + */ + public static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded; charset=UTF-8"; + + public static final String ENCODING = "UTF-8"; + + public static final String SERVER_KEY_NAME = "defaultServer"; + + public static final String HOST_KEY_NAME = "host"; + + public static final String PORT_KEY_NAME = "port"; + + public static final String CONN_TIMEOUT_KEY_NAME = "ConnectTimeout"; + + public static final String THREAD_KEY_NAME = "thread"; + + public static final String IDLE_TIMEOUT_KEY_NAME = "idletimeout"; + + public static final String TIMEOUT_KEY_NAME = "timeout"; + + public static final String MAX_CONN_PER_ADDR_KEY_NAME = "maxConnectionPerAddr"; + + public static final String REQUEST_ID = "x-request-id"; + + public static final String MAX_RESPONSE_HEADER_SIZE = "responseHeaderSize"; + + public static final String MAX_REQUEST_HEADER_SIZE = "requestHeaderSize"; + + private RestfulClientConst() { + + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulConfigure.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulConfigure.java new file mode 100644 index 0000000..6bb383f --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulConfigure.java @@ -0,0 +1,161 @@ +/* + * 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.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Rest client options.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class RestfulConfigure { + + private static final Logger LOG = LoggerFactory.getLogger(RestfulConfigure.class); + + private RestfulOptions options = null; + + /** + * Constructor<br/> + * <p> + * Use the default path initialization http Rest options. + * </p> + * + * @since + */ + public RestfulConfigure() { + final String config = "/etc/conf/restclient.json"; + final String approot = SystemEnvVariablesFactory.getInstance().getAppRoot(); + final StringBuilder extendSetting = new StringBuilder(); + + if(approot != null) { + extendSetting.append(approot); + extendSetting.append(config); + } else { + extendSetting.append(System.getProperty("user.dir")); + extendSetting.append(config); + } + + final String configfile = extendSetting.toString(); + initRestConf(configfile); + } + + /** + * Constructor<br/> + * <p> + * Use the specified file to initialize http Rest options. + * </p> + * + * @since + * @param configfile + */ + public RestfulConfigure(final String configfile) { + initRestConf(configfile); + } + + public RestfulOptions getOptions() { + return options; + } + + private void initRestConf(final String configfile) { + options = getDefaultOptions(); + + final JSONObject obj = loadJsonFromFile(configfile); + if(obj != null) { + if(obj.has(RestfulClientConst.SERVER_KEY_NAME)) { + final JSONObject server = obj.getJSONObject(RestfulClientConst.SERVER_KEY_NAME); + setStringOption(server, RestfulClientConst.HOST_KEY_NAME); + setIntOption(server, RestfulClientConst.PORT_KEY_NAME); + } + setIntOption(obj, RestfulClientConst.CONN_TIMEOUT_KEY_NAME); + setIntOption(obj, RestfulClientConst.THREAD_KEY_NAME); + setIntOption(obj, RestfulClientConst.IDLE_TIMEOUT_KEY_NAME); + setIntOption(obj, RestfulClientConst.TIMEOUT_KEY_NAME); + setIntOption(obj, RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME); + setIntOption(obj, RestfulClientConst.MAX_RESPONSE_HEADER_SIZE); + setIntOption(obj, RestfulClientConst.MAX_REQUEST_HEADER_SIZE); + } else { + LOG.error("failed to load json from " + configfile); + } + } + + private void setStringOption(final JSONObject json, final String key) { + if(json.has(key)) { + options.setOption(key, json.getString(key)); + } + } + + private void setIntOption(final JSONObject json, final String key) { + if(json.has(key)) { + options.setOption(key, json.getInt(key)); + } + } + + private RestfulOptions getDefaultOptions() { + options = new RestfulOptions(); + options.setOption(RestfulClientConst.CONN_TIMEOUT_KEY_NAME, 3000); + options.setOption(RestfulClientConst.THREAD_KEY_NAME, 200); + options.setOption(RestfulClientConst.IDLE_TIMEOUT_KEY_NAME, 30000); + options.setOption(RestfulClientConst.TIMEOUT_KEY_NAME, 30000); + options.setOption(RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME, 50); + options.setOption(RestfulClientConst.MAX_RESPONSE_HEADER_SIZE, 20 * 1024); + options.setOption(RestfulClientConst.MAX_REQUEST_HEADER_SIZE, 20 * 1024); + return options; + } + + private JSONObject loadJsonFromFile(final String filePath) { + final File file = new File(filePath); + if((!file.exists()) || (!file.isFile())) { + LOG.error(filePath + "isn't exist."); + return null; + } + BufferedReader reader = null; + final StringBuilder jsonstr = new StringBuilder(); + JSONObject jo = null; + try { + reader = new BufferedReader(new FileReader(file)); + final ReaderHelper rHelpper = new ReaderHelper(reader); + String tempString = null; + while((tempString = rHelpper.getLine()) != null) { + jsonstr.append(tempString); + } + jo = JSONObject.fromObject(jsonstr.toString()); + } catch(final IOException e) { + LOG.error("load file exception:" + e); + } finally { + if(reader != null) { + try { + reader.close(); + } catch(final IOException e) { + LOG.error("close error.", e); + } + } + } + return jo; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulFactory.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulFactory.java new file mode 100644 index 0000000..bc6ccae --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulFactory.java @@ -0,0 +1,105 @@ +/* + * 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.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * RestFul instance factory. <br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class RestfulFactory { + + /** + * https protocol. + */ + public static final String PROTO_HTTPS = "https"; + + /** + * http protocol. + */ + public static final String PROTO_HTTP = "http"; + + private static final Logger LOG = LoggerFactory.getLogger(RestfulFactory.class); + + private static final Map<String, Restful> INSTANCES = new HashMap<>(2); + + private RestfulFactory() { + + } + + /** + * Get RESTful instance. This method returns a singleton instance. + * <br/> + * + * @param protocol protocol. currently only support 'http'. + * @return restful instance. + * @since + */ + public static synchronized Restful getRestInstance(final String protocol) { + Restful rest = INSTANCES.get(protocol); + if(rest != null) { + return rest; + } + if(PROTO_HTTP.equals(protocol)) { + rest = createHttpRest(); + INSTANCES.put(protocol, rest); + } + + if (PROTO_HTTPS.equals(protocol)) { + rest = createHttpsRest(); + INSTANCES.put(protocol, rest); + } + return rest; + } + + private static Restful createHttpRest() { + final HttpRest rest = new HttpRest(); + setRestOption(rest, null); + return rest; + } + + private static Restful createHttpsRest() { + final HttpsRest rest = new HttpsRest(); + rest.initHttpsRest(); + return rest; + } + + private static void setRestOption(final HttpRest rest, final String restoptionfile) { + try { + RestfulConfigure config; + if(restoptionfile == null || restoptionfile.isEmpty()) { + config = new RestfulConfigure(); + } else { + config = new RestfulConfigure(restoptionfile); + } + + final RestfulOptions option = config.getOptions(); + rest.initHttpRest(option); + } catch(final ServiceException e) { + LOG.error("init http client exception: ", e); + } + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulOptions.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulOptions.java new file mode 100644 index 0000000..e39a99b --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulOptions.java @@ -0,0 +1,171 @@ +/* + * 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.util.HashMap; +import java.util.Map; + +/** + * Options for Rest communication.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class RestfulOptions { + + public static final String REST_OPTIONS_NAME_TIMEOUT = "timeout"; + + public static final int REST_OPTIONS_TIMEOUT_MAXTIMEOUT = 1800000; + + private final Map<String, Object> optionsMap = new HashMap<>(); + + /** + * Get port.<br/> + * + * @return port. + * @since + */ + public int getPort() { + final Object obj = this.getOption(RestfulClientConst.PORT_KEY_NAME); + if(null == obj) { + return 0; + } + return ((Integer)obj).intValue(); + } + + /** + * Set port.<br/> + * + * @param port port to set. + * @return + * @since + */ + public boolean setPort(final int port) { + this.setOption(RestfulClientConst.PORT_KEY_NAME, port); + return true; + } + + /** + * Get host.<br/> + * + * @return the host. + * @since + */ + public String getHost() { + final Object obj = this.getOption(RestfulClientConst.HOST_KEY_NAME); + if(null == obj) { + return ""; + } + return (String)obj; + } + + /** + * Set host.<br/> + * + * @param host host to set. + * @return + * @since + */ + public boolean setHost(final String host) { + this.setOption(RestfulClientConst.HOST_KEY_NAME, host); + return true; + } + + /** + * Set rest time-out.<br/> + * + * @param timeout time-out to set in seconds. + * @return + * @since + */ + public boolean setRestTimeout(final int timeout) { + if(0 < timeout && REST_OPTIONS_TIMEOUT_MAXTIMEOUT >= timeout) { + this.setOption(REST_OPTIONS_NAME_TIMEOUT, timeout); + return true; + } + return false; + } + + /** + * Get time-out.<br/> + * + * @return time-out in seconds. + * @since + */ + public int getRestTimeout() { + final Object obj = this.getOption(REST_OPTIONS_NAME_TIMEOUT); + if(null == obj) { + return 0; + } + return ((Integer)obj).intValue(); + } + + /** + * Get specified option.<br/> + * + * @param optionName option name. + * @return option + * @since + */ + public Object getOption(final String optionName) { + return optionsMap.get(optionName); + } + + /** + * Get option value as integer.<br/> + * + * @param optionName option name. + * @return option value as int. + * @since + */ + public int getIntOption(final String optionName) { + final Object obj = this.getOption(optionName); + if(null == obj) { + return 0; + } + return ((Integer)obj).intValue(); + } + + /** + * Get option value as string.<br/> + * + * @param optionName option name. + * @return option value as string. + * @since + */ + public String getStringOption(final String optionName) { + final Object obj = this.getOption(optionName); + if(null == obj) { + return ""; + } + return (String)obj; + } + + /** + * Set option.<br/> + * + * @param option option name. + * @param optionsValue option value. + * @return + * @since + */ + public Object setOption(final String option, final Object optionsValue) { + return optionsMap.put(option, optionsValue); + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulParametes.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulParametes.java new file mode 100644 index 0000000..face4b3 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulParametes.java @@ -0,0 +1,155 @@ +/* + * 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.util.HashMap; +import java.util.Map; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version Aug 9, 2016 + */ +public class RestfulParametes { + + private Map<String, String> paramMap = new HashMap<>(); + + private Map<String, String> headerMap = new HashMap<>(); + + private String rawData = null; + + /** + * <br/> + * + * @param key + * @return + * @since + */ + public String get(final String key) { + return paramMap.get(key); + } + + /** + * <br/> + * + * @param data + * @since + */ + public void setRawData(final String data) { + this.rawData = data; + } + + /** + * <br/> + * + * @return + * @since + */ + public String getRawData() { + return this.rawData; + } + + /** + * <br/> + * + * @param key + * @param value + * @return + * @since + */ + public String put(final String key, final String value) { + return paramMap.put(key, value); + } + + /** + * <br/> + * + * @param key + * @param value + * @return + * @since + */ + public String putHttpContextHeader(final String key, final String value) { + return headerMap.put(key, value); + } + + /** + * <br/> + * + * @param key + * @param value + * @return + * @since + */ + public String putHttpContextHeader(final String key, final int value) { + return this.putHttpContextHeader(key, String.valueOf(value)); + } + + /** + * <br/> + * + * @param key + * @return + * @since + */ + public String getHttpContextHeader(final String key) { + return headerMap.get(key); + } + + /** + * <br/> + * + * @return + * @since + */ + public Map<String, String> getParamMap() { + return paramMap; + } + + /** + * <br/> + * + * @param paramMap + * @since + */ + public void setParamMap(final Map<String, String> paramMap) { + this.paramMap = paramMap; + } + + /** + * <br/> + * + * @return + * @since + */ + public Map<String, String> getHeaderMap() { + return this.headerMap; + } + + /** + * <br/> + * + * @param headerMap + * @since + */ + public void setHeaderMap(final Map<String, String> headerMap) { + this.headerMap = headerMap; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulResponse.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulResponse.java new file mode 100644 index 0000000..deff758 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/RestfulResponse.java @@ -0,0 +1,148 @@ +/* + * 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.util.Map; + +/** + * Response for RestFul requests.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class RestfulResponse { + + private String responseContent; + + private int status = -1; + + private Map<String, String> respHeaderMap = null; + + /** + * <br/> + * + * @return + * @since + */ + public int getStatus() { + return status; + } + + /** + * <br/> + * + * @param status + * @since + */ + public void setStatus(final int status) { + this.status = status; + } + + /** + * <br/> + * + * @return + * @since + */ + public Map<String, String> getRespHeaderMap() { + return respHeaderMap; + } + + /** + * <br/> + * + * @param header + * @since + */ + public void setRespHeaderMap(final Map<String, String> header) { + this.respHeaderMap = header; + } + + /** + * Get response header value as integer.<br/> + * + * @param key header param name. + * @return header param value as integer. (-1 if error) + * @since + */ + public int getRespHeaderInt(final String key) { + if(respHeaderMap != null) { + final String result = respHeaderMap.get(key); + if(result != null) { + return Integer.parseInt(result); + } + } + return -1; + } + + /** + * Get response header value as long.<br/> + * + * @param key header param name. + * @return value as long. -1 if no value. + * @since + */ + public long getRespHeaderLong(final String key) { + if(respHeaderMap != null) { + final String result = respHeaderMap.get(key); + if(result != null) { + return Long.parseLong(result); + } + } + return -1; + } + + /** + * Get http header as string.<br/> + * + * @param key header name. + * @return header value. + * @since + */ + public String getRespHeaderStr(final String key) { + if(respHeaderMap != null) { + return respHeaderMap.get(key); + } + return null; + } + + /** + * <br/> + * + * @return + * @since + */ + public String getResponseContent() { + return responseContent; + } + + /** + * <br/> + * + * @param responseString + * @since + */ + public void setResponseJson(final String responseString) { + this.responseContent = responseString; + } + + public boolean isSuccess() { + return this.getStatus() / 100 == 2; + } +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ServiceException.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ServiceException.java new file mode 100644 index 0000000..18eb519 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/ServiceException.java @@ -0,0 +1,270 @@ +/* + * 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.text.MessageFormat; + +/** + * The base class for all common exception.<br/> + * <p> + * </p> + * + * @author + * @version 28-May-2016 + */ +public class ServiceException extends Exception { + + /** + * default exception id. + */ + public static final String DEFAULT_ID = "framwork.remote.SystemError"; + + /** + * Serial number. + */ + private static final long serialVersionUID = 5703294364555144738L; + + /** + * Exception id. + */ + private String id = DEFAULT_ID; + + private Object[] args = null; + + private int httpCode = 500; + + private ExceptionArgs exceptionArgs = null; + + /** + * The default constructor<br/> + * <p> + * This method is only used as deserialized, in other cases, use parameterized constructor. + * </p> + * + * @since + */ + public ServiceException() { + super(""); + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param id: details. + * @param cause: reason. + */ + public ServiceException(final String id, final Throwable cause) { + super(cause); + this.setId(id); + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param message: details. + */ + public ServiceException(final String message) { + super(message); + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param id: exception id. + * @param message: details. + */ + public ServiceException(final String id, final String message) { + super(message); + this.setId(id); + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param id: exception id. + * @param httpCode: http status code. + */ + public ServiceException(final String id, final int httpCode) { + super(); + this.setId(id); + this.setHttpCode(httpCode); + } + + /** + * Constructor<br/> + * <p> + * the exception include the httpcode and message. + * </p> + * + * @since + * @param httpCode http code. + * @param message details. + */ + public ServiceException(final int httpCode, final String message) { + super(message); + this.setHttpCode(httpCode); + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param id: exception id. + * @param httpCode: http code. + * @param exceptionArgs: Exception handling frame parameters. + */ + public ServiceException(final String id, final int httpCode, final ExceptionArgs exceptionArgs) { + super(); + this.setId(id); + this.setHttpCode(httpCode); + this.setExceptionArgs(exceptionArgs); + } + + /** + * Constructor<br/> + * <p> + * Have a placeholder exception, use args formatted message. + * </p> + * + * @since + * @param id: exception id. + * @param message: details. + * @param args: Placeholders for parameters + */ + public ServiceException(final String id, final String message, final Object... args) { + super(MessageFormat.format(message, args)); + this.setId(id); + this.args = args; + } + + /** + * Constructor<br/> + * <p> + * Have a placeholder exception, use args formatted message + * </p> + * + * @since + * @param id: exception id. + * @param message: details. + * @param cause: reason. + * @param args: placeholder for parameters + */ + public ServiceException(final String id, final String message, final Throwable cause, final Object... args) { + super(MessageFormat.format(message, args), cause); + this.setId(id); + this.args = args; + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param id: exception id. + * @param message: details. + * @param cause: reason. + */ + public ServiceException(final String id, final String message, final Throwable cause) { + super(message, cause); + this.setId(id); + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + * @param cause: reason. + */ + public ServiceException(final Throwable cause) { + super(cause); + } + + /** + * Get exceptoin id.<br/> + * + * @return + * @since + */ + public String getId() { + if(id == null || id.isEmpty()) { + return DEFAULT_ID; + } + return id; + } + + public void setId(final String id) { + this.id = id; + } + + public int getHttpCode() { + return this.httpCode; + } + + public void setHttpCode(final int httpCode) { + this.httpCode = httpCode; + } + + /** + * Obtain the ROA exception handling framework parameters<br/> + * + * @return exception args. + * @since + */ + public ExceptionArgs getExceptionArgs() { + return exceptionArgs; + } + + public void setExceptionArgs(final ExceptionArgs exceptionArgs) { + this.exceptionArgs = exceptionArgs; + } + + /** + * Gets the parameter information<br/> + * + * @return parameter list. + * @since + */ + protected Object[] getArgs() { + if(args == null || args.length == 0 || DEFAULT_ID.equals(getId())) { + return new Object[] {}; + } + return args; + } + + @Override + public String toString() { + return "exception.id: " + getId() + "; " + super.toString(); + } + +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariables.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariables.java new file mode 100644 index 0000000..d7558c0 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariables.java @@ -0,0 +1,36 @@ +/* + * 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; + +/** + * Dependency the system env<br/> + * <p> + * </p> + * + * @author + * @version 31-May-2016 + */ +public interface SystemEnvVariables { + + /** + * Get application root path <br/> + * + * @return application root path. + * @since + */ + String getAppRoot(); +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariablesDefImpl.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariablesDefImpl.java new file mode 100644 index 0000000..1981f64 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariablesDefImpl.java @@ -0,0 +1,67 @@ +/* + * 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.File; +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * System environment variable helper implementation.<br/> + * <p> + * </p> + * + * @author + * @version 24-Jun-2016 + */ +public class SystemEnvVariablesDefImpl implements SystemEnvVariables { + + private static final Logger LOG = LoggerFactory.getLogger(SystemEnvVariablesDefImpl.class); + + @Override + public String getAppRoot() { + String appRoot = null; + appRoot = System.getProperty("catalina.base"); + if(appRoot != null) { + appRoot = getCanonicalPath(appRoot); + } + return appRoot; + } + + /** + * Gets the canonical path<br/> + * + * @param inPath input path + * @return the canonical path. + * @since + */ + private String getCanonicalPath(final String inPath) { + String path = null; + try { + if(inPath != null) { + final File file = new File(inPath); + path = file.getCanonicalPath(); + } + } catch(final IOException e) { + LOG.error("file.getCanonicalPath() IOException:", e); + } + return path; + } + +} diff --git a/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariablesFactory.java b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariablesFactory.java new file mode 100644 index 0000000..e121bc1 --- /dev/null +++ b/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/restclient/SystemEnvVariablesFactory.java @@ -0,0 +1,53 @@ +/* + * 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; + +/** + * SystemEnvVariables factory class + * <br/> + * <p> + * </p> + * + * @author + * @version + */ +public class SystemEnvVariablesFactory { + + private static SystemEnvVariables systemEnvVariablesInstance = new SystemEnvVariablesDefImpl(); + + /** + * Constructor<br/> + * <p> + * </p> + * + * @since + */ + private SystemEnvVariablesFactory() { + + } + + /** + * get the SystemEnvVariables instance + * <br/> + * + * @return SystemEnvVariables instance + * @since + */ + public static SystemEnvVariables getInstance() { + return systemEnvVariablesInstance; + } +} |