From c0604184b2aa8cff924ca783ec6b36f1f5988775 Mon Sep 17 00:00:00 2001 From: Zhaoxing Date: Tue, 8 Aug 2017 14:02:53 +0800 Subject: init code Change-Id: Icd0948118397b256da70dfbcbbec5520dc5eafd4 Signed-off-by: Zhaoxing --- .../remoteservice/exception/ExceptionArgs.java | 110 ++ .../remoteservice/exception/ServiceException.java | 269 +++++ .../openo/baseservice/roa/util/ReaderHelper.java | 61 + .../roa/util/restclient/DefaultAsyncCallback.java | 37 + .../roa/util/restclient/HttpBaseRest.java | 273 +++++ .../baseservice/roa/util/restclient/HttpRest.java | 254 +++++ .../util/restclient/RestHttpContentExchange.java | 234 ++++ .../baseservice/roa/util/restclient/Restful.java | 298 +++++ .../roa/util/restclient/RestfulAsyncCallback.java | 43 + .../roa/util/restclient/RestfulClientConst.java | 63 ++ .../roa/util/restclient/RestfulConfigure.java | 162 +++ .../roa/util/restclient/RestfulFactory.java | 95 ++ .../roa/util/restclient/RestfulOptions.java | 170 +++ .../roa/util/restclient/RestfulParametes.java | 155 +++ .../roa/util/restclient/RestfulResponse.java | 144 +++ .../baseservice/roa/util/ReaderHelperTest.java | 116 ++ .../baseservice/roa/util/TestServiceUtil.java | 92 ++ .../roa/util/restclient/TestHttpRest.java | 1179 ++++++++++++++++++++ .../restclient/TestRestHttpContentExchange.java | 592 ++++++++++ .../roa/util/restclient/TestRestfulConfigure.java | 238 ++++ .../roa/util/restclient/TestRestfulFactory.java | 109 ++ .../roa/util/restclient/TestRestfulOptions.java | 288 +++++ .../roa/util/restclient/TestRestfulParametes.java | 229 ++++ .../roa/util/restclient/TestRestfulResponse.java | 273 +++++ .../src/test/resources/etc/conf/restclient.json | 11 + .../src/test/resources/rest-client-test.json | 11 + 26 files changed, 5506 insertions(+) create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java create mode 100644 wso2/rest-client/src/test/resources/etc/conf/restclient.json create mode 100644 wso2/rest-client/src/test/resources/rest-client-test.json (limited to 'wso2/rest-client/src') diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java new file mode 100644 index 0000000..6c92f23 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java @@ -0,0 +1,110 @@ +/* + * 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.openo.baseservice.remoteservice.exception; + +/** + * ROA exception handling parameters. + *
+ *

+ *

+ * + * @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
+ *

+ *

+ * + * @since + */ + public ExceptionArgs() { + // default constructor. + } + + /** + * Constructor
+ *

+ *

+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java new file mode 100644 index 0000000..378fe9f --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java @@ -0,0 +1,269 @@ +/* + * 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.openo.baseservice.remoteservice.exception; + +import java.text.MessageFormat; + +/** + * The base class for all common exception.
+ *

+ *

+ * + * @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
+ *

+ * This method is only used as deserialized, in other cases, use parameterized constructor. + *

+ * + * @since + */ + public ServiceException() { + super(""); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param id: details. + * @param cause: reason. + */ + public ServiceException(final String id, final Throwable cause) { + super(cause); + this.setId(id); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param message: details. + */ + public ServiceException(final String message) { + super(message); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param id: exception id. + * @param message: details. + */ + public ServiceException(final String id, final String message) { + super(message); + this.setId(id); + } + + /** + * Constructor
+ *

+ *

+ * + * @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
+ *

+ * the exception include the httpcode and message. + *

+ * + * @since + * @param httpCode http code. + * @param message details. + */ + public ServiceException(final int httpCode, final String message) { + super(message); + this.setHttpCode(httpCode); + } + + /** + * Constructor
+ *

+ *

+ * + * @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
+ *

+ * Have a placeholder exception, use args formatted message. + *

+ * + * @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
+ *

+ * Have a placeholder exception, use args formatted message + *

+ * + * @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
+ *

+ *

+ * + * @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
+ *

+ *

+ * + * @since + * @param cause: reason. + */ + public ServiceException(final Throwable cause) { + super(cause); + } + + /** + * Get exceptoin id.
+ * + * @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
+ * + * @return exception args. + * @since + */ + public ExceptionArgs getExceptionArgs() { + return exceptionArgs; + } + + public void setExceptionArgs(final ExceptionArgs exceptionArgs) { + this.exceptionArgs = exceptionArgs; + } + + /** + * Gets the parameter information
+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java new file mode 100644 index 0000000..85e4f56 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java @@ -0,0 +1,61 @@ +/* + * 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.openo.baseservice.roa.util; + +import org.apache.commons.io.LineIterator; + +import java.io.Reader; + +/** + * Helper for read line.
+ *

+ *

+ * + * @author + * @version 31-May-2016 + */ +public class ReaderHelper { + + private LineIterator ite = null; + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param reader + */ + public ReaderHelper(final Reader reader) { + if(reader != null) { + ite = new LineIterator(reader); + } + + } + + /** + * Gets the next line.
+ * + * @return line if present else null. + * @since + */ + public String getLine() { + if(ite != null && ite.hasNext()) { + return ite.nextLine(); + } + return null; + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java new file mode 100644 index 0000000..81adeb6 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java @@ -0,0 +1,37 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +/** + * Restful Asynchronous call back implentation.
+ *

+ *

+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java new file mode 100644 index 0000000..3e64937 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java @@ -0,0 +1,273 @@ +/* + * 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.openo.baseservice.roa.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.openo.baseservice.remoteservice.exception.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *
+ *

+ *

+ * + * @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
+ *

+ *

+ * + * @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 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 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); + } + + /** + *
+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java new file mode 100644 index 0000000..047f20e --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java @@ -0,0 +1,254 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.http.HttpMethods; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *
+ *

+ *

+ * + * @author + * @version Aug 9, 2016 + */ +public class HttpRest extends HttpBaseRest { + + private static final Logger LOG = LoggerFactory.getLogger(HttpRest.class); + + /** + * Initializing Rest options.
+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java new file mode 100644 index 0000000..99328a7 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java @@ -0,0 +1,234 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +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; + +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; + +/** + * ContentExchange implementation classe to provide access to response. + *
+ *

+ *

+ * + * @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
+ *

+ *

+ * + * @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. + *
+ * + * @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.
+ * + * @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. + *
+ * + * @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 header = new HashMap<>(); + + final Enumeration names = field.getFieldNames(); + for(final Enumeration 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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java new file mode 100644 index 0000000..8527e68 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java @@ -0,0 +1,298 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +/** + * ReSTful method interface.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public interface Restful { + + /** + * Http GET method.
+ * + * @param servicePath: request path. + * @param restParametes: query parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse get(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http HEAD method.
+ * + * @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.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse head(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http GET method.
+ * + * @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.
+ * + * @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.
+ * + * @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.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse put(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http PUT method.
+ * + * @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.
+ * + * @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.
+ * + * @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.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse post(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http POST method.
+ * + * @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.
+ * + * @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.
+ * + * @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.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse delete(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http DELETE method.
+ * + * @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.
+ * + * @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.
+ * + * @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.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse patch(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http PATCH method.
+ * + * @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.
+ * + * @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.
+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java new file mode 100644 index 0000000..bf461c9 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java @@ -0,0 +1,43 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +/** + * Callback interface for ReST calls.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public interface RestfulAsyncCallback { + + /** + * Response callback.
+ * + * @param response: response of ReST call. + * @since + */ + void callback(RestfulResponse response); + + /** + * Exceptoin callback.
+ * + * @param e: ReST call exception. + * @since + */ + void handleExcepion(Throwable e); +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java new file mode 100644 index 0000000..3741c20 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java @@ -0,0 +1,63 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +/** + * Constants for ReST client.
+ *

+ *

+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java new file mode 100644 index 0000000..3ce6859 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java @@ -0,0 +1,162 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.openo.baseservice.roa.util.ReaderHelper; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Rest client options.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestfulConfigure { + + private static final Logger LOG = LoggerFactory.getLogger(RestfulConfigure.class); + + private RestfulOptions options = null; + + /** + * Constructor
+ *

+ * Use the default path initialization http Rest options. + *

+ * + * @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
+ *

+ * Use the specified file to initialize http Rest options. + *

+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java new file mode 100644 index 0000000..5b94374 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java @@ -0,0 +1,95 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +/** + * RestFul instance factory.
+ *

+ *

+ * + * @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 INSTANCES = new HashMap<>(2); + + private RestfulFactory() { + + } + + /** + * Get RESTful instance. This method returns a singleton instance. + *
+ * + * @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); + } + return rest; + } + + private static Restful createHttpRest() { + final HttpRest rest = new HttpRest(); + setRestOption(rest, null); + 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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java new file mode 100644 index 0000000..6e5812f --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java @@ -0,0 +1,170 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import java.util.HashMap; +import java.util.Map; + +/** + * Options for Rest communication.
+ *

+ *

+ * + * @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 optionsMap = new HashMap<>(); + + /** + * Get port.
+ * + * @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.
+ * + * @param port port to set. + * @return + * @since + */ + public boolean setPort(final int port) { + this.setOption(RestfulClientConst.PORT_KEY_NAME, port); + return true; + } + + /** + * Get host.
+ * + * @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.
+ * + * @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.
+ * + * @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.
+ * + * @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.
+ * + * @param optionName option name. + * @return option + * @since + */ + public Object getOption(final String optionName) { + return optionsMap.get(optionName); + } + + /** + * Get option value as integer.
+ * + * @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.
+ * + * @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.
+ * + * @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/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java new file mode 100644 index 0000000..aea8753 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/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.openo.baseservice.roa.util.restclient; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ *

+ *

+ * + * @author + * @version Aug 9, 2016 + */ +public class RestfulParametes { + + private Map paramMap = new HashMap<>(); + + private Map headerMap = new HashMap<>(); + + private String rawData = null; + + /** + *
+ * + * @param key + * @return + * @since + */ + public String get(final String key) { + return paramMap.get(key); + } + + /** + *
+ * + * @param data + * @since + */ + public void setRawData(final String data) { + this.rawData = data; + } + + /** + *
+ * + * @return + * @since + */ + public String getRawData() { + return this.rawData; + } + + /** + *
+ * + * @param key + * @param value + * @return + * @since + */ + public String put(final String key, final String value) { + return paramMap.put(key, value); + } + + /** + *
+ * + * @param key + * @param value + * @return + * @since + */ + public String putHttpContextHeader(final String key, final String value) { + return headerMap.put(key, value); + } + + /** + *
+ * + * @param key + * @param value + * @return + * @since + */ + public String putHttpContextHeader(final String key, final int value) { + return this.putHttpContextHeader(key, String.valueOf(value)); + } + + /** + *
+ * + * @param key + * @return + * @since + */ + public String getHttpContextHeader(final String key) { + return headerMap.get(key); + } + + /** + *
+ * + * @return + * @since + */ + public Map getParamMap() { + return paramMap; + } + + /** + *
+ * + * @param paramMap + * @since + */ + public void setParamMap(final Map paramMap) { + this.paramMap = paramMap; + } + + /** + *
+ * + * @return + * @since + */ + public Map getHeaderMap() { + return this.headerMap; + } + + /** + *
+ * + * @param headerMap + * @since + */ + public void setHeaderMap(final Map headerMap) { + this.headerMap = headerMap; + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java new file mode 100644 index 0000000..25105b7 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java @@ -0,0 +1,144 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import java.util.Map; + +/** + * Response for RestFul requests.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestfulResponse { + + private String responseContent; + + private int status = -1; + + private Map respHeaderMap = null; + + /** + *
+ * + * @return + * @since + */ + public int getStatus() { + return status; + } + + /** + *
+ * + * @param status + * @since + */ + public void setStatus(final int status) { + this.status = status; + } + + /** + *
+ * + * @return + * @since + */ + public Map getRespHeaderMap() { + return respHeaderMap; + } + + /** + *
+ * + * @param header + * @since + */ + public void setRespHeaderMap(final Map header) { + this.respHeaderMap = header; + } + + /** + * Get response header value as integer.
+ * + * @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.
+ * + * @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.
+ * + * @param key header name. + * @return header value. + * @since + */ + public String getRespHeaderStr(final String key) { + if(respHeaderMap != null) { + return respHeaderMap.get(key); + } + return null; + } + + /** + *
+ * + * @return + * @since + */ + public String getResponseContent() { + return responseContent; + } + + /** + *
+ * + * @param responseString + * @since + */ + public void setResponseJson(final String responseString) { + this.responseContent = responseString; + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java new file mode 100644 index 0000000..9922476 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java @@ -0,0 +1,116 @@ +/* + * 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.openo.baseservice.roa.util; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.Reader; +import java.io.StringReader; + +import junit.framework.Assert; + +/** + *
+ *

+ *

+ * + * @author + * @version 12-Jun-2016 + */ +public class ReaderHelperTest { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + * Test method for {@link org.openo.baseservice.util.inf.ReaderHelper#getLine()}. + */ + @Test + public void testGetLine() { + final String message = "hello.. how are you?"; + final Reader reader = new StringReader(message); + final ReaderHelper helper = new ReaderHelper(reader); + final String actual = helper.getLine(); + Assert.assertEquals(message, actual); + } + + /** + * Test method for {@link org.openo.baseservice.util.inf.ReaderHelper#getLine()}. + */ + @Test + public void testGetLineMultiLine() { + final String line1 = "hello.. how are you?"; + final String line2 = "I am fine."; + final Reader reader = new StringReader(line1 + System.lineSeparator() + line2); + final ReaderHelper helper = new ReaderHelper(reader); + String actual = helper.getLine(); + Assert.assertEquals(line1, actual); + actual = helper.getLine(); + Assert.assertEquals(line2, actual); + actual = helper.getLine(); + Assert.assertEquals(null, actual); + } + + @Test + public void testGetLineNull() { + final ReaderHelper helper = new ReaderHelper(null); + final String actual = helper.getLine(); + Assert.assertEquals(null, actual); + + } + +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java new file mode 100644 index 0000000..d99d562 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java @@ -0,0 +1,92 @@ +/* + * 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.openo.baseservice.roa.util; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + *
+ *

+ *

+ * + * @author + * @version 13-Jun-2016 + */ +public class TestServiceUtil { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetServiceHost() { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetServicePort() { + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java new file mode 100644 index 0000000..47d4ac8 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java @@ -0,0 +1,1179 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.net.URLEncoder; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.HttpExchange; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 13-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestHttpRest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testInitHttpRest() throws Exception { + final RestfulOptions options = new RestfulOptions(); + new MockUp() { + + @Mock + public void doStart() { + System.out.println("started"); + } + }; + final HttpRest httpRest = new HttpRest(); + httpRest.initHttpRest(options); + final Field httpClient = HttpBaseRest.class.getDeclaredField("client"); + httpClient.setAccessible(true); + Assert.assertNotNull(httpClient.get(httpRest)); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testInitHttpRestExcpetion() throws Exception { + final RestfulOptions options = new RestfulOptions(); + new MockUp() { + + @Mock + public void doStart() throws Exception { + throw new Exception(); + } + }; + final HttpRest httpRest = new HttpRest(); + thrown.expect(ServiceException.class); + thrown.expectMessage("http client init failed."); + httpRest.initHttpRest(options); + final Field httpClient = HttpRest.class.getDeclaredField("client"); + httpClient.setAccessible(true); + Assert.assertNull(httpClient.get(httpRest)); + System.out.println("finished"); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testInitHttpRestNull() throws Exception { + final HttpRest httpRest = new HttpRest(); + thrown.expect(ServiceException.class); + thrown.expectMessage("option is null."); + httpRest.initHttpRest(null); + } + + /** + *
+ * + * @throws NoSuchFieldException + * @throws Exception + * @since + */ + @Test + public void testCreateRestHttpContentExchange() throws NoSuchFieldException, Exception { + final HttpBaseRest httpRest = new HttpRest(); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + + } + + @Override + public void handleExcepion(final Throwable e) { + + } + + }; + final RestHttpContentExchange exchange = httpRest.createRestHttpContentExchange(callback); + assertNotNull(exchange); + final Field callbackField = RestHttpContentExchange.class.getDeclaredField("callback"); + assertNotNull(callbackField); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetStringRestfulParametes() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", "application/json"); + parametes.putHttpContextHeader("Accept-Encoding", "*/*"); + final RestfulResponse response = httpRest.get("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetStringRestfulParametesRestfulOptions() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulResponse response = httpRest.get("path/to/service", new RestfulParametes(), options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetStringRestfulParametesEncodeError() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + new NonStrictExpectations() { + + @Mocked + URLEncoder encoder; + + { + URLEncoder.encode(anyString, RestfulClientConst.ENCODING); + result = new UnsupportedEncodingException(); + } + + }; + + thrown.expect(ServiceException.class); + thrown.expectMessage("Broken VM does not support"); + + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", "application/json"); + parametes.putHttpContextHeader("Accept-Encoding", "*/*"); + final RestfulResponse response = httpRest.get("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testHeadStringRestfulParametes() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.head("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testHeadStringRestfulParametesRestfulOptions() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.head("path/to/service", parametes, options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @param options + * @return + * @throws ServiceException + * @since + */ + private HttpRest getHttpRest(final RestfulOptions options) throws ServiceException { + final HttpRest httpRest = new HttpRest(); + { + new MockUp() { + + @Mock + public void doStart() { + System.out.println("started"); + } + + @Mock + public void send(final HttpExchange exchange) throws IOException { + System.out.println("send"); + } + }; + httpRest.initHttpRest(options); + + } + return httpRest; + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testAsyncGetStringRestfulParametesRestfulAsyncCallback() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncGet("path/to/service", new RestfulParametes(), callback); + httpRest.asyncGet("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncGetStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncGet("path/to/service", new RestfulParametes(), new RestfulOptions(), callback); + httpRest.asyncGet("path/to/service", new RestfulParametes(), new RestfulOptions(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPutStringRestfulParametes() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.put("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPutStringRestfulParametesRestfulOptions() throws ServiceException { + + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.put("path/to/service", parametes, null); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPutStringRestfulParametesRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPut("path/to/service", new RestfulParametes(), callback); + httpRest.asyncPut("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testAsyncPutStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPut("path/to/service", new RestfulParametes(), new RestfulOptions(), callback); + httpRest.asyncPut("path/to/service", new RestfulParametes(), new RestfulOptions(), null); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testPostStringRestfulParametes() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_EXPIRED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_EXPIRED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + + thrown.expect(ServiceException.class); + thrown.expectMessage("request is expierd"); + final RestfulResponse response = httpRest.post("http://localhost:80/path/to/service", parameters); + assertEquals(HttpExchange.STATUS_EXPIRED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPostStringRestfulParametesRestfulOptions() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_EXCEPTED); + return HttpExchange.STATUS_EXCEPTED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + thrown.expect(ServiceException.class); + thrown.expectMessage("request is exception"); + final RestfulResponse response = httpRest.post("path/to/service", parameters, null); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testAsyncPostStringRestfulParametesRestfulAsyncCallback() throws Exception { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_EXCEPTED); + return 99; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_EXCEPTED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPostStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testDeleteStringRestfulParametes() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + + final RestfulResponse response = httpRest.delete("path/to/service", null); + assertEquals(-1, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testDeleteStringRestfulParametesRestfulOptions() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.delete("path/to/service", parameters, options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncDeleteStringRestfulParametesRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncDelete("path/to/service", new RestfulParametes(), callback); + httpRest.asyncDelete("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncDeleteStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncDelete("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncDelete("path/to/service", new RestfulParametes(), options, null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPatchStringRestfulParametes() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.patch("path/to/service", parameters); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPatchStringRestfulParametesRestfulOptions() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.patch("path/to/service", parameters, options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPatchStringRestfulParametesRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPatch("path/to/service", new RestfulParametes(), callback); + httpRest.asyncPatch("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPatchStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPatch("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncPatch("path/to/service", new RestfulParametes(), options, null); + } + +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java new file mode 100644 index 0000000..dbd1b1e --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java @@ -0,0 +1,592 @@ +/* + * Copyright 2016-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.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.zip.GZIPInputStream; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.eclipse.jetty.client.Address; +import org.eclipse.jetty.client.CachedExchange; +import org.eclipse.jetty.client.HttpDestination; +import org.eclipse.jetty.client.HttpExchange; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeaders; +import org.eclipse.jetty.io.Buffer; +import org.eclipse.jetty.io.ByteArrayBuffer; +import org.eclipse.jetty.util.StringUtil; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestHttpContentExchange { + + @Mocked + HttpDestination mockedDest; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.ERROR); + } + + /** + *
+ * + * @throws IOException + * @since + */ + @Test + public void testOnRequestCommitted() throws IOException { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onRequestCommitted(); + + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG); + exchange.onRequestCommitted(); + } + + /** + *
+ * + * @throws IOException + * @since + */ + @Test + public void testOnRequestComplete() throws IOException { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onRequestComplete(); + + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG); + exchange.onRequestComplete(); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testOnResponseComplete() throws Exception { + RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onResponseComplete(); + + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG); + exchange.onResponseComplete(); + + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + } + + }; + + final Field statusField = HttpExchange.class.getDeclaredField("_status"); + statusField.setAccessible(true); + exchange = new RestHttpContentExchange(false, callback); + statusField.set(exchange, new AtomicInteger(200)); + exchange.setAddress(new Address("localhost", 9999)); + exchange.setRequestURI("/the/request/uri"); + exchange.onResponseComplete(); + assertEquals(1, isCallback.get()); + assertEquals(0, isException.get()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + @Ignore + public void testDecompressGzipToStr() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz"); + final byte[] binaryData = new byte[1024]; + stream.read(binaryData); + final String expected = "sample data."; + + final String actual = exchange.decompressGzipToStr(binaryData); + + System.out.println("actual: '" + actual + "'"); + System.out.println("expected: '" + expected + "'"); + assertEquals(actual, expected); + + new MockUp() { + + @Mock + public int read() throws Exception { + throw new IOException(); + } + + @Mock + public int read(final byte abyte0[], final int i, final int j) { + + return -1; + } + + }; + + thrown.expect(IOException.class); + exchange.decompressGzipToStr(binaryData); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + @Ignore + public void testDecompressGzipToStrException() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz"); + final byte[] binaryData = new byte[1024]; + stream.read(binaryData); + final String expected = "sample data."; + + new MockUp() { + + @Mock + public void close() throws IOException { + throw new IOException(); + } + + }; + + new MockUp() { + + @Mock + public void close() throws IOException { + throw new IOException(); + } + + }; + + new MockUp() { + + @Mock + public void close() throws IOException { + throw new IOException(); + } + + }; + + final String actual = exchange.decompressGzipToStr(binaryData); + + System.out.println("actual: '" + actual + "'"); + System.out.println("expected: '" + expected + "'"); + assertEquals(actual, expected); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testDecompressGzipToStrNull() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + final String expected = ""; + final String actual = exchange.decompressGzipToStr(null); + + System.out.println("actual: '" + actual + "'"); + System.out.println("expected: '" + expected + "'"); + assertEquals(actual, expected); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testOnResponseHeaderBufferBuffer() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final Buffer name = new ByteArrayBuffer("key"); + final Buffer value = new ByteArrayBuffer("value"); + exchange.onResponseHeader(name, value); + + new MockUp() { + + @Mock + public int getOrdinal(final Buffer buffer) { + return HttpHeaders.CONTENT_ENCODING_ORDINAL; + } + + }; + exchange.onResponseHeader(name, value); + + new MockUp() { + + @Mock + public String asciiToLowerCase(final String s) { + return "gzip"; + } + + }; + exchange.onResponseHeader(name, value); + + } + + /** + *
+ * + * @since + */ + @Test + public void testOnExceptionThrowable() { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onException(new Exception()); + } + + /** + *
+ * + * @since + */ + @Test + public void testOnExceptionThrowableWithCallback() { + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + } + + }; + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onException(new Exception()); + assertEquals(0, isCallback.get()); + assertEquals(1, isException.get()); + } + + /** + *
+ * + * @since + */ + @Test + public void testOnConnectionFailedThrowable() { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onConnectionFailed(new Exception()); + } + + /** + *
+ * + * @since + */ + @Test + public void testOnConnectionFailedThrowableException() { + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + } + + }; + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onConnectionFailed(new Exception()); + assertEquals(0, isCallback.get()); + assertEquals(1, isException.get()); + } + + /** + *
+ * + * @since + */ + @Test + public void testExpireHttpDestination() { + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.expire(mockedDest); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testExpireHttpDestinationException() throws Exception { + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final List thrSet = new ArrayList(); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + thrSet.add(e); + } + + }; + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.expire(mockedDest); + assertEquals(0, isCallback.get()); + assertEquals(1, isException.get()); + assertEquals(1, thrSet.size()); + final Throwable t = thrSet.get(0); + assertEquals(ServiceException.class, t.getClass()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testIsGzip() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final Buffer name = new ByteArrayBuffer("key"); + final Buffer value = new ByteArrayBuffer("value"); + + new MockUp() { + + @Mock + public int getOrdinal(final Buffer buffer) { + return HttpHeaders.CONTENT_ENCODING_ORDINAL; + } + + }; + exchange.onResponseHeader(name, value); + assertFalse(exchange.isGzip()); + + new MockUp() { + + @Mock + public String asciiToLowerCase(final String s) { + return "gzip"; + } + + }; + exchange.onResponseHeader(name, value); + assertTrue(exchange.isGzip()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetResponse() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final Field statusField = HttpExchange.class.getDeclaredField("_status"); + statusField.setAccessible(true); + statusField.set(exchange, new AtomicInteger(200)); + + RestfulResponse response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + + final HttpFields fields = new HttpFields(); + final Field headerFields = CachedExchange.class.getDeclaredField("_responseFields"); + headerFields.setAccessible(true); + headerFields.set(exchange, fields); + response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + fields.add("Content-Type", "application/json"); + fields.add("Content-Encode", "UTF-8"); + response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetResponseGzip() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + new MockUp() { + + @Mock + public boolean isGzip() { + return true; + } + }; + final Field statusField = HttpExchange.class.getDeclaredField("_status"); + statusField.setAccessible(true); + statusField.set(exchange, new AtomicInteger(200)); + + final RestfulResponse response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java new file mode 100644 index 0000000..7cc7b1e --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java @@ -0,0 +1,238 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; + +import org.openo.baseservice.util.impl.SystemEnvVariablesDefImpl; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; + +import net.sf.json.JSONObject; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +import mockit.Mock; +import mockit.MockUp; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestfulConfigure { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + setAppRoot(); + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + private static void setAppRoot() { + final URL resource = ClassLoader.getSystemResource("etc/conf/restclient.json"); + final String urlPath = resource.getPath().replace("etc/conf/restclient.json", ""); + + try { + final String path = new File(urlPath).getCanonicalPath(); + System.out.println("path: " + path); + + System.setProperty("catalina.base", path); + System.out.println("approot:" + System.getProperty("catalina.base")); + } catch(final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + *
+ * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigure() throws Exception { + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + assertEquals("127.0.0.1", options.getHost()); + assertEquals(8080, options.getPort()); + assertEquals(1000, options.getIntOption("ConnectTimeout")); + assertEquals(10, options.getIntOption("thread")); + assertEquals(500000, options.getIntOption("idletimeout")); + assertEquals(10000, options.getIntOption("timeout")); + + } + + /** + *
+ * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigureAppRootNull() throws Exception { + new MockUp() { + + @Mock + public String getAppRoot() { + return null; + } + + }; + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + + assertEquals("", options.getHost()); + assertEquals(0, options.getPort()); + assertEquals(3000, options.getIntOption("ConnectTimeout")); + assertEquals(200, options.getIntOption("thread")); + assertEquals(30000, options.getIntOption("idletimeout")); + assertEquals(30000, options.getIntOption("timeout")); + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigureDefault() throws Exception { + + { + + new MockUp() { + + @Mock + public boolean isFile() { + return false; + } + }; + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + assertEquals("", options.getHost()); + assertEquals(0, options.getPort()); + assertEquals(3000, options.getIntOption("ConnectTimeout")); + assertEquals(200, options.getIntOption("thread")); + assertEquals(30000, options.getIntOption("idletimeout")); + assertEquals(30000, options.getIntOption("timeout")); + } + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigureException() throws Exception { + + new MockUp() { + + @Mock + JSONObject fromObject(final Object object) throws IOException { + throw new IOException(); + } + }; + + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + assertEquals("", options.getHost()); + assertEquals(0, options.getPort()); + assertEquals(3000, options.getIntOption("ConnectTimeout")); + assertEquals(200, options.getIntOption("thread")); + assertEquals(30000, options.getIntOption("idletimeout")); + assertEquals(30000, options.getIntOption("timeout")); + + } + + /** + * + * @since + */ + @Test + public final void testRestfulConfigureString() { + final String configFile = "rest-client-test.json"; + final String appRoot = System.getProperty("catalina.base"); + final RestfulConfigure configure = new RestfulConfigure(appRoot + File.separator + configFile); + final RestfulOptions options = configure.getOptions(); + assertEquals("10.10.10.10", options.getHost()); + assertEquals(443, options.getPort()); + assertEquals(10, options.getIntOption("ConnectTimeout")); + assertEquals(100, options.getIntOption("thread")); + assertEquals(30, options.getIntOption("idletimeout")); + assertEquals(60, options.getIntOption("timeout")); + } + + /** + *
+ * + * @since + */ + @Test + public final void testGetOptions() { + } +} \ No newline at end of file diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java new file mode 100644 index 0000000..5678732 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java @@ -0,0 +1,109 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Mock; +import mockit.MockUp; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 21-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestfulFactory { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRestInstance() { + Restful instance = RestfulFactory.getRestInstance("https"); + assertNull(instance); + new MockUp() { + + @Mock + public void initHttpRest(final RestfulOptions option) throws ServiceException { + throw new ServiceException(); + } + + }; + instance = RestfulFactory.getRestInstance("http"); + assertNotNull(instance); + + instance = RestfulFactory.getRestInstance("http"); + assertNotNull(instance); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java new file mode 100644 index 0000000..b91bbef --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java @@ -0,0 +1,288 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; + +import java.util.ArrayList; +import java.util.List; + +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestfulOptions { + + @Rule + final public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetPort() { + final RestfulOptions options = new RestfulOptions(); + final int port = 9091; + assertEquals(0, options.getPort()); + options.setPort(port); + assertEquals(port, options.getPort()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetPort() { + final RestfulOptions options = new RestfulOptions(); + final int port = 9091; + assertTrue(options.setPort(port)); + assertEquals(port, options.getPort()); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetHost() { + final RestfulOptions options = new RestfulOptions(); + final String host = "localhost"; + assertEquals("", options.getHost()); + options.setHost(host); + assertEquals(host, options.getHost()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetHost() { + final RestfulOptions options = new RestfulOptions(); + final String host = "localhost"; + assertTrue(options.setHost(host)); + assertEquals(host, options.getHost()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetRestTimeout() { + final RestfulOptions options = new RestfulOptions(); + int timeout = 0; + assertFalse(options.setRestTimeout(timeout)); + assertEquals(0, options.getRestTimeout()); + + timeout = 1; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = 10; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT - 1; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT + 1; + assertFalse(options.setRestTimeout(timeout)); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRestTimeout() { + final RestfulOptions options = new RestfulOptions(); + int timeout = 0; + assertEquals(0, options.getRestTimeout()); + + timeout = 1; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetOption() { + final RestfulOptions options = new RestfulOptions(); + assertNull(options.getOption("invalid")); + + options.setHost("localhost"); + Object obj = options.getOption(RestfulClientConst.HOST_KEY_NAME); + assertNotNull(obj); + assertTrue(obj instanceof String); + assertEquals("localhost", obj); + + final List list = new ArrayList(); + list.add("data"); + options.setOption("list", list); + obj = options.getOption("list"); + assertNotNull(obj); + assertTrue(obj instanceof List); + assertSame(list, obj); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetIntOption() { + final RestfulOptions options = new RestfulOptions(); + + assertEquals(0, options.getIntOption("count")); + + options.setOption("count", 1); + assertEquals(1, options.getIntOption("count")); + + thrown.expect(RuntimeException.class); + + options.setOption("string-count", "two"); + final int value = options.getIntOption("string-count"); + assertEquals(2, value); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetStringOption() { + final RestfulOptions options = new RestfulOptions(); + + assertEquals("", options.getStringOption("count")); + + options.setOption("string-count", "one"); + assertEquals("one", options.getStringOption("string-count")); + + thrown.expect(RuntimeException.class); + + options.setOption("count", 2); + final String value = options.getStringOption("count"); + assertEquals(2, value); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetOption() { + final RestfulOptions options = new RestfulOptions(); + assertNull(options.getOption("invalid")); + + options.setHost("localhost"); + Object obj = options.getOption(RestfulClientConst.HOST_KEY_NAME); + assertNotNull(obj); + assertTrue(obj instanceof String); + assertEquals("localhost", obj); + + final List list = new ArrayList(); + list.add("data"); + options.setOption("list", list); + obj = options.getOption("list"); + assertNotNull(obj); + assertTrue(obj instanceof List); + assertSame(list, obj); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java new file mode 100644 index 0000000..fbe9430 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java @@ -0,0 +1,229 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ *

+ *

+ * + * @author + * @version 21-Jun-2016 + */ +public class TestRestfulParametes { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGet() { + final RestfulParametes params = new RestfulParametes(); + assertNull(params.get("param")); + final Map paramMap = new HashMap(); + params.setParamMap(paramMap); + paramMap.put("param", "value"); + assertEquals("value", params.get("param")); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetRawData() { + final RestfulParametes params = new RestfulParametes(); + final String data = "Sample data."; + params.setRawData(data); + assertEquals(data, params.getRawData()); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRawData() { + final RestfulParametes params = new RestfulParametes(); + assertNull(params.getRawData()); + final String data = "Sample data."; + params.setRawData(data); + assertEquals(data, params.getRawData()); + } + + /** + *
+ * + * @since + */ + @Test + public void testPut() { + final RestfulParametes params = new RestfulParametes(); + params.put("somekey", "somevalue"); + params.put("otherkey", "othervalue"); + assertEquals("somevalue", params.get("somekey")); + assertEquals("othervalue", params.get("otherkey")); + } + + /** + *
+ * + * @since + */ + @Test + public void testPutHttpContextHeaderStringString() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("Context-Encoding", "UTF-8"); + assertEquals("UTF-8", params.getHttpContextHeader("Context-Encoding")); + } + + /** + *
+ * + * @since + */ + @Test + public void testPutHttpContextHeaderStringInt() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("Expire-At", 1000); + assertEquals("1000", params.getHttpContextHeader("Expire-At")); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetHttpContextHeader() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("Expire-At", 1000); + params.putHttpContextHeader("Context-Encoding", "UTF-8"); + assertEquals("1000", params.getHttpContextHeader("Expire-At")); + assertEquals("UTF-8", params.getHttpContextHeader("Context-Encoding")); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetParamMap() { + final RestfulParametes params = new RestfulParametes(); + params.put("key", "value"); + final Map map = params.getParamMap(); + assertEquals("value", map.get("key")); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetParamMap() { + final RestfulParametes params = new RestfulParametes(); + final Map map = new HashMap(); + map.put("key", "value"); + params.setParamMap(map); + assertEquals("value", params.get("key")); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetHeaderMap() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("key", "value"); + final Map map = params.getHeaderMap(); + assertEquals("value", map.get("key")); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetHeaderMap() { + final RestfulParametes params = new RestfulParametes(); + final Map map = new HashMap(); + map.put("key", "value"); + params.setHeaderMap(map); + assertEquals("value", params.getHttpContextHeader("key")); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java new file mode 100644 index 0000000..19fc7d5 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java @@ -0,0 +1,273 @@ +/* + * 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.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +public class TestRestfulResponse { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetStatus() { + final RestfulResponse response = new RestfulResponse(); + int actual = response.getStatus(); + int expected = -1; + + assertEquals(expected, actual); + expected = 202; + response.setStatus(expected); + actual = response.getStatus(); + assertEquals(expected, actual); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetStatus() { + final RestfulResponse response = new RestfulResponse(); + final int expected = 10; + response.setStatus(expected); + final int actual = response.getStatus(); + assertEquals(expected, actual); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderMap() { + final RestfulResponse response = new RestfulResponse(); + Map expected = response.getRespHeaderMap(); + assertNull(expected); + expected = new HashMap(); + expected.put("key", "value"); + response.setRespHeaderMap(expected); + final Map actual = response.getRespHeaderMap(); + assertNotNull(actual); + assertSame(actual, expected); + + } + + /** + *
+ * + * @since + */ + @Test + public void testSetRespHeaderMap() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + Map expected = response.getRespHeaderMap(); + assertNull(expected); + expected = new HashMap(); + expected.put("key", "value"); + response.setRespHeaderMap(expected); + final Map actual = response.getRespHeaderMap(); + assertNotNull(actual); + assertSame(actual, expected); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderInt() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + int actual = response.getRespHeaderInt("somekey"); + assertEquals(-1, actual); + final Map headers = new HashMap(); + headers.put("key", "value"); + headers.put("count", "1"); + response.setRespHeaderMap(headers); + actual = response.getRespHeaderInt("somekey"); + assertEquals(-1, actual); + + actual = response.getRespHeaderInt("count"); + assertEquals(1, actual); + + thrown.expect(RuntimeException.class); + actual = response.getRespHeaderInt("key"); + assertEquals(1, actual); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderLong() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + long actual = response.getRespHeaderLong("somekey"); + assertEquals(-1, actual); + final Map headers = new HashMap(); + headers.put("key", "value"); + headers.put("count", "1"); + headers.put("max", "" + Long.MAX_VALUE); + headers.put("max++", Long.MAX_VALUE + 1 + ""); + response.setRespHeaderMap(headers); + actual = response.getRespHeaderLong("somekey"); + assertEquals(-1, actual); + + actual = response.getRespHeaderLong("count"); + assertEquals(1, actual); + + actual = response.getRespHeaderLong("max"); + assertEquals(Long.MAX_VALUE, actual); + + actual = response.getRespHeaderLong("max++"); + assertTrue(actual < 0); + + thrown.expect(RuntimeException.class); + actual = response.getRespHeaderLong("key"); + assertEquals(1, actual); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderStr() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + String actual = response.getRespHeaderStr("somekey"); + assertEquals(null, actual); + final Map headers = new HashMap(); + headers.put("key", "value"); + headers.put("count", "1"); + headers.put("max", "" + Long.MAX_VALUE); + response.setRespHeaderMap(headers); + actual = response.getRespHeaderStr("somekey"); + assertEquals(null, actual); + + actual = response.getRespHeaderStr("key"); + assertEquals("value", actual); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetResponseContent() { + final RestfulResponse response = new RestfulResponse(); + assertEquals(null, response.getResponseContent()); + + final String content = "{ \"content\" = \"The response content\" }"; + response.setResponseJson(content); + assertEquals(content, response.getResponseContent()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetResponseJson() { + final RestfulResponse response = new RestfulResponse(); + assertEquals(null, response.getResponseContent()); + + final String content = "{ \"content\" = \"The response content\" }"; + response.setResponseJson(content); + assertEquals(content, response.getResponseContent()); + } +} diff --git a/wso2/rest-client/src/test/resources/etc/conf/restclient.json b/wso2/rest-client/src/test/resources/etc/conf/restclient.json new file mode 100644 index 0000000..1ab1aaf --- /dev/null +++ b/wso2/rest-client/src/test/resources/etc/conf/restclient.json @@ -0,0 +1,11 @@ +{ + "defaultServer": + { + "host":"127.0.0.1", + "port":"8080", + }, + "ConnectTimeout":"1000", + "thread":"10", + "idletimeout":"500000", + "timeout":"10000" +} \ No newline at end of file diff --git a/wso2/rest-client/src/test/resources/rest-client-test.json b/wso2/rest-client/src/test/resources/rest-client-test.json new file mode 100644 index 0000000..0bdd9cd --- /dev/null +++ b/wso2/rest-client/src/test/resources/rest-client-test.json @@ -0,0 +1,11 @@ +{ + "defaultServer": + { + "host":"10.10.10.10", + "port":"443", + }, + "ConnectTimeout":"10", + "thread":"100", + "idletimeout":"30", + "timeout":"60", +} \ No newline at end of file -- cgit 1.2.3-korg