From 1aeffd7ad7d8d81c55cfbe57f3443e813e3a6541 Mon Sep 17 00:00:00 2001 From: birdie7761 Date: Thu, 30 Aug 2018 15:19:21 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E8=A7=A3=E5=86=B3unchecked=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cs/component/ComponentManager.java | 431 +++++++++--------- .../framework/cs/jmx/VIDynamicMBean.java | 309 ++++++------- .../framework/cs/metrics/MetricsHandler.java | 184 ++++---- 3 files changed, 464 insertions(+), 460 deletions(-) diff --git a/cornerstone/src/main/java/com/ctrip/framework/cs/component/ComponentManager.java b/cornerstone/src/main/java/com/ctrip/framework/cs/component/ComponentManager.java index 833a9ab..c3ca855 100644 --- a/cornerstone/src/main/java/com/ctrip/framework/cs/component/ComponentManager.java +++ b/cornerstone/src/main/java/com/ctrip/framework/cs/component/ComponentManager.java @@ -1,215 +1,216 @@ -package com.ctrip.framework.cs.component; - -import com.ctrip.framework.cs.component.defaultComponents.HostInfo; -import com.ctrip.framework.cs.UserAction; -import com.ctrip.framework.cs.annotation.ComponentStatus; -import com.ctrip.framework.cs.annotation.FieldInfo; -import com.ctrip.framework.cs.jmx.VIDynamicMBean; -import com.ctrip.framework.cs.util.ArrayUtils; -import com.ctrip.framework.cs.util.ServerConnector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.management.InstanceAlreadyExistsException; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import java.lang.management.ManagementFactory; -import java.lang.reflect.*; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Created by jiang.j on 2016/3/30. - */ -public final class ComponentManager { - - private static ConcurrentHashMap> container = new ConcurrentHashMap<>(); - private static ConcurrentHashMap instances = new ConcurrentHashMap<>(); - private static Logger logger = LoggerFactory.getLogger(ComponentManager.class); - private static Map overrideFieldDescription = new ConcurrentHashMap<>(); - - private static Class hostInfoExtend =null; - - public static void setFieldDescription(String fieldId,String description){ - overrideFieldDescription.put(fieldId.toLowerCase(),description); - } - - public static void setHostInfoExtend(Class extend){ - hostInfoExtend = extend; - try { - instances.put(HostInfo.class.getName(),hostInfoExtend.newInstance()); - } catch (Throwable e) { - logger.warn("new hostInfoExtend failed, class:" + hostInfoExtend.getName(), e); - } - } - public static synchronized boolean add(Class cb){ - ComponentStatus comp = cb.getAnnotation(ComponentStatus.class); - if(comp!=null) { - String compId =comp.id().toLowerCase(); - if(container.putIfAbsent(compId, cb)==null) { - if (comp.singleton()) { - try { - instances.putIfAbsent(cb.getName(), cb.newInstance()); - } catch (Throwable e) { - logger.error("init component status failed", e); - return false; - } - } - } - }else{ - return false; - } - - if(comp.jmx()){ - logger.info(comp.id() + " register self to jmx"); - final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - try { - server.registerMBean(new VIDynamicMBean(cb), new ObjectName("VI:type=" + ServerConnector.getPort() - + (HostInfo.isTomcat()?System.getProperty("vi.context.path"):"") + ",name=" +cb.getSimpleName())); - } catch (InstanceAlreadyExistsException e) { - logger.info("VI JMX MBeans "+cb.getSimpleName() + " already exist!"); - }catch (Throwable e) { - logger.warn("VI JMX MBeans error",e); - } - - logger.info(comp.id() + " finish register!"); - } - return true; - } - - @Deprecated - public static synchronized void register(Class cb){ - add(cb); - } - - public static T getStatus(Class statusClass,String user){ - if(!container.values().contains(statusClass)) { - add(statusClass); - } - - - T rtn = (T) instances.get(statusClass.getName()); - if(rtn == null){ - try { - rtn = statusClass.newInstance(); - } catch (Throwable e) { - logger.error("init component status failed", e); - } - }else if(rtn instanceof Refreshable) { - ((Refreshable)rtn).refresh(); - } - - if(rtn instanceof UserAction){ - ((UserAction)rtn).userAction(user); - } - - return rtn; - } - public static T getStatus(Class statusClass){ - return getStatus(statusClass,""); - } - - - static Map> getAllComponents(){ - return container; - } - - static List> getComponentMeta(){ - - List> metas = new ArrayList<>(); - - for (Class component : container.values() ){ - - ComponentStatus comp = component.getAnnotation(ComponentStatus.class); - if(comp!=null){ - - Map meta = new HashMap<>(); - meta.put("id",comp.id().toLowerCase()); - meta.put("name",comp.name()); - meta.put("list", String.valueOf(comp.list())); - meta.put("custom", String.valueOf(comp.custom())); - meta.put("description",comp.description()); - metas.add(meta); - } - } - - return metas; - - } - - - static List> getFieldMeta(){ - - List> metas = new ArrayList<>(); - - for (Class component : container.values() ){ - - ComponentStatus comp = component.getAnnotation(ComponentStatus.class); - if(comp==null) { - continue; - } - - - Field[] fields; - - if(component.getGenericSuperclass() instanceof ParameterizedType){ - ParameterizedType parameterizedType = (ParameterizedType) component.getGenericSuperclass(); - fields = parameterizedType.getActualTypeArguments()[0].getClass().getDeclaredFields(); - }else{ - fields = component.getDeclaredFields(); - } - try { - if (hostInfoExtend != null && component.equals(HostInfo.class)) { - fields = ArrayUtils.concatenate(fields, hostInfoExtend.getDeclaredFields()); - } - }catch (Throwable e){ - logger.warn("concatenate hostinfo field failed!",e); - } - for(Field field : fields) { - if(Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())){ - continue; - } - - Map meta = new HashMap<>(); - String fieldId =comp.id().toLowerCase()+"."+field.getName(); - meta.put("id", fieldId); - FieldInfo finfo = field.getAnnotation(FieldInfo.class); - String name = field.getName(); - - String type = String.valueOf(FieldInfo.FieldType.Txt); - if(finfo!=null) { - name = finfo.name(); - meta.put("description", finfo.description()); - if(finfo.type()== FieldInfo.FieldType.Txt && isNumberType(field.getType())){ - type=String.valueOf(FieldInfo.FieldType.Number); - }else { - type = String.valueOf(finfo.type()); - } - } - - if(overrideFieldDescription.containsKey(fieldId.toLowerCase())){ - meta.put("description",overrideFieldDescription.get(fieldId.toLowerCase())); - } - - meta.put("name", name); - meta.put("type", type); - metas.add(meta); - } - - } - - return metas; - - } - - private static boolean isNumberType(Class fieldType){ - if(Number.class.isAssignableFrom(fieldType)){ - return true; - }else if(fieldType.isPrimitive() && - (fieldType == int.class || fieldType == long.class || fieldType == float.class || fieldType == double.class || fieldType == short.class)){ - return true; - } - return false; - } - -} +package com.ctrip.framework.cs.component; + +import com.ctrip.framework.cs.component.defaultComponents.HostInfo; +import com.ctrip.framework.cs.UserAction; +import com.ctrip.framework.cs.annotation.ComponentStatus; +import com.ctrip.framework.cs.annotation.FieldInfo; +import com.ctrip.framework.cs.jmx.VIDynamicMBean; +import com.ctrip.framework.cs.util.ArrayUtils; +import com.ctrip.framework.cs.util.ServerConnector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.management.InstanceAlreadyExistsException; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.lang.management.ManagementFactory; +import java.lang.reflect.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Created by jiang.j on 2016/3/30. + */ +public final class ComponentManager { + + private static ConcurrentHashMap> container = new ConcurrentHashMap<>(); + private static ConcurrentHashMap instances = new ConcurrentHashMap<>(); + private static Logger logger = LoggerFactory.getLogger(ComponentManager.class); + private static Map overrideFieldDescription = new ConcurrentHashMap<>(); + + private static Class hostInfoExtend =null; + + public static void setFieldDescription(String fieldId,String description){ + overrideFieldDescription.put(fieldId.toLowerCase(),description); + } + + public static void setHostInfoExtend(Class extend){ + hostInfoExtend = extend; + try { + instances.put(HostInfo.class.getName(),hostInfoExtend.newInstance()); + } catch (Throwable e) { + logger.warn("new hostInfoExtend failed, class:" + hostInfoExtend.getName(), e); + } + } + public static synchronized boolean add(Class cb){ + ComponentStatus comp = cb.getAnnotation(ComponentStatus.class); + if(comp!=null) { + String compId =comp.id().toLowerCase(); + if(container.putIfAbsent(compId, cb)==null) { + if (comp.singleton()) { + try { + instances.putIfAbsent(cb.getName(), cb.newInstance()); + } catch (Throwable e) { + logger.error("init component status failed", e); + return false; + } + } + } + }else{ + return false; + } + + if(comp.jmx()){ + logger.info(comp.id() + " register self to jmx"); + final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + try { + server.registerMBean(new VIDynamicMBean(cb), new ObjectName("VI:type=" + ServerConnector.getPort() + + (HostInfo.isTomcat()?System.getProperty("vi.context.path"):"") + ",name=" +cb.getSimpleName())); + } catch (InstanceAlreadyExistsException e) { + logger.info("VI JMX MBeans "+cb.getSimpleName() + " already exist!"); + }catch (Throwable e) { + logger.warn("VI JMX MBeans error",e); + } + + logger.info(comp.id() + " finish register!"); + } + return true; + } + + @Deprecated + public static synchronized void register(Class cb){ + add(cb); + } + + @SuppressWarnings("unchecked") + public static T getStatus(Class statusClass,String user){ + if(!container.values().contains(statusClass)) { + add(statusClass); + } + + + T rtn = (T) instances.get(statusClass.getName()); + if(rtn == null){ + try { + rtn = statusClass.newInstance(); + } catch (Throwable e) { + logger.error("init component status failed", e); + } + }else if(rtn instanceof Refreshable) { + ((Refreshable)rtn).refresh(); + } + + if(rtn instanceof UserAction){ + ((UserAction)rtn).userAction(user); + } + + return rtn; + } + public static T getStatus(Class statusClass){ + return getStatus(statusClass,""); + } + + + static Map> getAllComponents(){ + return container; + } + + static List> getComponentMeta(){ + + List> metas = new ArrayList<>(); + + for (Class component : container.values() ){ + + ComponentStatus comp = component.getAnnotation(ComponentStatus.class); + if(comp!=null){ + + Map meta = new HashMap<>(); + meta.put("id",comp.id().toLowerCase()); + meta.put("name",comp.name()); + meta.put("list", String.valueOf(comp.list())); + meta.put("custom", String.valueOf(comp.custom())); + meta.put("description",comp.description()); + metas.add(meta); + } + } + + return metas; + + } + + + static List> getFieldMeta(){ + + List> metas = new ArrayList<>(); + + for (Class component : container.values() ){ + + ComponentStatus comp = component.getAnnotation(ComponentStatus.class); + if(comp==null) { + continue; + } + + + Field[] fields; + + if(component.getGenericSuperclass() instanceof ParameterizedType){ + ParameterizedType parameterizedType = (ParameterizedType) component.getGenericSuperclass(); + fields = parameterizedType.getActualTypeArguments()[0].getClass().getDeclaredFields(); + }else{ + fields = component.getDeclaredFields(); + } + try { + if (hostInfoExtend != null && component.equals(HostInfo.class)) { + fields = ArrayUtils.concatenate(fields, hostInfoExtend.getDeclaredFields()); + } + }catch (Throwable e){ + logger.warn("concatenate hostinfo field failed!",e); + } + for(Field field : fields) { + if(Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())){ + continue; + } + + Map meta = new HashMap<>(); + String fieldId =comp.id().toLowerCase()+"."+field.getName(); + meta.put("id", fieldId); + FieldInfo finfo = field.getAnnotation(FieldInfo.class); + String name = field.getName(); + + String type = String.valueOf(FieldInfo.FieldType.Txt); + if(finfo!=null) { + name = finfo.name(); + meta.put("description", finfo.description()); + if(finfo.type()== FieldInfo.FieldType.Txt && isNumberType(field.getType())){ + type=String.valueOf(FieldInfo.FieldType.Number); + }else { + type = String.valueOf(finfo.type()); + } + } + + if(overrideFieldDescription.containsKey(fieldId.toLowerCase())){ + meta.put("description",overrideFieldDescription.get(fieldId.toLowerCase())); + } + + meta.put("name", name); + meta.put("type", type); + metas.add(meta); + } + + } + + return metas; + + } + + private static boolean isNumberType(Class fieldType){ + if(Number.class.isAssignableFrom(fieldType)){ + return true; + }else if(fieldType.isPrimitive() && + (fieldType == int.class || fieldType == long.class || fieldType == float.class || fieldType == double.class || fieldType == short.class)){ + return true; + } + return false; + } + +} diff --git a/cornerstone/src/main/java/com/ctrip/framework/cs/jmx/VIDynamicMBean.java b/cornerstone/src/main/java/com/ctrip/framework/cs/jmx/VIDynamicMBean.java index 55d724a..f24fe76 100644 --- a/cornerstone/src/main/java/com/ctrip/framework/cs/jmx/VIDynamicMBean.java +++ b/cornerstone/src/main/java/com/ctrip/framework/cs/jmx/VIDynamicMBean.java @@ -1,154 +1,155 @@ -package com.ctrip.framework.cs.jmx; - -import com.ctrip.framework.cs.component.ComponentManager; -import com.ctrip.framework.cs.annotation.ComponentStatus; -import com.ctrip.framework.cs.annotation.FieldInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.management.*; -import javax.management.openmbean.*; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.util.*; - -/** - * Created by jiang.j on 2016/10/12. - */ -public class VIDynamicMBean implements DynamicMBean { - private Class _beanClass; - private Object _instance; - private Logger logger = LoggerFactory.getLogger(getClass()); - private Map> listFieldMap = new HashMap<>(); - public VIDynamicMBean(Class beanClass){ - - this._beanClass = beanClass; - } - @Override - public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { - _instance = ComponentManager.getStatus(_beanClass); - - Object rtn=null; - Class beanClass = this._beanClass; - - try { - if(Map.class.isAssignableFrom(beanClass) && attribute.equals("value")){ - Map data = (Map) _instance; - String[] keys = data.keySet().toArray(new String[data.keySet().size()]); - OpenType[] openTypes = new OpenType[data.keySet().size()]; - Arrays.fill(openTypes,JMXTypeFactory.getMapValueOpenType(beanClass)); - - CompositeType compositeType = new CompositeType("map","map",keys,keys, openTypes); - CompositeData compositeData = new CompositeDataSupport(compositeType,data); - - return compositeData; - }else { - Field field = beanClass.getDeclaredField(attribute); - field.setAccessible(true); - rtn = field.get(_instance); - if(listFieldMap.containsKey(attribute)){ - TabularType tabularType = (TabularType) listFieldMap.get(attribute); - TabularData result = new TabularDataSupport((TabularType) listFieldMap.get(attribute)); - - for(Object val : (List)rtn){ - Map data = new HashMap<>(); - for(String itemName:tabularType.getIndexNames()){ - Field itemField = val.getClass().getDeclaredField(itemName); - itemField.setAccessible(true); - data.put(itemName,itemField.get(val)); - } - result.put(new CompositeDataSupport(tabularType.getRowType(),data)); - } - - return result; - } - if (field.getType().isEnum()) { - rtn = String.valueOf(rtn); - } - } - } catch (Throwable e) { - logger.warn("get component status attribute failed!", e); - } - return rtn; - } - - @Override - public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { - - } - - @Override - public AttributeList getAttributes(String[] attributes) { - return null; - } - - @Override - public AttributeList setAttributes(AttributeList attributes) { - return null; - } - - @Override - public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { - return null; - } - - @Override - public MBeanInfo getMBeanInfo() { - ComponentStatus comp = _beanClass.getAnnotation(ComponentStatus.class); - if(comp==null) { - return null; - } - Class beanClass = this._beanClass; - ArrayList attributeInfos = new ArrayList<>(); - - if(Map.class.isAssignableFrom(beanClass)){ - - attributeInfos.add(new MBeanAttributeInfo("value", beanClass.getName(), beanClass.getName(), true, false, false)); - }else { - Field[] fields = beanClass.getDeclaredFields(); - for (Field field : fields) { - if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { - continue; - } - - FieldInfo finfo = field.getAnnotation(FieldInfo.class); - String name = field.getName(); - String type = field.getType().getName(); - Class fieldClass = field.getType(); - String description = ""; - if (finfo != null) { - description = finfo.description(); - } - - Class realClass = null; - if(List.class.isAssignableFrom(fieldClass) && (field.getGenericType() instanceof ParameterizedType)){ - - ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); - realClass = (Class) parameterizedType.getActualTypeArguments()[0]; - if(realClass.isPrimitive() || realClass.getName().startsWith("java.lang.")){ - - realClass = null; - } - } - - if(realClass!=null){ - try { - description = realClass.getName(); - TabularType tabularType =JMXTypeFactory.getTabularType(name,description,realClass); - listFieldMap.put(name,tabularType); - attributeInfos.add(new OpenMBeanAttributeInfoSupport(name,description,tabularType, true, false, false)); - } catch (OpenDataException e) { - logger.warn("get Mbean info failed!",e); - } - } - else { - attributeInfos.add(new MBeanAttributeInfo(name, type, description, true, false, false)); - } - - } - } - - return new MBeanInfo(_beanClass.getName(),comp.description(),attributeInfos.toArray(new MBeanAttributeInfo[attributeInfos.size()]),null,null,null); - } -} +package com.ctrip.framework.cs.jmx; + +import com.ctrip.framework.cs.component.ComponentManager; +import com.ctrip.framework.cs.annotation.ComponentStatus; +import com.ctrip.framework.cs.annotation.FieldInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.management.*; +import javax.management.openmbean.*; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.util.*; + +/** + * Created by jiang.j on 2016/10/12. + */ +public class VIDynamicMBean implements DynamicMBean { + private Class _beanClass; + private Object _instance; + private Logger logger = LoggerFactory.getLogger(getClass()); + private Map> listFieldMap = new HashMap<>(); + public VIDynamicMBean(Class beanClass){ + + this._beanClass = beanClass; + } + @Override + @SuppressWarnings("unchecked") + public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { + _instance = ComponentManager.getStatus(_beanClass); + + Object rtn=null; + Class beanClass = this._beanClass; + + try { + if(Map.class.isAssignableFrom(beanClass) && attribute.equals("value")){ + Map data = (Map) _instance; + String[] keys = data.keySet().toArray(new String[data.keySet().size()]); + OpenType[] openTypes = new OpenType[data.keySet().size()]; + Arrays.fill(openTypes,JMXTypeFactory.getMapValueOpenType(beanClass)); + + CompositeType compositeType = new CompositeType("map","map",keys,keys, openTypes); + CompositeData compositeData = new CompositeDataSupport(compositeType,data); + + return compositeData; + }else { + Field field = beanClass.getDeclaredField(attribute); + field.setAccessible(true); + rtn = field.get(_instance); + if(listFieldMap.containsKey(attribute)){ + TabularType tabularType = (TabularType) listFieldMap.get(attribute); + TabularData result = new TabularDataSupport((TabularType) listFieldMap.get(attribute)); + + for(Object val : (List)rtn){ + Map data = new HashMap<>(); + for(String itemName:tabularType.getIndexNames()){ + Field itemField = val.getClass().getDeclaredField(itemName); + itemField.setAccessible(true); + data.put(itemName,itemField.get(val)); + } + result.put(new CompositeDataSupport(tabularType.getRowType(),data)); + } + + return result; + } + if (field.getType().isEnum()) { + rtn = String.valueOf(rtn); + } + } + } catch (Throwable e) { + logger.warn("get component status attribute failed!", e); + } + return rtn; + } + + @Override + public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { + + } + + @Override + public AttributeList getAttributes(String[] attributes) { + return null; + } + + @Override + public AttributeList setAttributes(AttributeList attributes) { + return null; + } + + @Override + public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { + return null; + } + + @Override + public MBeanInfo getMBeanInfo() { + ComponentStatus comp = _beanClass.getAnnotation(ComponentStatus.class); + if(comp==null) { + return null; + } + Class beanClass = this._beanClass; + ArrayList attributeInfos = new ArrayList<>(); + + if(Map.class.isAssignableFrom(beanClass)){ + + attributeInfos.add(new MBeanAttributeInfo("value", beanClass.getName(), beanClass.getName(), true, false, false)); + }else { + Field[] fields = beanClass.getDeclaredFields(); + for (Field field : fields) { + if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { + continue; + } + + FieldInfo finfo = field.getAnnotation(FieldInfo.class); + String name = field.getName(); + String type = field.getType().getName(); + Class fieldClass = field.getType(); + String description = ""; + if (finfo != null) { + description = finfo.description(); + } + + Class realClass = null; + if(List.class.isAssignableFrom(fieldClass) && (field.getGenericType() instanceof ParameterizedType)){ + + ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); + realClass = (Class) parameterizedType.getActualTypeArguments()[0]; + if(realClass.isPrimitive() || realClass.getName().startsWith("java.lang.")){ + + realClass = null; + } + } + + if(realClass!=null){ + try { + description = realClass.getName(); + TabularType tabularType =JMXTypeFactory.getTabularType(name,description,realClass); + listFieldMap.put(name,tabularType); + attributeInfos.add(new OpenMBeanAttributeInfoSupport(name,description,tabularType, true, false, false)); + } catch (OpenDataException e) { + logger.warn("get Mbean info failed!",e); + } + } + else { + attributeInfos.add(new MBeanAttributeInfo(name, type, description, true, false, false)); + } + + } + } + + return new MBeanInfo(_beanClass.getName(),comp.description(),attributeInfos.toArray(new MBeanAttributeInfo[attributeInfos.size()]),null,null,null); + } +} diff --git a/cornerstone/src/main/java/com/ctrip/framework/cs/metrics/MetricsHandler.java b/cornerstone/src/main/java/com/ctrip/framework/cs/metrics/MetricsHandler.java index c5a4656..a009009 100644 --- a/cornerstone/src/main/java/com/ctrip/framework/cs/metrics/MetricsHandler.java +++ b/cornerstone/src/main/java/com/ctrip/framework/cs/metrics/MetricsHandler.java @@ -1,91 +1,93 @@ -package com.ctrip.framework.cs.metrics; - -import com.ctrip.framework.cs.Permission; -import com.ctrip.framework.cs.ViFunctionHandler; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import org.slf4j.Logger; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -/** - * Created by jiang.j on 2016/7/5. - */ -public class MetricsHandler implements ViFunctionHandler { - private String startPath ="/metrics/"; - MetricsCollector metricsCollector = MetricsCollector.getCollector(); - @Override - public Object execute(String path, String user, int permission, Logger logger, Map params) throws Exception { - Object rtn = null; - if(path.equals(startPath+"register")){ - Gson gson = new Gson(); - if(params == null){ - return null; - } - Object idRaw = params.get("id"); - String observerId = null; - MetricsObserver observer =null; - if(idRaw!=null) { - String id = gson.fromJson((JsonElement)(idRaw),String.class); - observer = metricsCollector.getObserver(id); - observerId = id; - } - - if(observer==null){ - observer = new MetricsObserverImpl(); - observerId = null; - } - - String namesRaw = String.valueOf(params.get("names")); - logger.info(namesRaw); - HashMap tags = new HashMap<>(); - HashSet names = new HashSet<>(); - double[] percentiles=null; - names = gson.fromJson(namesRaw,names.getClass()); - - if(names == null){ - return null; - } - if(params.containsKey("tags")){ - tags = gson.fromJson(String.valueOf(params.get("tags")),tags.getClass()); - } - - if(params.containsKey("percentiles")){ - percentiles =gson.fromJson(String.valueOf(params.get("percentiles")),double[].class); - } - - observer.setFilter(names,tags,percentiles); - if(observerId==null) { - rtn = metricsCollector.addObserver(user, observer); - }else{ - return observerId; - } - }else if(path.equals(startPath+"current")){ - Gson gson = new Gson(); - String id = gson.fromJson((JsonElement)(params.get("id")),String.class); - - rtn = metricsCollector.getOberserStats(id); - if(rtn==null){ - throw new NoObserverException(id); - } - }else if(path.equals(startPath+"names")){ - rtn = metricsCollector.getMetricNames(); - }else if(path.equals(startPath+"clearqueue")){ - metricsCollector.clearWaitingQueue(); - rtn = true; - } - return rtn; - } - - @Override - public String getStartPath() { - return startPath; - } - - @Override - public Permission getPermission(String user) { - return Permission.ALL; - } -} +package com.ctrip.framework.cs.metrics; + +import com.ctrip.framework.cs.Permission; +import com.ctrip.framework.cs.ViFunctionHandler; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; + +import org.slf4j.Logger; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +/** + * Created by jiang.j on 2016/7/5. + */ +public class MetricsHandler implements ViFunctionHandler { + private String startPath ="/metrics/"; + MetricsCollector metricsCollector = MetricsCollector.getCollector(); + @Override + public Object execute(String path, String user, int permission, Logger logger, Map params) throws Exception { + Object rtn = null; + if(path.equals(startPath+"register")){ + Gson gson = new Gson(); + if(params == null){ + return null; + } + Object idRaw = params.get("id"); + String observerId = null; + MetricsObserver observer =null; + if(idRaw!=null) { + String id = gson.fromJson((JsonElement)(idRaw),String.class); + observer = metricsCollector.getObserver(id); + observerId = id; + } + + if(observer==null){ + observer = new MetricsObserverImpl(); + observerId = null; + } + + String namesRaw = String.valueOf(params.get("names")); + logger.info(namesRaw); + HashMap tags = new HashMap<>(); + HashSet names; + double[] percentiles=null; + names = gson.fromJson(namesRaw,new TypeToken>(){}.getType()); + + if(names == null){ + return null; + } + if(params.containsKey("tags")){ + tags = gson.fromJson(String.valueOf(params.get("tags")),new TypeToken>(){}.getType()); + } + + if(params.containsKey("percentiles")){ + percentiles =gson.fromJson(String.valueOf(params.get("percentiles")),double[].class); + } + + observer.setFilter(names,tags,percentiles); + if(observerId==null) { + rtn = metricsCollector.addObserver(user, observer); + }else{ + return observerId; + } + }else if(path.equals(startPath+"current")){ + Gson gson = new Gson(); + String id = gson.fromJson((JsonElement)(params.get("id")),String.class); + + rtn = metricsCollector.getOberserStats(id); + if(rtn==null){ + throw new NoObserverException(id); + } + }else if(path.equals(startPath+"names")){ + rtn = metricsCollector.getMetricNames(); + }else if(path.equals(startPath+"clearqueue")){ + metricsCollector.clearWaitingQueue(); + rtn = true; + } + return rtn; + } + + @Override + public String getStartPath() { + return startPath; + } + + @Override + public Permission getPermission(String user) { + return Permission.ALL; + } +} From b6f22ae85612c080eaa092da75fb5ec92db3c60e Mon Sep 17 00:00:00 2001 From: birdie7761 Date: Thu, 30 Aug 2018 15:21:28 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E6=94=BE=E5=BC=83=E6=97=A7API=E8=BD=AC?= =?UTF-8?q?=E4=B8=BA=E5=BC=95=E7=94=A8=E6=96=B0API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cs/spring/AutoConfiguration.java | 146 +++++++++--------- .../spring/FilterRegistrationCondition.java | 40 ++--- 2 files changed, 93 insertions(+), 93 deletions(-) diff --git a/cornerstone/src/main/java/com/ctrip/framework/cs/spring/AutoConfiguration.java b/cornerstone/src/main/java/com/ctrip/framework/cs/spring/AutoConfiguration.java index 4e35b5a..2ddecc7 100644 --- a/cornerstone/src/main/java/com/ctrip/framework/cs/spring/AutoConfiguration.java +++ b/cornerstone/src/main/java/com/ctrip/framework/cs/spring/AutoConfiguration.java @@ -1,74 +1,74 @@ -package com.ctrip.framework.cs.spring; - -import com.ctrip.framework.cs.servlet.VIFilter; -import com.ctrip.framework.cs.SysKeys; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.Ordered; -import org.springframework.core.env.Environment; - -import javax.servlet.DispatcherType; - -/** - * Created by jiang.j on 2017/4/11. - */ -@Configuration -public class AutoConfiguration { - - private static final String URLPATTERNS = "/@in/*"; - @Configuration - @Conditional(NoneFilterRegistrationCondition.class) - static class ConfigurationNew { - - @Autowired - Environment environment; - @Bean(name = "VIFilterRegistrationBeanNew") - public org.springframework.boot.web.servlet.FilterRegistrationBean factory() { - - if(environment != null) { - String port = environment.getProperty("server.port"); - if(port !=null) { - System.setProperty(SysKeys.SPRINGBOOTPORTKEY, port); - } - } - org.springframework.boot.web.servlet.FilterRegistrationBean filter = - new org.springframework.boot.web.servlet.FilterRegistrationBean(); - filter.setFilter(new VIFilter()); - filter.setName("vi-filter"); - filter.addUrlPatterns(URLPATTERNS); - filter.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD); - filter.setAsyncSupported(true); - filter.setOrder(Ordered.HIGHEST_PRECEDENCE); - return filter; - } - } - - @Configuration - @Conditional(FilterRegistrationCondition.class) - static class ConfigurationOld { - - @Autowired - Environment environment; - @Bean(name = "VIFilterRegistrationBeanOld") - public org.springframework.boot.context.embedded.FilterRegistrationBean factory() { - - if(environment != null) { - String port = environment.getProperty("server.port"); - if(port !=null) { - System.setProperty(SysKeys.SPRINGBOOTPORTKEY, port); - } - } - org.springframework.boot.context.embedded.FilterRegistrationBean filter = - new org.springframework.boot.context.embedded.FilterRegistrationBean(); - filter.setFilter(new VIFilter()); - filter.setName("vi-filter"); - filter.addUrlPatterns(URLPATTERNS); - filter.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD); - filter.setAsyncSupported(true); - filter.setOrder(Ordered.HIGHEST_PRECEDENCE); - return filter; - } - } +package com.ctrip.framework.cs.spring; + +import com.ctrip.framework.cs.servlet.VIFilter; +import com.ctrip.framework.cs.SysKeys; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.env.Environment; + +import javax.servlet.DispatcherType; + +/** + * Created by jiang.j on 2017/4/11. + */ +@Configuration +public class AutoConfiguration { + + private static final String URLPATTERNS = "/@in/*"; + @Configuration + @Conditional(NoneFilterRegistrationCondition.class) + static class ConfigurationNew { + + @Autowired + Environment environment; + @Bean(name = "VIFilterRegistrationBeanNew") + public org.springframework.boot.web.servlet.FilterRegistrationBean factory() { + + if(environment != null) { + String port = environment.getProperty("server.port"); + if(port !=null) { + System.setProperty(SysKeys.SPRINGBOOTPORTKEY, port); + } + } + org.springframework.boot.web.servlet.FilterRegistrationBean filter = + new org.springframework.boot.web.servlet.FilterRegistrationBean(); + filter.setFilter(new VIFilter()); + filter.setName("vi-filter"); + filter.addUrlPatterns(URLPATTERNS); + filter.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD); + filter.setAsyncSupported(true); + filter.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filter; + } + } + + @Configuration + @Conditional(FilterRegistrationCondition.class) + static class ConfigurationOld { + + @Autowired + Environment environment; + @Bean(name = "VIFilterRegistrationBeanOld") + public org.springframework.boot.web.servlet.FilterRegistrationBean factory() { + + if(environment != null) { + String port = environment.getProperty("server.port"); + if(port !=null) { + System.setProperty(SysKeys.SPRINGBOOTPORTKEY, port); + } + } + org.springframework.boot.web.servlet.FilterRegistrationBean filter = + new org.springframework.boot.web.servlet.FilterRegistrationBean(); + filter.setFilter(new VIFilter()); + filter.setName("vi-filter"); + filter.addUrlPatterns(URLPATTERNS); + filter.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD); + filter.setAsyncSupported(true); + filter.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filter; + } + } } \ No newline at end of file diff --git a/cornerstone/src/main/java/com/ctrip/framework/cs/spring/FilterRegistrationCondition.java b/cornerstone/src/main/java/com/ctrip/framework/cs/spring/FilterRegistrationCondition.java index 903f6ec..7d3bdff 100644 --- a/cornerstone/src/main/java/com/ctrip/framework/cs/spring/FilterRegistrationCondition.java +++ b/cornerstone/src/main/java/com/ctrip/framework/cs/spring/FilterRegistrationCondition.java @@ -1,20 +1,20 @@ -package com.ctrip.framework.cs.spring; - -import org.springframework.context.annotation.Condition; -import org.springframework.context.annotation.ConditionContext; -import org.springframework.core.type.AnnotatedTypeMetadata; - -/** - * Created by jiang.j on 2017/6/8. - */ -public class FilterRegistrationCondition implements Condition { - @Override - public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { - try { - Class.forName("org.springframework.boot.context.embedded.FilterRegistrationBean"); - return true; - }catch (Throwable e){ - return false; - } - } -} +package com.ctrip.framework.cs.spring; + +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; + +/** + * Created by jiang.j on 2017/6/8. + */ +public class FilterRegistrationCondition implements Condition { + @Override + public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { + try { + Class.forName("org.springframework.boot.web.servlet.FilterRegistrationBean"); + return true; + }catch (Throwable e){ + return false; + } + } +} From 49bdbf63dcf2a9eed801d46b5a0594235741153a Mon Sep 17 00:00:00 2001 From: birdie7761 Date: Thu, 30 Aug 2018 15:23:11 +0800 Subject: [PATCH 3/3] =?UTF-8?q?base64=E6=96=B9=E6=B3=95=E4=BB=8Esun?= =?UTF-8?q?=E5=86=85=E9=83=A8=E7=B1=BB=E6=94=B9=E4=B8=BA=E4=BD=BF=E7=94=A8?= =?UTF-8?q?jdk=E4=B8=AD=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ctrip/framework/cs/util/DesUtil.java | 131 +++++++++--------- 1 file changed, 65 insertions(+), 66 deletions(-) diff --git a/cornerstone/src/main/java/com/ctrip/framework/cs/util/DesUtil.java b/cornerstone/src/main/java/com/ctrip/framework/cs/util/DesUtil.java index 6134ee4..c8289b6 100644 --- a/cornerstone/src/main/java/com/ctrip/framework/cs/util/DesUtil.java +++ b/cornerstone/src/main/java/com/ctrip/framework/cs/util/DesUtil.java @@ -1,66 +1,65 @@ -package com.ctrip.framework.cs.util; - -import sun.misc.BASE64Decoder; -import sun.misc.BASE64Encoder; - -import javax.crypto.Cipher; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.DESKeySpec; -import java.io.IOException; -import java.security.SecureRandom; - -/** - * Created by jiang.j on 2016/5/3. - */ -public class DesUtil { - - - private final static String DES = "DES"; - - public static String encrypt(String data, String key) throws Exception { - byte[] bt = encrypt(data.getBytes(), key.getBytes()); - String strs = new BASE64Encoder().encode(bt); - return strs; - } - - public static String decrypt(String data, String key) throws IOException, - Exception { - if (data == null) - return null; - BASE64Decoder decoder = new BASE64Decoder(); - byte[] buf = decoder.decodeBuffer(data); - byte[] bt = decrypt(buf,key.getBytes()); - return new String(bt); - } - - private static byte[] encrypt(byte[] data, byte[] key) throws Exception { - SecureRandom sr = new SecureRandom(); - - DESKeySpec dks = new DESKeySpec(key); - - SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); - SecretKey securekey = keyFactory.generateSecret(dks); - - Cipher cipher = Cipher.getInstance(DES); - - cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); - - return cipher.doFinal(data); - } - - - private static byte[] decrypt(byte[] data, byte[] key) throws Exception { - SecureRandom sr = new SecureRandom(); - - DESKeySpec dks = new DESKeySpec(key); - - SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); - SecretKey securekey = keyFactory.generateSecret(dks); - - Cipher cipher = Cipher.getInstance(DES); - - cipher.init(Cipher.DECRYPT_MODE, securekey, sr); - - return cipher.doFinal(data); - }} +package com.ctrip.framework.cs.util; + +import java.io.IOException; +import java.security.SecureRandom; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; +import javax.xml.bind.DatatypeConverter; + +/** + * Created by jiang.j on 2016/5/3. + */ +public class DesUtil { + + + private final static String DES = "DES"; + + public static String encrypt(String data, String key) throws Exception { + byte[] bt = encrypt(data.getBytes(), key.getBytes()); + String strs = DatatypeConverter.printBase64Binary(bt); + return strs; + } + + public static String decrypt(String data, String key) throws IOException, + Exception { + if (data == null) + return null; + + byte[] buf = DatatypeConverter.parseBase64Binary(data); + byte[] bt = decrypt(buf,key.getBytes()); + return new String(bt); + } + + private static byte[] encrypt(byte[] data, byte[] key) throws Exception { + SecureRandom sr = new SecureRandom(); + + DESKeySpec dks = new DESKeySpec(key); + + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); + SecretKey securekey = keyFactory.generateSecret(dks); + + Cipher cipher = Cipher.getInstance(DES); + + cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); + + return cipher.doFinal(data); + } + + + private static byte[] decrypt(byte[] data, byte[] key) throws Exception { + SecureRandom sr = new SecureRandom(); + + DESKeySpec dks = new DESKeySpec(key); + + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); + SecretKey securekey = keyFactory.generateSecret(dks); + + Cipher cipher = Cipher.getInstance(DES); + + cipher.init(Cipher.DECRYPT_MODE, securekey, sr); + + return cipher.doFinal(data); + }}