msb protocol synch change
[msb/apigateway.git] / msb-core / apiroute / apiroute-service / src / main / java / org / openo / msb / wrapper / ServiceAccessWrapper.java
1 /**
2  * Copyright 2016 ZTE Corporation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openo.msb.wrapper;
17
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24
25 import org.openo.msb.api.ServiceAccessInfo;
26 import org.openo.msb.wrapper.util.JedisUtil;
27 import org.openo.msb.wrapper.util.RouteUtil;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import redis.clients.jedis.Jedis;
32
33 public class ServiceAccessWrapper {
34     private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAccessWrapper.class);
35
36     private static ServiceAccessWrapper instance = new ServiceAccessWrapper();
37
38     private ServiceAccessWrapper() {}
39
40     public static ServiceAccessWrapper getInstance() {
41         return instance;
42     }
43
44     public ServiceAccessInfo getApiServiceAccessAddr(String serviceName, String version, String host) {
45
46         ServiceAccessInfo apiRouteAccessInfo = null;
47
48         Jedis jedis = null;
49         try {
50             jedis = JedisUtil.borrowJedisInstance();
51             if (jedis == null) {
52                 throw new Exception("fetch from jedis pool failed,null object!");
53             }
54
55             if ("null".equals(version)) {
56                 version = "";
57             }
58
59             String routekey =
60                     RouteUtil.getPrefixedKey("",RouteUtil.APIROUTE, serviceName, version,
61                             RouteUtil.ROUTE_PATH_INFO);
62             Boolean isExist = jedis.exists(routekey);
63             if (isExist) {
64                 apiRouteAccessInfo = new ServiceAccessInfo();
65                 apiRouteAccessInfo.setServiceName(serviceName);
66                 apiRouteAccessInfo.setVersion(version);
67                 String accessAddr = "http://" + host + "/api/" + serviceName + "/" + version;
68                 apiRouteAccessInfo.setAccessAddr(accessAddr);
69             }
70         } catch (Exception e) {
71             LOGGER.error("call redis throw exception", e);
72         } finally {
73             JedisUtil.returnJedisInstance(jedis);
74         }
75         return apiRouteAccessInfo;
76
77     }
78
79     public List<ServiceAccessInfo> getApiRouteAccessAddr(String serviceType, String serviceName,
80             String version, String host) {
81         List<ServiceAccessInfo> serviceList = new ArrayList<ServiceAccessInfo>();
82         Jedis jedis = null;
83         try {
84             jedis = JedisUtil.borrowJedisInstance();
85             if (jedis == null) {
86                 throw new Exception("fetch from jedis pool failed,null object!");
87             }
88
89             String keyPattern = this.getRedisSearchPattern(serviceType, serviceName, version);
90             Set<String> infoKeys = jedis.keys(keyPattern);
91             Pattern pattern = this.getKeyPattern();
92             for (Iterator<String> iterator = infoKeys.iterator(); iterator.hasNext();) {
93                 String infoKey = (String) iterator.next();
94                 Matcher matcher = pattern.matcher(infoKey);
95                 if (matcher.matches()) {
96                     ServiceAccessInfo serviceAccessInfo = new ServiceAccessInfo();
97                     serviceAccessInfo.setServiceType(matcher.group("servicetype"));
98                     serviceAccessInfo.setServiceName(matcher.group("servicename"));
99                     serviceAccessInfo.setVersion(matcher.group("version"));
100                     this.buildServiceAccessAddr(serviceAccessInfo, host, infoKey, jedis);
101                     serviceList.add(serviceAccessInfo);
102                 }
103             }
104         } catch (Exception e) {
105             LOGGER.error("call redis throw exception", e);
106         } finally {
107             JedisUtil.returnJedisInstance(jedis);
108         }
109         return serviceList;
110
111     }
112
113     private void buildServiceAccessAddr(ServiceAccessInfo serviceAccessInfo, String host,
114             String infoKey, Jedis jedis) {
115         String serviceType = serviceAccessInfo.getServiceType();
116         StringBuffer accessAddr = new StringBuffer();
117         switch (serviceType) {
118             case RouteUtil.APIROUTE:
119                 accessAddr.append("http://").append(host).append(":").append(JedisUtil.serverPort)
120                         .append("/").append(serviceAccessInfo.getServiceType()).append("/")
121                         .append(serviceAccessInfo.getServiceName()).append("/")
122                         .append(serviceAccessInfo.getVersion());
123                 serviceAccessInfo.setAccessAddr(accessAddr.toString());
124                 break;
125             case RouteUtil.IUIROUTE:
126                 accessAddr.append("http://").append(host).append(":").append(JedisUtil.serverPort)
127                         .append("/").append(serviceAccessInfo.getServiceType()).append("/")
128                         .append(serviceAccessInfo.getServiceName());
129                 serviceAccessInfo.setAccessAddr(accessAddr.toString());
130                 break;
131             case RouteUtil.CUSTOMROUTE:
132                 accessAddr.append("http://").append(host).append(":").append(JedisUtil.serverPort)
133                         .append(serviceAccessInfo.getServiceName());
134                 serviceAccessInfo.setAccessAddr(accessAddr.toString());
135                 break;
136             case RouteUtil.P2PROUTE:
137                 accessAddr.append(jedis.hget(infoKey, "url"));
138                 serviceAccessInfo.setAccessAddr(accessAddr.toString());
139                 break;
140             default:
141                 serviceAccessInfo.setAccessAddr("not supported now");
142                 break;
143         }
144     }
145
146     private String getRedisSearchPattern(String serviceType, String serviceName, String version) {
147         StringBuffer sb = new StringBuffer();
148         sb.append(RouteUtil.ROUTE_PATH);
149         if (null != serviceType && !"".equals(serviceType)) {
150             sb.append(":").append(serviceType);
151         } else {
152             sb.append(":").append("*");
153         }
154         sb.append(":").append(serviceName);
155         if (null != version && !"".equals(version)) {
156             sb.append(":");
157             sb.append(version);
158             sb.append(":");
159         } else {
160             sb.append(":*");
161         }
162         sb.append(RouteUtil.ROUTE_PATH_INFO);
163         return sb.toString();
164     }
165
166     private Pattern getKeyPattern() {
167         String pStr =
168                 "conductor:routing:(?<servicetype>api|iui|custom|p2p):(?<servicename>[^:]+)(:(?<version>[^:]*))?:info";
169         return Pattern.compile(pStr);
170     }
171 }