From 798ccdc010e4628f6638602a4426444a68c0c52a Mon Sep 17 00:00:00 2001 From: HuabingZhao Date: Thu, 17 Aug 2017 19:39:44 +0800 Subject: msb http client Issue-Id: MSB-22 Change-Id: I79714244d675e193a0bf6bf64085e76a02e937e3 Signed-off-by: HuabingZhao --- .../onap/msb/sdk/httpclient/ProxyRetrofitCall.java | 127 ++++++++++++++ .../msb/sdk/httpclient/RetrofitServiceCreater.java | 117 +++++++++++++ .../msb/sdk/httpclient/RetrofitServiceUtils.java | 122 ++++++++++++++ .../httpclient/ServiceHttpEndPointBeanObject.java | 107 ++++++++++++ .../sdk/httpclient/ServiceHttpEndPointObject.java | 186 +++++++++++++++++++++ .../sdk/httpclient/annotaion/BodyConverter.java | 29 ++++ .../sdk/httpclient/annotaion/ConnectionParams.java | 38 +++++ .../msb/sdk/httpclient/annotaion/LoadBalance.java | 36 ++++ .../httpclient/annotaion/ServiceHttpEndPoint.java | 52 ++++++ .../httpclient/builder/IRetrofitObjectBuilder.java | 36 ++++ .../builder/impl/ClientRetrofitObjectBuilder.java | 181 ++++++++++++++++++++ .../msb/sdk/httpclient/conf/HttpClientConf.java | 91 ++++++++++ .../convert/IConverterFactoryBuilder.java | 25 +++ .../convert/jackson/JacksonConverterFactory.java | 90 ++++++++++ .../jackson/JacksonConverterFactoryBuilder.java | 50 ++++++ .../jackson/JacksonRequestBodyConverter.java | 51 ++++++ .../jackson/JacksonResponseBodyConverter.java | 64 +++++++ .../exception/RetrofitServiceRuntimeException.java | 50 ++++++ .../httpclient/handler/HandlerContextBuilder.java | 30 ++++ .../httpclient/handler/RetrofitServiceHandler.java | 162 ++++++++++++++++++ .../handler/RetrofitServiceHandlerContext.java | 159 ++++++++++++++++++ .../handler/RetrofitServiceHandlerFactory.java | 110 ++++++++++++ .../handler/impl/ConnectionParamsBuilder.java | 63 +++++++ .../handler/impl/ConverterFactoryBuilder.java | 71 ++++++++ .../msb/sdk/httpclient/handler/impl/LBBuilder.java | 76 +++++++++ .../handler/impl/MetricmanagerBuilder.java | 39 +++++ .../impl/RetrofitHandlerContextBuilder.java | 48 ++++++ .../impl/ServiceHttpEndPointBeanObjectBuilder.java | 76 +++++++++ .../sdk/httpclient/lb/ILoadBalanceStrategy.java | 28 ++++ .../msb/sdk/httpclient/lb/LoadBalanceContext.java | 61 +++++++ .../sdk/httpclient/lb/RoundRobinLBStrategy.java | 50 ++++++ .../msb/sdk/httpclient/metric/MetricManager.java | 84 ++++++++++ .../msb/sdk/httpclient/metric/MetricObject.java | 38 +++++ .../httpclient/msb/MSBServiceWrapperClient.java | 162 ++++++++++++++++++ 34 files changed, 2709 insertions(+) create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/ProxyRetrofitCall.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceCreater.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceUtils.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointBeanObject.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointObject.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/annotaion/BodyConverter.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/annotaion/ConnectionParams.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/annotaion/LoadBalance.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/annotaion/ServiceHttpEndPoint.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/builder/IRetrofitObjectBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/builder/impl/ClientRetrofitObjectBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/conf/HttpClientConf.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/convert/IConverterFactoryBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactory.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactoryBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonRequestBodyConverter.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonResponseBodyConverter.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/exception/RetrofitServiceRuntimeException.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/HandlerContextBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandler.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerContext.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerFactory.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConnectionParamsBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConverterFactoryBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/impl/LBBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/impl/MetricmanagerBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/impl/RetrofitHandlerContextBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ServiceHttpEndPointBeanObjectBuilder.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/lb/ILoadBalanceStrategy.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/lb/LoadBalanceContext.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/lb/RoundRobinLBStrategy.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/metric/MetricManager.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/metric/MetricObject.java create mode 100644 src/main/java/org/onap/msb/sdk/httpclient/msb/MSBServiceWrapperClient.java (limited to 'src/main/java/org') diff --git a/src/main/java/org/onap/msb/sdk/httpclient/ProxyRetrofitCall.java b/src/main/java/org/onap/msb/sdk/httpclient/ProxyRetrofitCall.java new file mode 100644 index 0000000..ac831e9 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/ProxyRetrofitCall.java @@ -0,0 +1,127 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandler; +import org.onap.msb.sdk.httpclient.metric.MetricObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import okhttp3.Request; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +public class ProxyRetrofitCall implements Call { + + private static final Logger logger = LoggerFactory.getLogger(ProxyRetrofitCall.class); + + private Call targetCall; + + private RetrofitServiceHandler handler; + + private ServiceHttpEndPointObject endPoint; + + private Object proxy; + + private Method method; + + private Object[] args; + + private MetricObject metricObject; + + + + public ProxyRetrofitCall(Call targetCall, RetrofitServiceHandler retrofitServiceHandler, + ServiceHttpEndPointObject endPoint, Object proxy, Method method, Object[] args, + MetricObject metricObject) { + super(); + this.targetCall = targetCall; + this.handler = retrofitServiceHandler; + this.endPoint = endPoint; + this.proxy = proxy; + this.method = method; + this.args = args; + this.metricObject = metricObject; + } + + @Override + public Response execute() throws IOException { + + + try { + return targetCall.execute(); + } catch (Exception e) { + + logger.warn("first invoke httpclient error,endPoint:{},method:{},msg:{}", endPoint, method, + e.getMessage()); + + // 清理残留的endpoint记录 + handler.clean(); + try { + return ((Call) handler.reInvoke(proxy, method, args, endPoint)).execute(); + } catch (IOException e1) { + logger.error("sencond invoke httpclient error,endPoint:{},method:{}", endPoint, method, e1); + throw e1; + } catch (Throwable e2) { + logger.error("sencond invoke httpclient error,endPoint:{},method:{}", endPoint, method, e2); + throw e; + } + + + + } finally { + + } + + } + + @Override + public void enqueue(Callback callback) { + targetCall.enqueue(callback); + } + + @Override + public boolean isExecuted() { + return targetCall.isExecuted(); + } + + @Override + public void cancel() { + targetCall.cancel(); + + } + + @Override + public boolean isCanceled() { + // TODO Auto-generated method stub + return targetCall.isCanceled(); + } + + @Override + public Call clone() { + // TODO Auto-generated method stub + return new ProxyRetrofitCall(targetCall.clone(), this.handler, this.endPoint, this.proxy, + this.method, this.args, metricObject); + } + + @Override + public Request request() { + return targetCall.request(); + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceCreater.java b/src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceCreater.java new file mode 100644 index 0000000..413189c --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceCreater.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.List; + +import org.onap.msb.sdk.httpclient.conf.HttpClientConf; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerFactory; +import org.onap.msb.sdk.httpclient.msb.MSBServiceWrapperClient; + +/** + * @author 10071214 + * + */ +public class RetrofitServiceCreater { + + + private RetrofitServiceHandlerFactory factory = new RetrofitServiceHandlerFactory(); + + private MSBServiceWrapperClient msbClient; + + + public RetrofitServiceCreater(HttpClientConf globalHttpClientConf, + MSBServiceWrapperClient msbClient) { + + RetrofitServiceHandlerContext.setGlobalHttpClientConf(globalHttpClientConf); + this.msbClient = msbClient; + + factory.init(); + + + } + + public T createRetrofitService(Class retrofitSrvInterfaceClazz, + ServiceHttpEndPointBeanObject serviceHttpEndPointBeanObject) { + + InvocationHandler handler = factory.buildInvocationHandler(retrofitSrvInterfaceClazz, + serviceHttpEndPointBeanObject, null, msbClient); + + List> clazzList = new ArrayList<>(); + clazzList.add(retrofitSrvInterfaceClazz); + + Object targetInterface = Proxy.newProxyInstance(retrofitSrvInterfaceClazz.getClassLoader(), + clazzList.toArray(new Class[] {}), handler); + + return (T) targetInterface; + } + + + public T createRetrofitService(Class retrofitSrvInterfaceClazz, + ServiceHttpEndPointBeanObject serviceHttpEndPointBeanObject, HttpClientConf httpClientConf) { + + + InvocationHandler handler = factory.buildInvocationHandler(retrofitSrvInterfaceClazz, + serviceHttpEndPointBeanObject, httpClientConf, msbClient); + + List> clazzList = new ArrayList<>(); + clazzList.add(retrofitSrvInterfaceClazz); + + Object targetInterface = Proxy.newProxyInstance(retrofitSrvInterfaceClazz.getClassLoader(), + clazzList.toArray(new Class[] {}), handler); + + return (T) targetInterface; + } + + public T createRetrofitService(Class retrofitSrvInterfaceClazz, + HttpClientConf httpClientConf) { + + + InvocationHandler handler = + factory.buildInvocationHandler(retrofitSrvInterfaceClazz, null, httpClientConf, msbClient); + + List> clazzList = new ArrayList<>(); + clazzList.add(retrofitSrvInterfaceClazz); + + Object targetInterface = Proxy.newProxyInstance(retrofitSrvInterfaceClazz.getClassLoader(), + clazzList.toArray(new Class[] {}), handler); + + return (T) targetInterface; + } + + + public T createRetrofitService(Class retrofitSrvInterfaceClazz) { + + + InvocationHandler handler = + factory.buildInvocationHandler(retrofitSrvInterfaceClazz, null, null, msbClient); + + List> clazzList = new ArrayList<>(); + clazzList.add(retrofitSrvInterfaceClazz); + + Object targetInterface = Proxy.newProxyInstance(retrofitSrvInterfaceClazz.getClassLoader(), + clazzList.toArray(new Class[] {}), handler); + + return (T) targetInterface; + } + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceUtils.java b/src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceUtils.java new file mode 100644 index 0000000..229efd8 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/RetrofitServiceUtils.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient; + +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.onap.msb.sdk.httpclient.conf.HttpClientConf; + +import okhttp3.OkHttpClient; + +/** + * @author 10071214 + * + */ +public class RetrofitServiceUtils { + + + + private static Map httpMap = new HashMap<>(); + + private static Map httpsMap = new HashMap<>(); + + public synchronized static OkHttpClient buildDefaultOkHttpsClient(HttpClientConf httpClientConf) + throws Exception { + + if (!httpsMap.containsKey(httpClientConf)) { + OkHttpClient httpsOkHttpClient = buildOkHttpsClient(httpClientConf); + httpsMap.put(httpClientConf, httpsOkHttpClient); + } + return httpsMap.get(httpClientConf); + } + + + public synchronized static OkHttpClient buildDefaultOkHttpClient(HttpClientConf httpClientConf) + throws Exception { + + if (!httpMap.containsKey(httpClientConf)) { + OkHttpClient httpOkHttpClient = buildOkHttpClient(httpClientConf); + httpMap.put(httpClientConf, httpOkHttpClient); + } + + return httpMap.get(httpClientConf); + } + + + + private static OkHttpClient buildOkHttpsClient(HttpClientConf httpClientConf) throws Exception { + + if (httpClientConf == null) { + httpClientConf = new HttpClientConf(); + } + + TrustManager[] trustManager = new TrustManager[] {new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException {} + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException {} + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }}; + + SSLContext sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, trustManager, new SecureRandom()); + SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); + + + + return new OkHttpClient.Builder() + .connectTimeout(httpClientConf.getConnectTimeout(), TimeUnit.MILLISECONDS) + .readTimeout(httpClientConf.getReadTimeout(), TimeUnit.MILLISECONDS) + .writeTimeout(httpClientConf.getWriteTimeout(), TimeUnit.MILLISECONDS) + .sslSocketFactory(sslSocketFactory).hostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }).build(); + } + + + private static OkHttpClient buildOkHttpClient(HttpClientConf httpClientConf) throws Exception { + + if (httpClientConf == null) { + httpClientConf = new HttpClientConf(); + } + + return new OkHttpClient.Builder() + .connectTimeout(httpClientConf.getConnectTimeout(), TimeUnit.MILLISECONDS) + .readTimeout(httpClientConf.getReadTimeout(), TimeUnit.MILLISECONDS) + .writeTimeout(httpClientConf.getWriteTimeout(), TimeUnit.MILLISECONDS).build(); + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointBeanObject.java b/src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointBeanObject.java new file mode 100644 index 0000000..4e36a83 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointBeanObject.java @@ -0,0 +1,107 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient; + +public class ServiceHttpEndPointBeanObject { + + // 在MSB上注册的服务名 + private String serviceName; + // 在MSB注册的版本号 + private String serviceVersion; + // 在通过msb转发时,所用的协议 + private String msbProtocl = "https"; + + // 服务间点对点访问时,所用的协议 + private String clientProtocl = "http"; + + // 服务所在的租户名 + private String nameSpace = ""; + + // 服务的可见范围,系统间:“0”,系统内:“1”(默认),可配置多个,以 | 分隔 + private String visualRange = "0"; + + // 在MSB上注册的服务类型 + private String serverType = "api"; + + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getServiceVersion() { + return serviceVersion; + } + + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = serviceVersion; + } + + + public String getServerType() { + return serverType; + } + + public void setServerType(String serverType) { + this.serverType = serverType; + } + + + + public String getMsbProtocl() { + return msbProtocl; + } + + public void setMsbProtocl(String msbProtocl) { + this.msbProtocl = msbProtocl; + } + + public String getNameSpace() { + return nameSpace; + } + + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + public String getVisualRange() { + return visualRange; + } + + public void setVisualRange(String visualRange) { + this.visualRange = visualRange; + } + + public String getClientProtocl() { + return clientProtocl; + } + + public void setClientProtocl(String clientProtocl) { + this.clientProtocl = clientProtocl; + } + + @Override + public String toString() { + return "ServiceHttpEndPointBeanObject [serviceName=" + serviceName + ", serviceVersion=" + + serviceVersion + ", msbProtocl=" + msbProtocl + ", clientProtocl=" + clientProtocl + + ", nameSpace=" + nameSpace + ", visualRange=" + visualRange + ", serverType=" + serverType + + "]"; + } + + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointObject.java b/src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointObject.java new file mode 100644 index 0000000..8ac5086 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/ServiceHttpEndPointObject.java @@ -0,0 +1,186 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient; + +import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo; +import org.onap.msb.sdk.discovery.entity.NodeInfo; + +/** + * @author hu.rui + * + */ +public class ServiceHttpEndPointObject { + + + private String serviceName; + + private String serviceVersion; + + private String ip; + + private String port; + + private String protocl = "http"; + + private String nameSpace = ""; + + private NodeInfo nodeInfo; + + private MicroServiceFullInfo cloneFullInfo; + + + public ServiceHttpEndPointObject(String serviceName, String serviceVersion, NodeInfo nodeInfo, + MicroServiceFullInfo cloneFullInfo) { + + this.serviceName = serviceName; + this.serviceVersion = serviceVersion; + this.nodeInfo = nodeInfo; + this.cloneFullInfo = cloneFullInfo; + + this.ip = nodeInfo.getIp(); + this.port = nodeInfo.getPort(); + + } + + + + public String getServiceName() { + return serviceName; + } + + + + public String getServiceVersion() { + return serviceVersion; + } + + + + public String getIp() { + return ip; + } + + + + public String getPort() { + return port; + } + + + + public NodeInfo getNodeInfo() { + return nodeInfo; + } + + + + public MicroServiceFullInfo getCloneFullInfo() { + return cloneFullInfo; + } + + + + public String getProtocl() { + return protocl; + } + + + + public void setProtocl(String protocl) { + this.protocl = protocl; + } + + + + public String getNameSpace() { + return nameSpace; + } + + + + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((ip == null) ? 0 : ip.hashCode()); + result = prime * result + ((nameSpace == null) ? 0 : nameSpace.hashCode()); + result = prime * result + ((port == null) ? 0 : port.hashCode()); + result = prime * result + ((protocl == null) ? 0 : protocl.hashCode()); + result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); + result = prime * result + ((serviceVersion == null) ? 0 : serviceVersion.hashCode()); + return result; + } + + + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ServiceHttpEndPointObject other = (ServiceHttpEndPointObject) obj; + if (ip == null) { + if (other.ip != null) + return false; + } else if (!ip.equals(other.ip)) + return false; + if (nameSpace == null) { + if (other.nameSpace != null) + return false; + } else if (!nameSpace.equals(other.nameSpace)) + return false; + if (port == null) { + if (other.port != null) + return false; + } else if (!port.equals(other.port)) + return false; + if (protocl == null) { + if (other.protocl != null) + return false; + } else if (!protocl.equals(other.protocl)) + return false; + if (serviceName == null) { + if (other.serviceName != null) + return false; + } else if (!serviceName.equals(other.serviceName)) + return false; + if (serviceVersion == null) { + if (other.serviceVersion != null) + return false; + } else if (!serviceVersion.equals(other.serviceVersion)) + return false; + return true; + } + + + + @Override + public String toString() { + return "ServiceHttpEndPointObject [serviceName=" + serviceName + ", serviceVersion=" + + serviceVersion + ", ip=" + ip + ", port=" + port + ", protocl=" + protocl + ", nameSpace=" + + nameSpace + ", nodeInfo=" + nodeInfo + ", cloneFullInfo=" + cloneFullInfo + "]"; + } + + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/annotaion/BodyConverter.java b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/BodyConverter.java new file mode 100644 index 0000000..9a1cacc --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/BodyConverter.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.annotaion; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author hu.rui + * + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface BodyConverter { + String builderClassName() default "com.zte.ums.zenap.httpclient.retrofit.convert.jackson.JacksonConverterFactoryBuilder"; +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/annotaion/ConnectionParams.java b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/ConnectionParams.java new file mode 100644 index 0000000..bfbead6 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/ConnectionParams.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.annotaion; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author 10071214 + * + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface ConnectionParams { + + long readTimeout() default 180 * 1000; + + long connectTimeout() default 20 * 1000; + + long writeTimeout() default 10 * 1000; + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/annotaion/LoadBalance.java b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/LoadBalance.java new file mode 100644 index 0000000..eb9d507 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/LoadBalance.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.annotaion; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author hu.rui + * + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface LoadBalance { + + public enum LBSTYLE { + CLIENT, MSB + }; + + LBSTYLE lbStyle() default LBSTYLE.CLIENT; + + String lbClassName() default "com.zte.ums.zenap.httpclient.retrofit.lb.RoundRobinLBStrategy"; +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/annotaion/ServiceHttpEndPoint.java b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/ServiceHttpEndPoint.java new file mode 100644 index 0000000..1764503 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/annotaion/ServiceHttpEndPoint.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.annotaion; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 服务名和版本号不同,接口名就需要不同 + * + * @author hu.rui + * + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface ServiceHttpEndPoint { + + // 在MSB上注册的服务名 + String serviceName(); + + // 在MSB注册的版本号 + String serviceVersion(); + + // 在通过msb转发时,所用的协议 + String msbProtocl() default "https"; + + // 服务间点对点访问时,所用的协议 + String clientProtocl() default "http"; + + // 服务所在的租户名 + String nameSpace() default ""; + + // 服务的可见范围,系统间:“0”,系统内:“1”(默认),可配置多个,以 | 分隔 + String visualRange() default "1"; + + // 在MSB上注册的服务类型 + String serverType() default "api"; + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/builder/IRetrofitObjectBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/builder/IRetrofitObjectBuilder.java new file mode 100644 index 0000000..9af16be --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/builder/IRetrofitObjectBuilder.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.builder; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointObject; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; + +/** + * @author 10071214 + * + */ +public interface IRetrofitObjectBuilder { + + Map buildRetrofitObject( + AtomicReference> endPointToRetrofitRef, + ServiceHttpEndPointObject lastEndPoint) throws RetrofitServiceRuntimeException; + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/builder/impl/ClientRetrofitObjectBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/builder/impl/ClientRetrofitObjectBuilder.java new file mode 100644 index 0000000..e7f7cd5 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/builder/impl/ClientRetrofitObjectBuilder.java @@ -0,0 +1,181 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.builder.impl; + +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo; +import org.onap.msb.sdk.discovery.entity.NodeInfo; +import org.onap.msb.sdk.httpclient.RetrofitServiceUtils; +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointBeanObject; +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointObject; +import org.onap.msb.sdk.httpclient.builder.IRetrofitObjectBuilder; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; + +import okhttp3.OkHttpClient; +import retrofit2.Retrofit; + +/** + * @author 10071214 + * + */ +public class ClientRetrofitObjectBuilder implements IRetrofitObjectBuilder { + + + private RetrofitServiceHandlerContext context; + + + public ClientRetrofitObjectBuilder(RetrofitServiceHandlerContext context) { + super(); + this.context = context; + } + + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.httpclient.retrofit.builder.IRetrofitObjectBuilder#buildRetrofitObject(java. + * util.concurrent.atomic.AtomicReference) + */ + @Override + public Map buildRetrofitObject( + AtomicReference> endPointToRetrofitRef, + ServiceHttpEndPointObject lastEndPoint) throws RetrofitServiceRuntimeException { + + Map srvEndPointToRetrofit = endPointToRetrofitRef.get(); + if (srvEndPointToRetrofit == null) { + srvEndPointToRetrofit = new LinkedHashMap<>(); + try { + + + ServiceHttpEndPointBeanObject srvhttpEndPointBeanObject = + context.getServiceHttpEndPointBeanObject(); + + // MsbClientFactory msbClient = context.getLocator().getService(MsbClientFactory.class); + + MicroServiceFullInfo fullInfo = null; + + fullInfo = + context.getMsbClient().queryMicroServiceInfo(srvhttpEndPointBeanObject.getServiceName(), + srvhttpEndPointBeanObject.getServiceVersion()); + + + for (NodeInfo nodeInfo : fullInfo.getNodes()) { + + MicroServiceFullInfo cloneFullInfo = cloneFullInfo(fullInfo, nodeInfo); + + ServiceHttpEndPointObject endPointObj = + new ServiceHttpEndPointObject(srvhttpEndPointBeanObject.getServiceName(), + srvhttpEndPointBeanObject.getServiceVersion(), nodeInfo, cloneFullInfo); + + // 目前支持http + String baseUrl = null; + if (fullInfo.getUrl() == null || fullInfo.getUrl().trim().length() == 0 + || fullInfo.getUrl().equals("/")) { + baseUrl = String.format("http://%s:%s/", nodeInfo.getIp(), nodeInfo.getPort()); + } else { + baseUrl = String.format("http://%s:%s%s/", nodeInfo.getIp(), nodeInfo.getPort(), + fullInfo.getUrl()); + } + + OkHttpClient httpClient = null; + + if (context.getHttpClientConf() != null) { + if (srvhttpEndPointBeanObject.getClientProtocl().toLowerCase().equals("https")) { + httpClient = + RetrofitServiceUtils.buildDefaultOkHttpsClient(context.getHttpClientConf()); + } else { + httpClient = + RetrofitServiceUtils.buildDefaultOkHttpClient(context.getHttpClientConf()); + } + } else { + if (srvhttpEndPointBeanObject.getClientProtocl().toLowerCase().equals("https")) { + httpClient = RetrofitServiceUtils.buildDefaultOkHttpsClient( + RetrofitServiceHandlerContext.getGlobalHttpClientConf()); + } else { + httpClient = RetrofitServiceUtils.buildDefaultOkHttpClient( + RetrofitServiceHandlerContext.getGlobalHttpClientConf()); + } + } + + + + Retrofit retrofit = new Retrofit.Builder().client(httpClient).baseUrl(baseUrl) + .addConverterFactory(context.getConverterFactoryBuilder().buildConverterFactory()) + .build(); + + srvEndPointToRetrofit.put(endPointObj, + retrofit.create(context.getRetrofitSrvInterfaceClazz())); + + } + + if (srvEndPointToRetrofit.isEmpty()) { + throw new RetrofitServiceRuntimeException( + "can't find service in msb,serviceName:" + srvhttpEndPointBeanObject.getServiceName() + + ",serviceVersion:" + srvhttpEndPointBeanObject.getServiceVersion()); + } + + if (lastEndPoint != null) { + srvEndPointToRetrofit.remove(lastEndPoint); + } + + if (srvEndPointToRetrofit.isEmpty()) { + throw new RetrofitServiceRuntimeException("can't find other service in msb,serviceName:" + + srvhttpEndPointBeanObject.getServiceName() + ",serviceVersion:" + + srvhttpEndPointBeanObject.getServiceVersion()); + } + + if (endPointToRetrofitRef.compareAndSet(null, srvEndPointToRetrofit)) { + context.setLastUpdateMsbTime(System.currentTimeMillis()); + } + + return endPointToRetrofitRef.get(); + + + } catch (Exception e) { + throw new RetrofitServiceRuntimeException("init Retrofit service map fail", e); + } + + } else { + return endPointToRetrofitRef.get(); + } + } + + + private MicroServiceFullInfo cloneFullInfo(MicroServiceFullInfo fullInfo, NodeInfo nodeInfo) { + + MicroServiceFullInfo cloneFuleInfo = new MicroServiceFullInfo(); + cloneFuleInfo.setMetadata(fullInfo.getMetadata()); + cloneFuleInfo.setProtocol(fullInfo.getProtocol()); + cloneFuleInfo.setServiceName(fullInfo.getServiceName()); + cloneFuleInfo.setStatus(fullInfo.getStatus()); + cloneFuleInfo.setUrl(fullInfo.getUrl()); + cloneFuleInfo.setVersion(fullInfo.getVersion()); + cloneFuleInfo.setVisualRange(fullInfo.getVisualRange()); + Set nodeInfos = new HashSet<>(); + nodeInfos.add(nodeInfo); + cloneFuleInfo.setNodes(nodeInfos); + return cloneFuleInfo; + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/conf/HttpClientConf.java b/src/main/java/org/onap/msb/sdk/httpclient/conf/HttpClientConf.java new file mode 100644 index 0000000..f3e5006 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/conf/HttpClientConf.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.conf; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author 10071214 + * + */ +public class HttpClientConf { + + @JsonProperty + private long readTimeout = 180 * 1000; + + @JsonProperty + private long connectTimeout = 20 * 1000; + + @JsonProperty + private long writeTimeout = 10 * 1000; + + + public long getReadTimeout() { + return readTimeout; + } + + public long getConnectTimeout() { + return connectTimeout; + } + + public long getWriteTimeout() { + return writeTimeout; + } + + public void setReadTimeout(long readTimeout) { + this.readTimeout = readTimeout; + } + + public void setConnectTimeout(long connectTimeout) { + this.connectTimeout = connectTimeout; + } + + public void setWriteTimeout(long writeTimeout) { + this.writeTimeout = writeTimeout; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (connectTimeout ^ (connectTimeout >>> 32)); + result = prime * result + (int) (readTimeout ^ (readTimeout >>> 32)); + result = prime * result + (int) (writeTimeout ^ (writeTimeout >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + HttpClientConf other = (HttpClientConf) obj; + if (connectTimeout != other.connectTimeout) + return false; + if (readTimeout != other.readTimeout) + return false; + if (writeTimeout != other.writeTimeout) + return false; + return true; + } + + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/convert/IConverterFactoryBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/convert/IConverterFactoryBuilder.java new file mode 100644 index 0000000..526392b --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/convert/IConverterFactoryBuilder.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.convert; + +import retrofit2.Converter; + +/** + * @author hu.rui + * + */ +public interface IConverterFactoryBuilder { + + Converter.Factory buildConverterFactory(); +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactory.java b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactory.java new file mode 100644 index 0000000..4170cbd --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactory.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * 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. + ******************************************************************************/ +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.onap.msb.sdk.httpclient.convert.jackson; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Converter; +import retrofit2.Retrofit; + +/** + * A {@linkplain Converter.Factory converter} which uses Jackson. + *

+ * Because Jackson is so flexible in the types it supports, this converter assumes that it can + * handle all types. If you are mixing JSON serialization with something else (such as protocol + * buffers), you must {@linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add this + * instance} last to allow the other converters a chance to see their types. + */ +public final class JacksonConverterFactory extends Converter.Factory { + /** Create an instance using a default {@link ObjectMapper} instance for conversion. */ + public static JacksonConverterFactory create() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); + return create(mapper); + } + + /** Create an instance using {@code mapper} for conversion. */ + public static JacksonConverterFactory create(ObjectMapper mapper) { + return new JacksonConverterFactory(mapper); + } + + private final ObjectMapper mapper; + + private JacksonConverterFactory(ObjectMapper mapper) { + if (mapper == null) + throw new NullPointerException("mapper == null"); + this.mapper = mapper; + } + + @Override + public Converter responseBodyConverter(Type type, Annotation[] annotations, + Retrofit retrofit) { + JavaType javaType = mapper.getTypeFactory().constructType(type); + ObjectReader reader = mapper.reader(javaType); + return new JacksonResponseBodyConverter<>(reader); + } + + @Override + public Converter requestBodyConverter(Type type, + Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { + JavaType javaType = mapper.getTypeFactory().constructType(type); + ObjectWriter writer = mapper.writerWithType(javaType); + return new JacksonRequestBodyConverter<>(writer); + } +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactoryBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactoryBuilder.java new file mode 100644 index 0000000..e0477ad --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonConverterFactoryBuilder.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.convert.jackson; + +import org.onap.msb.sdk.httpclient.convert.IConverterFactoryBuilder; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +import retrofit2.Converter.Factory; + +/** + * @author hu.rui + * + */ +public class JacksonConverterFactoryBuilder implements IConverterFactoryBuilder { + + private static ObjectMapper objectMapper = new ObjectMapper(); + static { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.httpclient.retrofit.convert.IConverterFactoryBuilder#buildConverterFactory() + */ + @Override + public Factory buildConverterFactory() { + return JacksonConverterFactory.create(objectMapper); + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonRequestBodyConverter.java b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonRequestBodyConverter.java new file mode 100644 index 0000000..516da82 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonRequestBodyConverter.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * 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. + ******************************************************************************/ +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.onap.msb.sdk.httpclient.convert.jackson; + +import java.io.IOException; + +import com.fasterxml.jackson.databind.ObjectWriter; + +import okhttp3.MediaType; +import okhttp3.RequestBody; +import retrofit2.Converter; + +final class JacksonRequestBodyConverter implements Converter { + private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); + + private final ObjectWriter adapter; + + JacksonRequestBodyConverter(ObjectWriter adapter) { + this.adapter = adapter; + } + + @Override + public RequestBody convert(T value) throws IOException { + byte[] bytes = adapter.writeValueAsBytes(value); + return RequestBody.create(MEDIA_TYPE, bytes); + } +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonResponseBodyConverter.java b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonResponseBodyConverter.java new file mode 100644 index 0000000..29ca49b --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/convert/jackson/JacksonResponseBodyConverter.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * 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. + ******************************************************************************/ +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.onap.msb.sdk.httpclient.convert.jackson; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.ObjectReader; + +import okhttp3.ResponseBody; +import retrofit2.Converter; + +final class JacksonResponseBodyConverter implements Converter { + + private static final Logger logger = LoggerFactory.getLogger(JacksonResponseBodyConverter.class); + + private final ObjectReader adapter; + + + + JacksonResponseBodyConverter(ObjectReader adapter) { + this.adapter = adapter; + } + + @Override + public T convert(ResponseBody value) throws IOException { + String src = null; + try { + src = value.string(); + return adapter.readValue(src); + } catch (IOException e) { + logger.error("parse responseBody error,body:" + src); + throw e; + } finally { + value.close(); + } + } +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/exception/RetrofitServiceRuntimeException.java b/src/main/java/org/onap/msb/sdk/httpclient/exception/RetrofitServiceRuntimeException.java new file mode 100644 index 0000000..1d57209 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/exception/RetrofitServiceRuntimeException.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.exception; + +/** + * @author hu.rui + * + */ +public class RetrofitServiceRuntimeException extends RuntimeException { + + + private static final long serialVersionUID = -3980528276111865693L; + + + public RetrofitServiceRuntimeException() { + super(); + } + + + public RetrofitServiceRuntimeException(String message) { + super(message); + } + + + public RetrofitServiceRuntimeException(String message, Throwable cause) { + super(message, cause); + } + + public RetrofitServiceRuntimeException(Throwable cause) { + super(cause); + } + + + protected RetrofitServiceRuntimeException(String message, Throwable cause, + boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/HandlerContextBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/HandlerContextBuilder.java new file mode 100644 index 0000000..58ec187 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/HandlerContextBuilder.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler; + +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; + +/** + * @author 10071214 + * + */ +public interface HandlerContextBuilder { + + + void build(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException; + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandler.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandler.java new file mode 100644 index 0000000..7b886d6 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandler.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import org.onap.msb.sdk.httpclient.ProxyRetrofitCall; +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointObject; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.lb.LoadBalanceContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jersey.repackaged.com.google.common.collect.Lists; +import retrofit2.Call; + +/** + * @author 10071214 + * + */ +public class RetrofitServiceHandler implements InvocationHandler { + + private final static Logger logger = LoggerFactory.getLogger(RetrofitServiceHandler.class); + private static long periodTime = 60; + + static { + try { + String periodStr = System.getenv("retrofit_route_cache_refresh_period"); + periodTime = periodStr != null ? Long.valueOf(periodStr) : 60; + logger.info("retrofit_route_cache_refresh_period:" + periodTime); + } catch (Exception e) { + logger.warn("", e); + } + + } + + + + private RetrofitServiceHandlerContext flowContext; + + private AtomicReference> endPointToRetrofitRef = + new AtomicReference(); + + public RetrofitServiceHandler(RetrofitServiceHandlerContext flowContext) { + super(); + this.flowContext = flowContext; + logger.info("retrofit_route_cache_refresh_period:" + periodTime); + } + + + /* + * (non-Javadoc) + * + * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, + * java.lang.Object[]) + */ + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + Object retrofitObject = null; + ServiceHttpEndPointObjectWapper wapper = null; + + updateMsbInfo(); + wapper = selectRetrofitObjectByLBStrategy( + flowContext.getRetrofitObjectBuilder().buildRetrofitObject(endPointToRetrofitRef, null), + method, args); + retrofitObject = wapper.retrofitObject; + + Object resultObjecct = method.invoke(retrofitObject, args); + + if (resultObjecct instanceof Call) { + Call targetCall = (Call) resultObjecct; + return new ProxyRetrofitCall(targetCall, this, wapper.endPoint, proxy, method, args, + flowContext.getMetricmanager().getMetricObject(method)); + } + return resultObjecct; + } + + + public Object reInvoke(Object proxy, Method method, Object[] args, + ServiceHttpEndPointObject endPoint) throws Throwable { + + + Object retrofitObject = null; + ServiceHttpEndPointObjectWapper wapper = null; + + updateMsbInfo(); + + Map serviceHttpEndPointObjectMap = + flowContext.getRetrofitObjectBuilder().buildRetrofitObject(endPointToRetrofitRef, endPoint); + + wapper = selectRetrofitObjectByLBStrategy(serviceHttpEndPointObjectMap, method, args); + + + + retrofitObject = wapper.retrofitObject; + + Object resultObjecct = method.invoke(retrofitObject, args); + + return resultObjecct; + + } + + private void updateMsbInfo() { + + + + if (System.currentTimeMillis() - flowContext.getLastUpdateMsbTime() > periodTime * 1000) { + clean(); + } + } + + public void clean() { + endPointToRetrofitRef.set(null); + } + + + private ServiceHttpEndPointObjectWapper selectRetrofitObjectByLBStrategy( + Map srvEndPointToRetrofit, Method method, Object[] args) + throws RetrofitServiceRuntimeException { + + LoadBalanceContext ctx = new LoadBalanceContext(); + ctx.setEndPoints(Lists.newArrayList(srvEndPointToRetrofit.keySet())); + ctx.setArgs(args); + ctx.setMethod(method); + ServiceHttpEndPointObject endPoint = flowContext.getLbStrategy().chooseEndPointObject(ctx); + return new ServiceHttpEndPointObjectWapper(endPoint, srvEndPointToRetrofit.get(endPoint)); + } + +} + + +class ServiceHttpEndPointObjectWapper { + + protected ServiceHttpEndPointObject endPoint; + protected Object retrofitObject; + + public ServiceHttpEndPointObjectWapper(ServiceHttpEndPointObject endPoint, + Object retrofitObject) { + super(); + this.endPoint = endPoint; + this.retrofitObject = retrofitObject; + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerContext.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerContext.java new file mode 100644 index 0000000..68ee16c --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerContext.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler; + +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointBeanObject; +import org.onap.msb.sdk.httpclient.annotaion.LoadBalance.LBSTYLE; +import org.onap.msb.sdk.httpclient.builder.IRetrofitObjectBuilder; +import org.onap.msb.sdk.httpclient.conf.HttpClientConf; +import org.onap.msb.sdk.httpclient.convert.IConverterFactoryBuilder; +import org.onap.msb.sdk.httpclient.lb.ILoadBalanceStrategy; +import org.onap.msb.sdk.httpclient.metric.MetricManager; +import org.onap.msb.sdk.httpclient.msb.MSBServiceWrapperClient; + + +/** + * @author 10071214 + * + */ +public class RetrofitServiceHandlerContext { + + private static HttpClientConf globalHttpClientConf; + + + + public static HttpClientConf getGlobalHttpClientConf() { + return globalHttpClientConf; + } + + public static void setGlobalHttpClientConf(HttpClientConf globalHttpClientConf) { + RetrofitServiceHandlerContext.globalHttpClientConf = globalHttpClientConf; + } + + private Class retrofitSrvInterfaceClazz; + + + private LBSTYLE lbStyle; + + private IConverterFactoryBuilder converterFactoryBuilder; + + + private ILoadBalanceStrategy lbStrategy; + + + private MetricManager metricmanager; + + private IRetrofitObjectBuilder retrofitObjectBuilder; + + private ServiceHttpEndPointBeanObject serviceHttpEndPointBeanObject = null; + + private long lastUpdateMsbTime; + + private HttpClientConf httpClientConf; + + private MSBServiceWrapperClient msbClient; + + + + public Class getRetrofitSrvInterfaceClazz() { + return retrofitSrvInterfaceClazz; + } + + public void setRetrofitSrvInterfaceClazz(Class retrofitSrvInterfaceClazz) { + this.retrofitSrvInterfaceClazz = retrofitSrvInterfaceClazz; + } + + + + public MSBServiceWrapperClient getMsbClient() { + return msbClient; + } + + public void setMsbClient(MSBServiceWrapperClient msbClient) { + this.msbClient = msbClient; + } + + public LBSTYLE getLbStyle() { + return lbStyle; + } + + public void setLbStyle(LBSTYLE lbStyle) { + this.lbStyle = lbStyle; + } + + public IConverterFactoryBuilder getConverterFactoryBuilder() { + return converterFactoryBuilder; + } + + public void setConverterFactoryBuilder(IConverterFactoryBuilder converterFactoryBuilder) { + this.converterFactoryBuilder = converterFactoryBuilder; + } + + + public ILoadBalanceStrategy getLbStrategy() { + return lbStrategy; + } + + public void setLbStrategy(ILoadBalanceStrategy lbStrategy) { + this.lbStrategy = lbStrategy; + } + + + public MetricManager getMetricmanager() { + return metricmanager; + } + + public void setMetricmanager(MetricManager metricmanager) { + this.metricmanager = metricmanager; + } + + public IRetrofitObjectBuilder getRetrofitObjectBuilder() { + return retrofitObjectBuilder; + } + + public void setRetrofitObjectBuilder(IRetrofitObjectBuilder retrofitObjectBuilder) { + this.retrofitObjectBuilder = retrofitObjectBuilder; + } + + public ServiceHttpEndPointBeanObject getServiceHttpEndPointBeanObject() { + return serviceHttpEndPointBeanObject; + } + + public void setServiceHttpEndPointBeanObject( + ServiceHttpEndPointBeanObject serviceHttpEndPointBeanObject) { + this.serviceHttpEndPointBeanObject = serviceHttpEndPointBeanObject; + } + + public long getLastUpdateMsbTime() { + return lastUpdateMsbTime; + } + + public void setLastUpdateMsbTime(long lastUpdateMsbTime) { + this.lastUpdateMsbTime = lastUpdateMsbTime; + } + + public HttpClientConf getHttpClientConf() { + return httpClientConf; + } + + public void setHttpClientConf(HttpClientConf httpClientConf) { + this.httpClientConf = httpClientConf; + } + + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerFactory.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerFactory.java new file mode 100644 index 0000000..fb78820 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/RetrofitServiceHandlerFactory.java @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler; + +import java.lang.reflect.InvocationHandler; +import java.util.List; + +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointBeanObject; +import org.onap.msb.sdk.httpclient.conf.HttpClientConf; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.impl.ConnectionParamsBuilder; +import org.onap.msb.sdk.httpclient.handler.impl.ConverterFactoryBuilder; +import org.onap.msb.sdk.httpclient.handler.impl.LBBuilder; +import org.onap.msb.sdk.httpclient.handler.impl.MetricmanagerBuilder; +import org.onap.msb.sdk.httpclient.handler.impl.RetrofitHandlerContextBuilder; +import org.onap.msb.sdk.httpclient.handler.impl.ServiceHttpEndPointBeanObjectBuilder; +import org.onap.msb.sdk.httpclient.msb.MSBServiceWrapperClient; + +import com.google.common.collect.Lists; + +/** + * @author 10071214 + * + */ + +public class RetrofitServiceHandlerFactory { + + private List builders = Lists.newArrayList(); + + public void init() { + + builders.add(new ServiceHttpEndPointBeanObjectBuilder()); + builders.add(new MetricmanagerBuilder()); + builders.add(new LBBuilder()); + builders.add(new ConnectionParamsBuilder()); + builders.add(new ConverterFactoryBuilder()); + builders.add(new RetrofitHandlerContextBuilder()); + + + } + + + + public InvocationHandler buildInvocationHandler(Class retrofitSrvInterfaceClazz, + ServiceHttpEndPointBeanObject serviceHttpEndPointBeanObject) + throws RetrofitServiceRuntimeException { + + RetrofitServiceHandlerContext ctx = new RetrofitServiceHandlerContext(); + ctx.setRetrofitSrvInterfaceClazz(retrofitSrvInterfaceClazz); + /* ctx.setLocator(locator); */ + ctx.setServiceHttpEndPointBeanObject(serviceHttpEndPointBeanObject); + + for (HandlerContextBuilder builder : builders) { + builder.build(ctx); + } + return new RetrofitServiceHandler(ctx); + } + + + public InvocationHandler buildInvocationHandler(Class retrofitSrvInterfaceClazz) + throws RetrofitServiceRuntimeException { + + RetrofitServiceHandlerContext ctx = new RetrofitServiceHandlerContext(); + ctx.setRetrofitSrvInterfaceClazz(retrofitSrvInterfaceClazz); + // ctx.setLocator(locator); + + for (HandlerContextBuilder builder : builders) { + builder.build(ctx); + } + return new RetrofitServiceHandler(ctx); + + } + + + + public InvocationHandler buildInvocationHandler(Class retrofitSrvInterfaceClazz, + ServiceHttpEndPointBeanObject serviceHttpEndPointBeanObject, HttpClientConf httpClientConf, + MSBServiceWrapperClient msbClient) { + + RetrofitServiceHandlerContext ctx = new RetrofitServiceHandlerContext(); + ctx.setRetrofitSrvInterfaceClazz(retrofitSrvInterfaceClazz); + // ctx.setLocator(locator); + ctx.setServiceHttpEndPointBeanObject(serviceHttpEndPointBeanObject); + + ctx.setHttpClientConf(httpClientConf); + ctx.setMsbClient(msbClient); + + for (HandlerContextBuilder builder : builders) { + builder.build(ctx); + } + return new RetrofitServiceHandler(ctx); + + } + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConnectionParamsBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConnectionParamsBuilder.java new file mode 100644 index 0000000..c479607 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConnectionParamsBuilder.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler.impl; + +import org.onap.msb.sdk.httpclient.annotaion.ConnectionParams; +import org.onap.msb.sdk.httpclient.conf.HttpClientConf; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.HandlerContextBuilder; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author 10071214 + * + */ +public class ConnectionParamsBuilder implements HandlerContextBuilder { + + + + private final static Logger logger = LoggerFactory.getLogger(ConnectionParamsBuilder.class); + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.httpclient.retrofit.handler.HandlerContextBuilder#build(com.zte.ums.zenap. + * httpclient.retrofit.handler.RetrofitServiceHandlerContext) + */ + @Override + public void build(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException { + + + Class retrofitSrvInterfaceClazz = ctx.getRetrofitSrvInterfaceClazz(); + + ConnectionParams connectionParams = + retrofitSrvInterfaceClazz.getAnnotation(ConnectionParams.class); + if (connectionParams != null && ctx.getHttpClientConf() == null) { + HttpClientConf httpClientConf = new HttpClientConf(); + httpClientConf.setConnectTimeout(connectionParams.connectTimeout()); + httpClientConf.setReadTimeout(connectionParams.readTimeout()); + httpClientConf.setWriteTimeout(connectionParams.writeTimeout()); + ctx.setHttpClientConf(httpClientConf); + } + + + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConverterFactoryBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConverterFactoryBuilder.java new file mode 100644 index 0000000..c8b5822 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ConverterFactoryBuilder.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler.impl; + +import org.onap.msb.sdk.httpclient.annotaion.BodyConverter; +import org.onap.msb.sdk.httpclient.convert.IConverterFactoryBuilder; +import org.onap.msb.sdk.httpclient.convert.jackson.JacksonConverterFactoryBuilder; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.HandlerContextBuilder; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author 10071214 + * + */ +public class ConverterFactoryBuilder implements HandlerContextBuilder { + + + private final static Logger logger = LoggerFactory.getLogger(ConverterFactoryBuilder.class); + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.versey.rpc.retrofit2.service.impl.handler.HandlerContextBuilder#build(com.zte + * .ums.zenap.versey.rpc.retrofit2.service.impl.handler.RetrofitServiceHandlerContext) + */ + @Override + public void build(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException { + initConverterFactoryBuilder(ctx); + + } + + private void initConverterFactoryBuilder(RetrofitServiceHandlerContext ctx) + throws RetrofitServiceRuntimeException { + + BodyConverter cvnverter = ctx.getRetrofitSrvInterfaceClazz().getAnnotation(BodyConverter.class); + IConverterFactoryBuilder converterFactoryBuilder; + if (cvnverter != null) { + try { + converterFactoryBuilder = + (IConverterFactoryBuilder) Class.forName(cvnverter.builderClassName()).newInstance(); + } catch (Exception e) { + logger.error("init converterFactoryBuilder error", e); + throw new RetrofitServiceRuntimeException("init converterFactoryBuilder error", e); + } + + } else { + converterFactoryBuilder = new JacksonConverterFactoryBuilder(); + } + + ctx.setConverterFactoryBuilder(converterFactoryBuilder); + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/LBBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/LBBuilder.java new file mode 100644 index 0000000..98b2a32 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/LBBuilder.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler.impl; + +import org.onap.msb.sdk.httpclient.annotaion.LoadBalance; +import org.onap.msb.sdk.httpclient.annotaion.LoadBalance.LBSTYLE; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.HandlerContextBuilder; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; +import org.onap.msb.sdk.httpclient.lb.ILoadBalanceStrategy; +import org.onap.msb.sdk.httpclient.lb.RoundRobinLBStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author 10071214 + * + */ +public class LBBuilder implements HandlerContextBuilder { + + + private final static Logger logger = LoggerFactory.getLogger(LBBuilder.class); + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.versey.rpc.retrofit2.service.impl.handler.HandlerContextBuilder#build(com.zte + * .ums.zenap.versey.rpc.retrofit2.service.impl.handler.RetrofitServiceHandlerContext) + */ + @Override + public void build(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException { + initlb(ctx); + + } + + private void initlb(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException { + LoadBalance lb = ctx.getRetrofitSrvInterfaceClazz().getAnnotation(LoadBalance.class); + + LBSTYLE lbStyle = null; + ILoadBalanceStrategy lbStrategy; + if (lb != null) { + lbStyle = lb.lbStyle(); + try { + lbStrategy = (ILoadBalanceStrategy) Class.forName(lb.lbClassName()).newInstance(); + } catch (Exception e) { + logger.error("init lb strategy error", e); + throw new RetrofitServiceRuntimeException("init lb strategy error", e); + + } + } else { + lbStyle = LBSTYLE.CLIENT; + lbStrategy = new RoundRobinLBStrategy(); + + } + + ctx.setLbStyle(lbStyle); + ctx.setLbStrategy(lbStrategy); + + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/MetricmanagerBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/MetricmanagerBuilder.java new file mode 100644 index 0000000..3dbe4e2 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/MetricmanagerBuilder.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler.impl; + +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.HandlerContextBuilder; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; +import org.onap.msb.sdk.httpclient.metric.MetricManager; + +/** + * @author 10071214 + * + */ +public class MetricmanagerBuilder implements HandlerContextBuilder { + + @Override + public void build(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException { + MetricManager metricmanager = new MetricManager(); + ctx.setMetricmanager(metricmanager); + metricmanager.initMetric(ctx.getRetrofitSrvInterfaceClazz()); + + } + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/RetrofitHandlerContextBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/RetrofitHandlerContextBuilder.java new file mode 100644 index 0000000..ba73079 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/RetrofitHandlerContextBuilder.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler.impl; + +import org.onap.msb.sdk.httpclient.builder.impl.ClientRetrofitObjectBuilder; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.HandlerContextBuilder; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; + +/** + * @author 10071214 + * + */ +public class RetrofitHandlerContextBuilder implements HandlerContextBuilder { + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.httpclient.retrofit.handler.HandlerContextBuilder#build(com.zte.ums.zenap. + * httpclient.retrofit.handler.RetrofitServiceHandlerContext) + */ + @Override + public void build(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException { + + // if (ctx.getLbStyle().equals(LBSTYLE.MSB)) { + // + // ctx.setRetrofitObjectBuilder(new MsbRetrofitObjectBuilder(ctx)); + // } else { + ctx.setRetrofitObjectBuilder(new ClientRetrofitObjectBuilder(ctx)); + // } + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ServiceHttpEndPointBeanObjectBuilder.java b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ServiceHttpEndPointBeanObjectBuilder.java new file mode 100644 index 0000000..5d4bdde --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/handler/impl/ServiceHttpEndPointBeanObjectBuilder.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +/** + * + */ +package org.onap.msb.sdk.httpclient.handler.impl; + +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointBeanObject; +import org.onap.msb.sdk.httpclient.annotaion.ServiceHttpEndPoint; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; +import org.onap.msb.sdk.httpclient.handler.HandlerContextBuilder; +import org.onap.msb.sdk.httpclient.handler.RetrofitServiceHandlerContext; + +/** + * @author 10071214 + * + */ +public class ServiceHttpEndPointBeanObjectBuilder implements HandlerContextBuilder { + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.versey.rpc.retrofit2.service.impl.handler.HandlerContextBuilder#build(com.zte + * .ums.zenap.versey.rpc.retrofit2.service.impl.handler.RetrofitServiceHandlerContext) + */ + @Override + public void build(RetrofitServiceHandlerContext ctx) throws RetrofitServiceRuntimeException { + + if (ctx.getServiceHttpEndPointBeanObject() == null) { + // 从注解上构建 + ServiceHttpEndPointBeanObject beanObject = + buildBeanObjectFromClassAnnotion(ctx.getRetrofitSrvInterfaceClazz()); + ctx.setServiceHttpEndPointBeanObject(beanObject); + } + + + } + + + private ServiceHttpEndPointBeanObject buildBeanObjectFromClassAnnotion( + Class retrofitSrvInterfaceClazz) { + + ServiceHttpEndPointBeanObject resultBeanObject = new ServiceHttpEndPointBeanObject(); + ServiceHttpEndPoint srvhttpEndPoint = + retrofitSrvInterfaceClazz.getAnnotation(ServiceHttpEndPoint.class); + resultBeanObject.setServerType(srvhttpEndPoint.serverType()); + resultBeanObject.setServiceName(srvhttpEndPoint.serviceName()); + resultBeanObject.setServiceVersion(srvhttpEndPoint.serviceVersion()); + + resultBeanObject.setClientProtocl(srvhttpEndPoint.clientProtocl()); + resultBeanObject.setMsbProtocl(srvhttpEndPoint.msbProtocl()); + if ("null".equals(srvhttpEndPoint.nameSpace())) { + resultBeanObject.setNameSpace(null); + } else { + resultBeanObject.setNameSpace(srvhttpEndPoint.nameSpace()); + } + + resultBeanObject.setVisualRange(srvhttpEndPoint.visualRange()); + + + return resultBeanObject; + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/lb/ILoadBalanceStrategy.java b/src/main/java/org/onap/msb/sdk/httpclient/lb/ILoadBalanceStrategy.java new file mode 100644 index 0000000..94ccd67 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/lb/ILoadBalanceStrategy.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.lb; + +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointObject; + +/** + * 每个实际的策略对象在运行中会保持单例 + * + * @author hu.rui + * + */ +public interface ILoadBalanceStrategy { + + ServiceHttpEndPointObject chooseEndPointObject(LoadBalanceContext lbCtx); + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/lb/LoadBalanceContext.java b/src/main/java/org/onap/msb/sdk/httpclient/lb/LoadBalanceContext.java new file mode 100644 index 0000000..ee46de5 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/lb/LoadBalanceContext.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.lb; + +import java.lang.reflect.Method; +import java.util.List; + +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointObject; + +/** + * @author hu.rui + * + */ +public class LoadBalanceContext { + + // 从msb上查询到的全部endPoint信息 + private List endPoints; + + private Object[] args; + + private Method method; + + + public Method getMethod() { + return method; + } + + public void setMethod(Method method) { + this.method = method; + } + + public List getEndPoints() { + return endPoints; + } + + public void setEndPoints(List endPoints) { + this.endPoints = endPoints; + } + + public Object[] getArgs() { + return args; + } + + public void setArgs(Object[] args) { + this.args = args; + } + + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/lb/RoundRobinLBStrategy.java b/src/main/java/org/onap/msb/sdk/httpclient/lb/RoundRobinLBStrategy.java new file mode 100644 index 0000000..efbd0ba --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/lb/RoundRobinLBStrategy.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.lb; + +import java.util.concurrent.atomic.AtomicLong; + +import org.onap.msb.sdk.httpclient.ServiceHttpEndPointObject; +import org.onap.msb.sdk.httpclient.exception.RetrofitServiceRuntimeException; + +/** + * @author hu.rui + * + */ +public class RoundRobinLBStrategy implements ILoadBalanceStrategy { + + private AtomicLong invokeCount = new AtomicLong(0); + + /* + * (non-Javadoc) + * + * @see + * com.zte.ums.zenap.httpclient.retrofit.lb.ILoadBalanceStrategy#chooseEndPointObject(com.zte.ums. + * zenap.httpclient.retrofit.lb.LoadBalanceContext) + */ + @Override + public ServiceHttpEndPointObject chooseEndPointObject(LoadBalanceContext lbCtx) { + + long invokecount = invokeCount.getAndIncrement(); + + if (lbCtx.getEndPoints().size() == 0) { + throw new RetrofitServiceRuntimeException("target endPoints is empty"); + } + + int mod = (int) (invokecount % lbCtx.getEndPoints().size()); + + return lbCtx.getEndPoints().get(mod); + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/metric/MetricManager.java b/src/main/java/org/onap/msb/sdk/httpclient/metric/MetricManager.java new file mode 100644 index 0000000..ee81723 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/metric/MetricManager.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.metric; + +import static com.codahale.metrics.MetricRegistry.name; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import com.codahale.metrics.JmxReporter; +import com.codahale.metrics.Meter; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.Slf4jReporter; +import com.codahale.metrics.Timer; + +/** + * @author hu.rui + * + */ +public class MetricManager { + + private static MetricRegistry registry = new MetricRegistry(); + + private static Slf4jReporter slf4jReporter; + + private static JmxReporter jmxReporter; + + static { + initMetricReporters(); + } + + protected Map timers = new HashMap<>(); + protected Map meters = new HashMap<>(); + protected Map exceptionmeters = new HashMap<>(); + + + + private static void initMetricReporters() { + + /* + * slf4jReporter = Slf4jReporter.forRegistry(registry) + * .outputTo(LoggerFactory.getLogger(RetrofitServiceHandler.class)) + * .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); + * slf4jReporter.start(10, TimeUnit.MINUTES); + */ + + jmxReporter = JmxReporter.forRegistry(registry).build(); + jmxReporter.start(); + + } + + public void initMetric(Class retrofitSrvInterfaceClazz) { + + for (Method method : retrofitSrvInterfaceClazz.getMethods()) { + + timers.put(method, registry.timer(chooseName(method, "timer"))); + meters.put(method, registry.meter(chooseName(method, "meter"))); + exceptionmeters.put(method, registry.meter(chooseName(method, "exception"))); + } + + + } + + private String chooseName(final Method method, final String... suffixes) { + return name(name(method.getDeclaringClass(), method.getName()), suffixes); + } + + public MetricObject getMetricObject(Method method) { + return new MetricObject(timers.get(method), meters.get(method), exceptionmeters.get(method)); + } + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/metric/MetricObject.java b/src/main/java/org/onap/msb/sdk/httpclient/metric/MetricObject.java new file mode 100644 index 0000000..7cc1473 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/metric/MetricObject.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.metric; + +import com.codahale.metrics.Meter; +import com.codahale.metrics.Timer; + +/** + * @author hu.rui + * + */ +public class MetricObject { + + public Timer timer; + public Meter meter; + public Meter exceptionmeter; + + public MetricObject(Timer timer, Meter meter, Meter exceptionmeter) { + super(); + this.timer = timer; + this.meter = meter; + this.exceptionmeter = exceptionmeter; + } + + + +} diff --git a/src/main/java/org/onap/msb/sdk/httpclient/msb/MSBServiceWrapperClient.java b/src/main/java/org/onap/msb/sdk/httpclient/msb/MSBServiceWrapperClient.java new file mode 100644 index 0000000..f72f711 --- /dev/null +++ b/src/main/java/org/onap/msb/sdk/httpclient/msb/MSBServiceWrapperClient.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * Copyright 2017 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + ******************************************************************************/ +package org.onap.msb.sdk.httpclient.msb; + +import java.util.concurrent.Callable; + +import org.onap.msb.sdk.discovery.MSBService; +import org.onap.msb.sdk.discovery.common.RouteException; +import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo; +import org.onap.msb.sdk.discovery.entity.MicroServiceInfo; +import org.onap.msb.sdk.discovery.entity.NodeAddress; +import org.onap.msb.sdk.discovery.entity.RouteResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class MSBServiceWrapperClient { + + private static final Logger logger = LoggerFactory.getLogger(MSBServiceWrapperClient.class); + + private String msbSvrAddress; + + private MSBService msbService = new MSBService(); + + private String nameSpace; + + public MSBServiceWrapperClient(String msbSvrIp, int msbSvrPort) { + super(); + this.msbSvrAddress = msbSvrIp + ":" + msbSvrPort; + + logger.info("msb service info:msbSvrAddress:{},nameSpace:{}", this.msbSvrAddress, + this.nameSpace); + + } + + public MicroServiceFullInfo queryMicroServiceInfo(String serviceName, String version) + throws RouteException { + + return invokeMsb(() -> msbService.queryMicroServiceInfo(msbSvrAddress, serviceName, version)); + + + } + + private V invokeMsb(Callable callable) throws RouteException { + try { + return callable.call(); + } catch (Exception e) { + logger.error("msb service info:msbSvrAddress:" + this.msbSvrAddress, e); + if (e instanceof RouteException) { + throw (RouteException) e; + } else { + throw new RuntimeException(e); + } + } + + } + + + /** + * 注册微服务-默认追加方式,在msb上注册服务信息,服务的信息都可以填充在MicroServiceInfo上,包括:租户的信息等 + * + * @param microServiceInfo 微服务注册实体类 + * @throws RouteException + * @return MicroServiceFullInfo + */ + public MicroServiceFullInfo registerMicroServiceInfo(MicroServiceInfo msinfo) + throws RouteException { + + return invokeMsb(() -> msbService.registerMicroServiceInfo(msbSvrAddress, msinfo)); + } + + + + /** + * 注册微服务,在msb上注册服务信息,服务的信息都可以填充在MicroServiceInfo上,包括:租户的信息等 + * + * @param microServiceInfo 微服务注册实体类 + * @param createOrUpdate true:新增或追加更新 ,false:重新添加 + * @throws RouteException + * @return MicroServiceFullInfo + */ + public MicroServiceFullInfo registerMicroServiceInfo(MicroServiceInfo msinfo, + boolean createOrUpdate) throws RouteException { + + return invokeMsb( + () -> msbService.registerMicroServiceInfo(msbSvrAddress, msinfo, createOrUpdate)); + } + + + + /** + * @Title cancelMicroServiceInfo + * @Description TODO(注销全部微服务) + * @param serviceName 服务名[必填,若自定义服务名包含/,用*代替] + * @param version 版本号[若无版本号,传空字符串] + * @throws RouteException + * @return RouteResult + */ + public RouteResult cancelMicroServiceInfo(String serviceName, String version) + throws RouteException { + return invokeMsb(() -> msbService.cancelMicroServiceInfo(msbSvrAddress, serviceName, version)); + } + + + + /** + * 注销单个微服务 + * + * @param serviceName 服务名[必填,若自定义服务名包含/,用*代替] + * @param version 版本号[若无版本号,传空字符串] + * @param ip + * @param port + * @throws RouteException + * @return RouteResult + */ + + public RouteResult cancelMicroServiceInfo(String serviceName, String version, String ip, + String port) throws RouteException { + + return invokeMsb( + () -> msbService.cancelMicroServiceInfo(msbSvrAddress, serviceName, version, ip, port)); + } + + + public String getMsbSvrAddress() { + return msbSvrAddress; + } + + + + /** + * 请求服务实例TTL健康检查,默认使用本租户的信息 + * + * @param serviceName 服务名 + * @param version 版本号[若无版本号,传空字符串] + * @param ip 实例IP + * @param port 实例端口 + * @throws RouteException + * @return CheckNode + */ + public NodeAddress healthCheckbyTTL(String serviceName, String version, String ip, String port) + throws RouteException { + + return invokeMsb( + () -> msbService.healthCheckbyTTL(msbSvrAddress, serviceName, version, ip, port)); + + } + + + +} -- cgit 1.2.3-korg