diff options
Diffstat (limited to 'msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util')
8 files changed, 0 insertions, 1172 deletions
diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/FileUtil.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/FileUtil.java deleted file mode 100644 index baf3a1a..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/FileUtil.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; - -public final class FileUtil { - - /** - * Read all the files under a folder - */ - public static File[] readFileFolder(String filepath) throws FileNotFoundException, IOException { - File file = new File(filepath); - if (file.isDirectory()) { - File[] filelist = file.listFiles(); - return filelist; - } - - return null; - } - - public static String readFile(String Path) throws IOException{ - BufferedReader reader = null; - String fileContent = ""; - try { - FileInputStream fileInputStream = new FileInputStream(Path); - InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); - reader = new BufferedReader(inputStreamReader); - String tempString = null; - while ((tempString = reader.readLine()) != null) { - fileContent += tempString; - } - reader.close(); - } catch (IOException e) { - throw e; - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - throw e; - } - } - } - return fileContent; - } -} diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/JacksonJsonUtil.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/JacksonJsonUtil.java deleted file mode 100644 index 5157187..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/JacksonJsonUtil.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -import java.util.List; - -import org.openo.msb.api.ApiRouteInfo; -import org.openo.msb.api.RouteServer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - - -public class JacksonJsonUtil { - - private static final Logger logger = LoggerFactory.getLogger(JacksonJsonUtil.class); - - private static ObjectMapper mapper; - - - public static synchronized ObjectMapper getMapperInstance() { - if (mapper == null) { - mapper = new ObjectMapper(); - } - return mapper; - } - - /** - * from java object to json - * @param obj - * @return json - * @throws Exception - */ - public static String beanToJson(Object obj) throws Exception { - String json=null; - try { - ObjectMapper objectMapper = getMapperInstance(); - objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - json =objectMapper.writeValueAsString(obj); - } catch (Exception e) { - logger.error("Class beanToJson faild"); - throw new Exception("Class beanToJson faild"); - } - return json; - } - - - - /** - * from json to java object - * @param json - * @param cls - * @return - * @throws Exception - */ - public static Object jsonToBean(String json, Class<?> cls) throws Exception { - Object vo =null; - try { - ObjectMapper objectMapper = getMapperInstance(); - objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - vo = objectMapper.readValue(json, cls); - - } catch (Exception e) { - logger.error(cls+" JsonTobean faild"); - throw new Exception(cls+" JsonTobean faild"); - } - return vo; - } - - /** - * from json to java List - * @param json - * @return - * @throws Exception - */ - public static List<ApiRouteInfo> jsonToListBean(String json) throws Exception { - List<ApiRouteInfo> vo =null; - try { - - ObjectMapper objectMapper = getMapperInstance(); - - - vo = objectMapper.readValue(json, new TypeReference<List<ApiRouteInfo>>() {}); - - } catch (Exception e) { - throw new Exception( "JSON_TO_BEAN_FAILD"); - } - return vo; - } - - public static void main(String[] args) { - RouteServer server=new RouteServer("127.0.0.1","80"); - try { - String json=beanToJson(server); - System.out.println(json); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - -} diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/JedisUtil.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/JedisUtil.java deleted file mode 100644 index 46d071e..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/JedisUtil.java +++ /dev/null @@ -1,220 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.util.PropertyResourceBundle; -import java.util.ResourceBundle; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; - - - -public final class JedisUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class); - private static String host = "127.0.0.1"; - private static int port = 6379; - private static int connectionTimeout = 2000; - private static int DEFAULT_DB_INDEX = 0; - - private static JedisPool jedisPool = null; - - public static String serverIp="127.0.0.1"; - - public static int serverPort=10080; - - public static String propertiesName="redis.properties"; - - public static String propertiesPath=""; - - - -public static void main(String[] args) { - -} - - private JedisUtil() { - // private constructor - - } - - private static void initialPool() { - try { - JedisPoolConfig config = new JedisPoolConfig(); - -// String pathtest=JedisUtil.class.getResource("").getPath(); -// String path ="/"+ pathtest.substring(0, pathtest.indexOf("assembly")).replace("file:/", "") +"assembly/"+defaultWorkspace; - - File propertiesFile = new File(propertiesPath); - - if (propertiesFile.exists()) { - - - BufferedInputStream inputStream =new BufferedInputStream(new FileInputStream(propertiesPath)); - ResourceBundle bundle =new PropertyResourceBundle(inputStream); - - if (bundle == null) { - throw new IllegalArgumentException( - "[redis.properties] is not found!"); - } - - - - String strHost = bundle.getString("redis.host"); - if(StringUtils.isNotEmpty(strHost)){ - host = strHost; - } - String strPort = bundle.getString("redis.port"); - if(StringUtils.isNotEmpty(strPort)){ - port = Integer.valueOf(strPort); - } - - - String strTimeout = bundle.getString("redis.connectionTimeout"); - if (StringUtils.isNotEmpty(strTimeout) ){ - connectionTimeout = Integer.valueOf(strTimeout); - } - -// serverIp=bundle.getString("server.ip"); - serverPort=Integer.valueOf(bundle.getString("server.port")); - - String strDbIndex = bundle.getString("redis.db_index"); - if (StringUtils.isNotEmpty(strDbIndex)) { - DEFAULT_DB_INDEX = Integer.valueOf(strDbIndex); - } - - String strMaxTotal = bundle.getString("redis.pool.maxTotal"); - if (StringUtils.isNotEmpty(strMaxTotal)) { - config.setMaxTotal(Integer.valueOf(strMaxTotal)); - } - - String strMaxIdle = bundle.getString("redis.pool.maxIdle"); - if (StringUtils.isNotEmpty(strMaxIdle)) { - config.setMaxIdle(Integer.valueOf(strMaxIdle)); - } - - String strMaxWaitMillis = bundle.getString("redis.pool.maxWaitMillis"); - if (StringUtils.isNotEmpty(strMaxWaitMillis)) { - config.setMaxWaitMillis(Long.valueOf(strMaxWaitMillis)); - } - - String strTestOnBorrow = bundle - .getString("redis.pool.testOnBorrow"); - if (StringUtils.isNotEmpty(strTestOnBorrow)) { - config.setTestOnBorrow(Boolean.valueOf(strTestOnBorrow)); - } - - String strTestOnReturn = bundle - .getString("redis.pool.testOnReturn"); - if (StringUtils.isNotEmpty(strTestOnReturn)) { - config.setTestOnReturn(Boolean.valueOf(strTestOnReturn)); - } - - } - - LOGGER.info("Redis server info: " + host + ":" + port); - LOGGER.info("nginx server info: " + serverIp + ":" + serverPort); - - -// ResourceBundle bundle = ResourceBundle.getBundle("conf.redis"); - - jedisPool = new JedisPool(config, host, port, connectionTimeout); - } catch (Exception e) { - LOGGER.error("Initiate Jedis pool failed!", e); - } - } - /** - * From the connection pool to obtain jedis instance, use the default database index number 0 - * @return - */ - public synchronized static Jedis borrowJedisInstance() { - if (jedisPool == null) { - initialPool(); - } - try { - if (jedisPool != null) { - Jedis resource = jedisPool.getResource(); - resource.select(DEFAULT_DB_INDEX); - return resource; - } else { - return null; - } - } catch (Exception e) { - LOGGER.error("Get Jedis from pool failed!", e); - return null; - } - } - /** - * From the connection pool to obtain jedis instance, using the specified database index number - * @return - */ - public synchronized static Jedis borrowJedisInstance(final int dbIndex) { - if (jedisPool == null) { - initialPool(); - } - try { - if (jedisPool != null) { - Jedis resource = jedisPool.getResource(); - resource.select(dbIndex); - return resource; - } else { - return null; - } - } catch (Exception e) { - LOGGER.error("Get Jedis from pool failed!", e); - return null; - } - } - - /** - * returned to the pool jedis instance - * @param jedis - */ - public static void returnJedisInstance(final Jedis jedis) { - if (jedis != null) { - jedis.close(); - } - } - - - /** - * @Title getJedis - * @Description TODO(From the connection pool to obtain jedis instance) - * @throws Exception - * @return Jedis - */ - public static Jedis getJedis() throws Exception{ - - - Jedis jedis = borrowJedisInstance(); - if (jedis == null) { - throw new Exception("fetch from jedis pool failed,null object!"); - - } - - return jedis; - - } - -}
\ No newline at end of file diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MetricsUtil.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MetricsUtil.java deleted file mode 100644 index df21f3e..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MetricsUtil.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -public class MetricsUtil { - - public static String adminContextPath = "http://127.0.0.1:8086/admin/metrics"; - - public static final int SC_OK = 200; -} diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MicroServiceDB.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MicroServiceDB.java deleted file mode 100644 index f2e2004..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MicroServiceDB.java +++ /dev/null @@ -1,428 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -import java.sql.Date; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.StringUtils; -import org.openo.msb.api.MicroServiceFullInfo; -import org.openo.msb.api.MicroServiceInfo; -import org.openo.msb.api.Node; -import org.openo.msb.api.NodeInfo; -import org.openo.msb.api.Service; -import org.openo.msb.wrapper.serviceListener.IMicroServiceChangeListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.Jedis; - -public class MicroServiceDB { - - private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceDB.class); - - private static MicroServiceDB instance = new MicroServiceDB(); - - private List<IMicroServiceChangeListener> serviceListenerlist = - new ArrayList<IMicroServiceChangeListener>(); - - private MicroServiceDB() {} - - public static MicroServiceDB getInstance() { - return instance; - } - - - public void addServiceChangeListener(IMicroServiceChangeListener listener) { - synchronized (serviceListenerlist) { - serviceListenerlist.add(listener); - } - } - - - public void removeServiceChangeListener(IMicroServiceChangeListener listener) { - synchronized (serviceListenerlist) { - serviceListenerlist.remove(listener); - } - } - - - public MicroServiceFullInfo[] getAllMicroServiceInstances() throws Exception { - Jedis jedis = null; - MicroServiceFullInfo[] microServiceList; - try { - jedis = JedisUtil.getJedis(); - - String routekey = - MicroServiceUtil.getPrefixedKey("","*", MicroServiceUtil.SUFFIX_PATH_INFO); - Set<String> serviceSet = jedis.keys(routekey); - microServiceList = new MicroServiceFullInfo[serviceSet.size()]; - - Pattern redisKeyPattern = MicroServiceUtil.getRedisKeyPattern(); - int i = 0; - for (String servicePath : serviceSet) { - Matcher matcher = redisKeyPattern.matcher(servicePath); - if (matcher.matches()) { - microServiceList[i] = getMicroServiceByJedis(jedis, matcher.group("servicename"),matcher.group("version"), ""); - i++; - } - } - } catch (Exception e) { - LOGGER.error("call redis throw exception", e); - throw new Exception("call redis throw exception:"+e.getMessage()); - } finally { - JedisUtil.returnJedisInstance(jedis); - } - - return microServiceList; - } - - public void saveMicroServiceInfo2Redis(MicroServiceInfo microServiceInfo,String serverPort) throws Exception { - // 1.1 set info - String serviceInfokey = - MicroServiceUtil.getServiceInfoKey(serverPort,microServiceInfo.getServiceName(), - microServiceInfo.getVersion()); - Map<String, String> serviceInfoMap = new HashMap<String, String>(); - serviceInfoMap.put("url", microServiceInfo.getUrl()); - serviceInfoMap.put("protocol", microServiceInfo.getProtocol()); - serviceInfoMap.put("visualRange",microServiceInfo.getVisualRange()); - serviceInfoMap.put("lb_policy",microServiceInfo.getLb_policy()); - serviceInfoMap.put("status", "1"); - - - - // 1.2 set lb info - String serviceLBkey = - MicroServiceUtil.getPrefixedKey(serverPort,microServiceInfo.getServiceName(), - microServiceInfo.getVersion(), MicroServiceUtil.ROUTE_PATH_LOADBALANCE); - - - Jedis jedis = null; - try { - jedis = JedisUtil.getJedis(); - // 2.1 save info - jedis.hmset(serviceInfokey, serviceInfoMap); - - - for(Node node:microServiceInfo.getNodes()){ - - String key=serviceLBkey+":"+node.getIp()+"-"+node.getPort(); - - Map<String,String> nodeMap = new HashMap<String,String>(); - - nodeMap.put("ip", node.getIp()); - nodeMap.put("port", node.getPort()); - nodeMap.put("ttl", Integer.toString(node.getTtl())); - long expiration_time=System.currentTimeMillis()+node.getTtl()*1000; - nodeMap.put("expiration", Long.toString(expiration_time)); - - if(jedis.keys(key).isEmpty()){ - nodeMap.put("created_at", Long.toString(System.currentTimeMillis())); - } -// else{ -// Map<String,String> nodeLBmap = jedis.hgetAll(key); -// nodeMap.put("created_at", nodeLBmap.get("created_at")); -// } - nodeMap.put("updated_at", Long.toString(System.currentTimeMillis())); - - jedis.hmset(key, nodeMap); - } - -// jedis.sadd(serviceLBkey, nodeArray); - - } catch (Exception e) { - LOGGER.error("save to redis throw exception", e); - throw new Exception("save to redis throw exception:"+e.getMessage()); - } finally { - JedisUtil.returnJedisInstance(jedis); - } - - - - } - - public void updateMicroServiceStatus(String serviceName, String version,String status) throws Exception{ - - - String serviceInfokey = MicroServiceUtil.getServiceInfoKey("",serviceName, version); - Map<String, String> serviceInfoMap = new HashMap<String, String>(); - serviceInfoMap.put("status", status); - - - Jedis jedis = null; - try { - jedis = JedisUtil.borrowJedisInstance(); - if (jedis == null) { - throw new Exception("fetch from jedis pool failed,null object!"); - } - jedis.hmset(serviceInfokey, serviceInfoMap); - } - catch (Exception e) { - LOGGER.error("update MicroService status throw exception", e); - throw new Exception("update MicroService status throw exception:"+e.getMessage()); - } finally { - JedisUtil.returnJedisInstance(jedis); - } - - } - - - public void updateMicroServiceNode2Redis(String serviceName, String version,String ip,String port,int ttl) throws Exception { - String serviceLBkey = - MicroServiceUtil.getPrefixedKey("",serviceName,version, MicroServiceUtil.ROUTE_PATH_LOADBALANCE); - - - Jedis jedis = null; - try { - jedis = JedisUtil.getJedis(); - - - String nodeKey=serviceLBkey+":"+ip+"-"+port; - Map<String,String> nodeLBmap = jedis.hgetAll(nodeKey); - - if(nodeLBmap.isEmpty()){ - throw new NullPointerException(" MicroService Node not fond "); - } - - - nodeLBmap.put("ttl", Integer.toString(ttl)); - long expiration_time=System.currentTimeMillis()+ttl*1000; - nodeLBmap.put("expiration", Long.toString(expiration_time)); - nodeLBmap.put("updated_at", Long.toString(System.currentTimeMillis())); - - jedis.hmset(nodeKey, nodeLBmap); - - - } - catch (NullPointerException e){ - throw e; - } - catch (Exception e) { - LOGGER.error("update MicroService Node throw exception", e); - throw new Exception("update MicroService Node throw exception:"+e.getMessage()); - } finally { - JedisUtil.returnJedisInstance(jedis); - } - } - - - public void noticeUpdateApiListener(String serviceName,String version,Service microServiceInfo,String serverPort) { - if (isNeedNotify(microServiceInfo)) { - for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onChange(serviceName,version, microServiceInfo,serverPort); - } - } - - } - - public void noticeUpdateStatusListener(Service microServiceInfo,String status) { - - for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onStatusChange(microServiceInfo.getServiceName(),microServiceInfo.getUrl(), - microServiceInfo.getVersion(),microServiceInfo.getProtocol(),status); - } - } - - - - public void noticeApiListener(Service microServiceInfo, String type,String serverPort) { - if (isNeedNotify(microServiceInfo)) { - - if ("ADD".equals(type)) { - for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onSave(microServiceInfo,serverPort); - } - } else if ("DELETE".equals(type)) { - for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onDelete(microServiceInfo.getServiceName(),microServiceInfo.getUrl(), - microServiceInfo.getVersion(),microServiceInfo.getProtocol(),serverPort); - } - } - - } - } - - - public MicroServiceFullInfo getMicroServiceInstance(String serviceName, String version,String serverPort) - throws Exception { - if (null == version || "null".equals(version)) { - version = ""; - } - - Jedis jedis = null; - MicroServiceFullInfo microServiceInfo = null; - - try { - jedis = JedisUtil.getJedis(); - - microServiceInfo= getMicroServiceByJedis(jedis,serviceName,version, serverPort); - - - } catch (Exception e) { - LOGGER.error("call redis throw exception", e); - throw new Exception("call redis throw exception:"+e.getMessage()); - } finally { - JedisUtil.returnJedisInstance(jedis); - } - - return microServiceInfo; - - } - - private MicroServiceFullInfo getMicroServiceByJedis(Jedis jedis,String serviceName, String version,String serverPort){ - MicroServiceFullInfo microServiceInfo = null; - String serviceInfoKey = MicroServiceUtil.getServiceInfoKey(serverPort,serviceName, version); - Map<String, String> infomap = jedis.hgetAll(serviceInfoKey); - if (!infomap.isEmpty()) { - microServiceInfo = new MicroServiceFullInfo(); - microServiceInfo.setServiceName(serviceName); - microServiceInfo.setVersion(version); - microServiceInfo.setUrl(infomap.get("url")); - microServiceInfo.setProtocol(infomap.get("protocol")); - microServiceInfo.setVisualRange(infomap.get("visualRange")); - microServiceInfo.setStatus(infomap.get("status")); - microServiceInfo.setLb_policy(infomap.get("lb_policy")); - - String nodeLBkey = - MicroServiceUtil.getPrefixedKey(serverPort,microServiceInfo.getServiceName(), - microServiceInfo.getVersion(), - MicroServiceUtil.ROUTE_PATH_LOADBALANCE); - - Set<String> nodeKeys=jedis.keys(nodeLBkey+":*"); - - Set<NodeInfo> nodes=new HashSet<NodeInfo>(); - for(String nodeKey:nodeKeys){ - Map<String,String> nodeLBmap = jedis.hgetAll(nodeKey); - NodeInfo nodeInfo=new NodeInfo(); - nodeInfo.setNodeId(serviceName+"_"+nodeLBmap.get("ip")+"_"+nodeLBmap.get("port")); - nodeInfo.setIp(nodeLBmap.get("ip")); - nodeInfo.setPort(nodeLBmap.get("port")); - nodeInfo.setTtl(Integer.parseInt(nodeLBmap.get("ttl"))); - nodeInfo.setCreated_at(new Date(Long.parseLong(nodeLBmap.get("created_at")))); - nodeInfo.setUpdated_at(new Date(Long.parseLong(nodeLBmap.get("updated_at")))); - nodeInfo.setExpiration(new Date(Long.parseLong(nodeLBmap.get("expiration")))); - - nodes.add(nodeInfo); - } - - microServiceInfo.setNodes(nodes); - } - - - - - return microServiceInfo; - } - - - public void deleteMicroService(String serviceName, String version,String serverPort) throws Exception { - if (null == version || "null".equals(version)) { - version = ""; - } - - Jedis jedis = null; - try { - jedis = JedisUtil.getJedis(); - String routekey = MicroServiceUtil.getPrefixedKey(serverPort,serviceName, version, "*"); - Set<String> infoSet = jedis.keys(routekey); - - if (infoSet.isEmpty()) { - LOGGER.error("delete MicroService FAIL:serviceName-" - + serviceName + ",version:" + version + " not fond "); - } - else{ - String[] paths = new String[infoSet.size()]; - - infoSet.toArray(paths); - - jedis.del(paths); - } - } catch (Exception e) { - LOGGER.error("call redis throw exception", e); - throw new Exception("call redis throw exception:"+e.getMessage()); - } finally { - JedisUtil.returnJedisInstance(jedis); - } - } - - public void deleteNode(String serviceName, String version, String ip,String port) throws Exception { - if (null == version || "null".equals(version)) { - version = ""; - } - - Jedis jedis = null; - try { - jedis = JedisUtil.getJedis(); - String serviceLBkey = - MicroServiceUtil.getPrefixedKey("",serviceName, version, - MicroServiceUtil.ROUTE_PATH_LOADBALANCE,ip+"-"+port); - jedis.del(serviceLBkey); - } catch (Exception e) { - LOGGER.error("call redis throw exception", e); - throw new Exception("call redis throw exception:"+e.getMessage()); - } finally { - JedisUtil.returnJedisInstance(jedis); - } - - } - - - /** - * Determine whether the service needs to send a notification - * TODO: filter according to the agreement, - * the only notice of agreement for REST \ UI interface MSB - REST - * @param protocol - * @return - */ - private boolean isNeedNotifyByProtocol(String protocol) { - return "UI".equalsIgnoreCase(protocol) || "REST".equalsIgnoreCase(protocol) || "HTTP".equalsIgnoreCase(protocol); - } - - /** - * Determine whether the service needs to send a notification - * TODO: according to the visual range filter conditions - * @param visualRange - * @return - */ - private boolean isNeedNotifyByVisualRange(String visualRange) { - String[] rangeArray=StringUtils.split(visualRange, "|"); - return RouteUtil.contain(RouteUtil.visualRangeMatches, rangeArray); - } - - /** - * According to the MicroServiceInfo entity information to judge whether need to send a notification - * @param microServiceInfo - * @return - */ - private boolean isNeedNotify(Service microServiceInfo) { - if (null != microServiceInfo) { - return isNeedNotifyByProtocol(microServiceInfo.getProtocol()) && - isNeedNotifyByVisualRange(microServiceInfo.getVisualRange()); - } else { - return false; - } - } - - - -} diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MicroServiceUtil.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MicroServiceUtil.java deleted file mode 100644 index 3da82ed..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/MicroServiceUtil.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; - - -public class MicroServiceUtil { - public static final String PREFIX_PATH = "discover:microservices"; - - public static final String PREFIX_PATH_PORT = "discover:"; - - public static final String SUFFIX_PATH_INFO = "info"; - - public static final String REDIS_KEY_PATTERN = - "discover:microservices:(?<servicename>[^:]+)(:(?<version>[^:]*))?:info"; - - public static final String REQUEST_SUCCESS = "SUCCESS"; - - public static final String REQUEST_FAIL = "FAIL"; - - public static final String ROUTE_PATH_LOADBALANCE = "lb"; // 负载均衡路径名 - - - public static String getPrefixedKey(String... paths) { - StringBuffer sb = new StringBuffer(); - - if(paths[0].trim().equals("") || paths[0].equals(String.valueOf(JedisUtil.serverPort))){ - sb.append(PREFIX_PATH); - } - else{ - sb.append(PREFIX_PATH_PORT).append(paths[0]); - } - - for (int i = 1; i < paths.length; i++) { - sb.append(":"); - sb.append(paths[i]); - } - return sb.toString(); - } - - - public static String getServiceInfoKey(String serverPort,String serviceName, String version) { - return getPrefixedKey(serverPort,serviceName, version, SUFFIX_PATH_INFO); - } - - - - - - public static Pattern getRedisKeyPattern() { - return Pattern.compile(REDIS_KEY_PATTERN); - } - - public static String getRealIp(HttpServletRequest request) { - String ip = request.getHeader("X-Forwarded-For"); - if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { - // After the reverse proxy can have multiple IP value for many times, the first IP is the real IP - int index = ip.indexOf(","); - if (index != -1) { - return ip.substring(0, index); - } else { - return ip; - } - } - ip = request.getHeader("X-Real-IP"); - - if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { - return ip; - } - - - return request.getRemoteAddr(); - - } - - -} diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/RegExpTestUtil.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/RegExpTestUtil.java deleted file mode 100644 index 90c8cba..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/RegExpTestUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -import java.util.regex.Pattern; - -public class RegExpTestUtil { - - - - public static boolean hostRegExpTest(String host){ - - String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)" - +":(\\d{1,5})$"; - return Pattern.matches(hostReg, host); - - } - - public static boolean ipRegExpTest(String ip){ - - String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"; - return Pattern.matches(hostReg, ip); - - } - - public static boolean portRegExpTest(String port){ - - String hostReg = "^\\d{1,5}$"; - return Pattern.matches(hostReg, port); - - } - -public static boolean versionRegExpTest(String version){ - - String versionReg = "^v\\d+(\\.\\d+)?$"; - return Pattern.matches(versionReg, version); - - } - -public static boolean urlRegExpTest(String url){ - if(url.equals("/")) return true; - - String urlReg = "^\\/.*((?!\\/).)$"; - return Pattern.matches(urlReg, url); - -} - -public static boolean apiRouteUrlRegExpTest(String url){ - - String urlReg = "^\\/"+RouteUtil.API_ROOT_PATH+"\\/.*$"; - return Pattern.matches(urlReg, url); - -} - -public static boolean iuiRouteUrlRegExpTest(String url){ - - String urlReg = "^\\/"+RouteUtil.IUI_ROOT_PATH+"\\/.*$"; - return Pattern.matches(urlReg, url); - -} - - - - - public static void main(String[] args) { - System.out.println(urlRegExpTest("/api ")); -// System.out.println("api".startsWith("/")); - } -} diff --git a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/RouteUtil.java b/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/RouteUtil.java deleted file mode 100644 index c987142..0000000 --- a/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/wrapper/util/RouteUtil.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright 2016 ZTE Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openo.msb.wrapper.util; - -import org.apache.commons.lang3.StringUtils; -import org.openo.msb.api.DiscoverInfo; - - -public class RouteUtil { - - public static String IUI_ROOT_PATH="iui"; - - public static String API_ROOT_PATH="api"; - - public static final String ROUTE_PATH="msb:routing"; - - public static final String APIROUTE="api"; - - public static final String IUIROUTE="iui"; - - public static final String CUSTOMROUTE="custom"; - - public static final String P2PROUTE="p2p"; - - - public static final String ROUTE_PATH_INFO="info"; - - public static final String ROUTE_PATH_LOADBALANCE="lb"; - - public static final String APIROUTE_PATH_LIFE="life"; - - - public static final String REQUEST_SUCCESS = "SUCCESS"; - - public static final String REQUEST_FAIL = "FAIL"; - - public static String PROTOCOL_LIST="REST,UI,HTTP,MQ,FTP,SNMP,TCP,UDP"; - - public static DiscoverInfo discoverInfo=new DiscoverInfo(); - - - public static String[] visualRangeRange={"0","1"}; - - public static String[] controlRangeMatches={"0","1","2"}; - - public static String[] statusRangeMatches={"0","1"}; - - public static String[] useOwnUpstreamRangeMatches={"0","1"}; - - public static String[] visualRangeMatches={"1"}; - - /** - * @Title: getPrefixedKey - * @Description: TODO(Add base path prefix radis assembly path) - * @param: @param serviceName - * @param: @param version - * @param: @param type - * @param: @return - * @return: String - */ - - public static String getPrefixedKey(String...paths){ - StringBuffer sb= new StringBuffer(); - - if(paths[0].trim().equals("") || paths[0].equals(String.valueOf(JedisUtil.serverPort))){ - sb.append(ROUTE_PATH); - } - else{ - sb.append(paths[0]); - } - - for (int i = 1; i < paths.length; i++) { - sb.append(":"); - sb.append(paths[i]); - } - return sb.toString(); - } - - - public static Object[] concat(Object[] a, Object[] b) { - Object[] c= new Object[a.length+b.length]; - System.arraycopy(a, 0, c, 0, a.length); - System.arraycopy(b, 0, c, a.length, b.length); - return c; - } - - public static boolean contain(String[] array,String str){ - for(int i=0;i<array.length;i++){ - if(array[i].equals(str)){ - return true; - } - } - return false; - - } - - public static boolean contain(String[] array,String value[]){ - for(int i=0;i<array.length;i++){ - for(int n=0;n<value.length;n++){ - if(array[i].equals(value[n])){ - return true; - } - } - } - return false; - - } - - public static String show(String[] array){ - - return StringUtils.join(array, "|"); - - } - - public static void main(String[] args) { - String array[]={"1","2"}; - System.out.println(StringUtils.join(array, "|")); - } - - -} |