Fix the sonar detected error
authoryoubowu <wu.youbo@zte.com.cn>
Wed, 1 Mar 2017 02:55:46 +0000 (10:55 +0800)
committer6092002067 <wu.youbo@zte.com.cn>
Wed, 1 Mar 2017 02:55:46 +0000 (10:55 +0800)
Issue-ID:HOLMES-51

Change-Id: I1ac160651d7cd1382076a447d33482219cdb0def
Signed-off-by: youbowu <wu.youbo@zte.com.cn>
12 files changed:
holmes-actions/src/main/java/org/openo/holmes/common/api/stat/Alarm.java
holmes-actions/src/main/java/org/openo/holmes/common/i18n/correlation-i18n-en-US.json
holmes-actions/src/main/java/org/openo/holmes/common/i18n/correlation-i18n-zh-CN.json
holmes-actions/src/main/java/org/openo/holmes/common/producer/MQProducer.java
holmes-actions/src/main/java/org/openo/holmes/common/utils/I18nProxy.java
holmes-actions/src/main/java/org/openo/holmes/common/utils/JacksonUtil.java
holmes-actions/src/main/java/org/openo/holmes/common/utils/LanguageUtil.java
holmes-actions/src/main/java/org/openo/holmes/common/utils/UserUtil.java
holmes-actions/src/test/java/org/openo/holmes/common/api/stat/AlarmTest.java
holmes-actions/src/test/java/org/openo/holmes/common/utils/DbDaoUtilTest.java
holmes-actions/src/test/java/org/openo/holmes/common/utils/I18nProxyTest.java
holmes-actions/src/test/java/org/openo/holmes/common/utils/JudgeNullUtilTest.java

index e5eda70..3ea3715 100644 (file)
@@ -46,78 +46,83 @@ public class Alarm implements AplusData, Cloneable, Serializable {
     public static final byte EVENT_RAISED = 0;\r
 \r
     private static final long serialVersionUID = 4520003737132012000L;\r
-\r
+    private final static Date clearedServerTime = null;\r
+    private final Map<Integer, Integer> linkIdNodeIdxMap = new HashMap<Integer, Integer>();\r
     private byte eventType = EVENT_RAISED;\r
-\r
     private long id = 0L;\r
-\r
     private String alarmKey = "";\r
-\r
     private String network = "";\r
-\r
     private String neType = "";\r
-\r
     private String equipType = "";\r
-\r
     private String position1 = "";\r
-\r
     private String subPosition1 = null;\r
-\r
     private String position2 = null;\r
-\r
     private String subPosition2 = null;\r
-\r
     private byte severity = -1;\r
-\r
     private byte alarmType = -1;\r
-\r
     private long probableCause = -1;\r
-\r
     private String specificProblem = null;\r
-\r
     private String additionalText = null;\r
-\r
     private Date raisedTime = new Date();\r
-\r
     private Date raisedServerTime = new Date();\r
-\r
     private Date clearedTime = null;\r
-\r
-    private final Date clearedServerTime = null;\r
-\r
     private String region = null;\r
-\r
     private String site = null;\r
-\r
     private String aid = null;\r
-\r
     private short systemType = -1;\r
-\r
     private boolean rootAlarmFlag = false;\r
-\r
     private int linkId = -1;\r
-\r
     private int nodeIdx = -1;\r
-\r
     private Set<Integer> linkIds = new HashSet<Integer>();\r
-\r
     private HashMap<String, Integer> priorityMap = new HashMap<String, Integer>();\r
-\r
     private HashMap<String, Integer> rootAlarmTypeMap = new HashMap<String, Integer>();\r
-\r
     private int rootAlarmType = -1;\r
-\r
     private boolean keyAlarmFlag = false;\r
-\r
     private int keyAlarmType = -1;\r
-\r
     private int networkLevel = -1;\r
-\r
     private int linkType = -1;\r
-\r
     private int centerType;\r
 \r
-    private final Map<Integer, Integer> linkIdNodeIdxMap = new HashMap<Integer, Integer>();\r
+    public static Alarm valueOf(String xmlString) {\r
+        Element element;\r
+        try {\r
+            StringReader sb = new StringReader(xmlString);\r
+            element = new SAXBuilder().build(sb).getRootElement();\r
+            sb.close();\r
+        } catch (Exception e) {\r
+            throw new RuntimeException(e);\r
+        }\r
+\r
+        Alarm alarm = new Alarm();\r
+        @SuppressWarnings("unchecked")\r
+        List<Attribute> list = element.getAttributes();\r
+        for (Attribute attr : list) {\r
+            String attrName = attr.getName();\r
+            try {\r
+                Field field = Alarm.class.getDeclaredField(attrName);\r
+                if (!attrName.endsWith("Time")) {\r
+                    String type = field.getType().getSimpleName();\r
+                    if ("byte".equals(type)) {\r
+                        field.set(alarm, Byte.parseByte(attr.getValue()));\r
+                    } else if ("long".equals(type)) {\r
+                        field.set(alarm, Long.parseLong(attr.getValue()));\r
+                    } else if ("String".equals(type)) {\r
+                        field.set(alarm, attr.getValue());\r
+                    } else {\r
+                        throw new RuntimeException("unknow attr type: " + type.toString());\r
+                    }\r
+                } else {\r
+                    Date date = new Date();\r
+                    date.setTime(Long.parseLong(attr.getValue()));\r
+                    field.set(alarm, date);\r
+                }\r
+            } catch (Exception e) {\r
+                throw new RuntimeException(e);\r
+            }\r
+        }\r
+\r
+        return alarm;\r
+    }\r
 \r
     public void addLinkIdNodeIdx(int linkId, int index) {\r
         linkIdNodeIdxMap.put(linkId, index);\r
@@ -146,11 +151,7 @@ public class Alarm implements AplusData, Cloneable, Serializable {
     }\r
 \r
     public boolean containNode(int linkId, int index) {\r
-        if (linkIdNodeIdxMap.containsKey(linkId) && linkIdNodeIdxMap.get(linkId) == index) {\r
-            return true;\r
-        } else {\r
-            return false;\r
-        }\r
+       return linkIdNodeIdxMap.containsKey(linkId) && linkIdNodeIdxMap.get(linkId) == index;\r
     }\r
 \r
     @Override\r
@@ -193,47 +194,6 @@ public class Alarm implements AplusData, Cloneable, Serializable {
         return new XMLOutputter().outputString(el);\r
     }\r
 \r
-    public static Alarm valueOf(String xmlString) {\r
-        Element element = null;\r
-        try {\r
-            StringReader sb = new StringReader(xmlString);\r
-            element = new SAXBuilder().build(sb).getRootElement();\r
-            sb.close();\r
-        } catch (Exception e) {\r
-            throw new RuntimeException(e);\r
-        }\r
-\r
-        Alarm alarm = new Alarm();\r
-        @SuppressWarnings("unchecked")\r
-        List<Attribute> list = element.getAttributes();\r
-        for (Attribute attr : list) {\r
-            String attrName = attr.getName();\r
-            try {\r
-                Field field = Alarm.class.getDeclaredField(attrName);\r
-                if (!attrName.endsWith("Time")) {\r
-                    String type = field.getType().getSimpleName();\r
-                    if (type.equals("byte")) {\r
-                        field.set(alarm, Byte.parseByte(attr.getValue()));\r
-                    } else if (type.equals("long")) {\r
-                        field.set(alarm, Long.parseLong(attr.getValue()));\r
-                    } else if (type.equals("String")) {\r
-                        field.set(alarm, attr.getValue());\r
-                    } else {\r
-                        throw new RuntimeException("unknow attr type: " + type.toString());\r
-                    }\r
-                } else {\r
-                    Date date = new Date();\r
-                    date.setTime(Long.parseLong(attr.getValue()));\r
-                    field.set(alarm, date);\r
-                }\r
-            } catch (Exception e) {\r
-                throw new RuntimeException(e);\r
-            }\r
-        }\r
-\r
-        return alarm;\r
-    }\r
-\r
     @Override\r
     public int hashCode() {\r
         return this.getAlarmKey().hashCode();\r
index 8288f6e..0192d01 100644 (file)
@@ -13,7 +13,7 @@
   "EXCEPTION_REQUEST_IS_EMPTY": "The request object is empty",\r
   "RULE_MANAGEMENT_CALL_DELETE_RULE_REST_FAILED": "Delete rules from engine call interface failure ",\r
   "RULE_MANAGEMENT_CALL_DEPLOY_RULE_REST_FAILED": "From the rules engine calls the deployment of interface failure",\r
-  "RULE_MANAGEMENT__CALL_CHECK_RULE_REST_FAILED": "From the rules engine calls the check of interface failure",\r
+  "RULE_MANAGEMENT_CALL_CHECK_RULE_REST_FAILED": "From the rules engine calls the check of interface failure",\r
   "RULE_MANAGEMENT_CREATE_QUERY_SQL_FAILED": "Create query exception",\r
   "RULE_MANAGEMENT_QUERY_RULE_FAILED": "Query rule failed",\r
   "RULE_MANAGEMENT_REQUEST_OBJECT_IS_EMPTY": "Request object is empty",\r
index 347986a..0b0d007 100644 (file)
@@ -9,7 +9,7 @@
   "ENGINE_QUERY_CACHE_FAILED":"查询缓存失败",\r
   "RULE_MANAGEMENT_CALL_DELETE_RULE_REST_FAILED": "从引擎调用删除规则接口失败",\r
   "RULE_MANAGEMENT_CALL_DEPLOY_RULE_REST_FAILED": "从引擎调用部署规则接口失败",\r
-  "RULE_MANAGEMENT__CALL_CHECK_RULE_REST_FAILED": "从引擎调用校验规则接口失败",\r
+  "RULE_MANAGEMENT_CALL_CHECK_RULE_REST_FAILED": "从引擎调用校验规则接口失败",\r
   "RULE_MANAGEMENT_CREATE_QUERY_SQL_FAILED": "创建查询语句异常",\r
   "RULE_MANAGEMENT_QUERY_RULE_FAILED": "查询规则失败",\r
   "RULE_MANAGEMENT_REQUEST_OBJECT_IS_EMPTY":"请求对象为空",\r
index e9c38b9..8cb3d2b 100644 (file)
@@ -15,6 +15,7 @@
  */\r
 package org.openo.holmes.common.producer;\r
 \r
+import java.io.Serializable;\r
 import javax.inject.Inject;\r
 import javax.jms.Connection;\r
 import javax.jms.ConnectionFactory;\r
@@ -41,22 +42,33 @@ public class MQProducer {
     private ConnectionFactory connectionFactory;\r
 \r
     public void sendAlarmMQTopicMsg(Alarm alarm) {\r
+        sendMQTopicMsg(alarm);\r
+    }\r
+\r
+    public void sendCorrelationMQTopicMsg(String ruleId, long createTimeL, Alarm parentAlarm,\r
+            Alarm childAlarm) {\r
+        CorrelationResult correlationResult = getCorrelationResult(ruleId, createTimeL, parentAlarm, childAlarm);\r
+        sendMQTopicMsg(correlationResult);\r
+    }\r
 \r
+    private <T> void sendMQTopicMsg(T t) {\r
+        Serializable msgEntity = (Serializable) t;\r
         Connection connection = null;\r
         Session session;\r
         Destination destination;\r
         MessageProducer messageProducer;\r
+\r
         try {\r
             connection = connectionFactory.createConnection();\r
             connection.start();\r
             session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);\r
-            destination = session.createTopic(AlarmConst.MQ_TOPIC_NAME_ALARM);\r
+            destination = session.createTopic(AlarmConst.MQ_TOPIC_NAME_ALARMS_CORRELATION);\r
             messageProducer = session.createProducer(destination);\r
-            ObjectMessage message = session.createObjectMessage(alarm);\r
+            ObjectMessage message = session.createObjectMessage(msgEntity);\r
             messageProducer.send(message);\r
             session.commit();\r
         } catch (Exception e) {\r
-            log.error("Failed send alarm." + e.getMessage(), e);\r
+            log.error("Failed send correlation." + e.getMessage(), e);\r
         } finally {\r
             if (connection != null) {\r
                 try {\r
@@ -68,39 +80,13 @@ public class MQProducer {
         }\r
     }\r
 \r
-    public void sendCorrelationMQTopicMsg(String ruleId, long createTimeL, Alarm parentAlarm,\r
+    private CorrelationResult getCorrelationResult(String ruleId, long createTimeL, Alarm parentAlarm,\r
             Alarm childAlarm) {\r
-\r
         CorrelationResult correlationResult = new CorrelationResult();\r
         correlationResult.setRuleId(ruleId);\r
         correlationResult.setCreateTimeL(createTimeL);\r
         correlationResult.setResultType(AplusResult.APLUS_CORRELATION);\r
         correlationResult.setAffectedAlarms(new Alarm[]{parentAlarm, childAlarm});\r
-\r
-        Connection connection = null;\r
-        Session session;\r
-        Destination destination;\r
-        MessageProducer messageProducer;\r
-\r
-        try {\r
-            connection = connectionFactory.createConnection();\r
-            connection.start();\r
-            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);\r
-            destination = session.createTopic(AlarmConst.MQ_TOPIC_NAME_ALARMS_CORRELATION);\r
-            messageProducer = session.createProducer(destination);\r
-            ObjectMessage message = session.createObjectMessage(correlationResult);\r
-            messageProducer.send(message);\r
-            session.commit();\r
-        } catch (Exception e) {\r
-            log.error("Failed send correlation." + e.getMessage(), e);\r
-        } finally {\r
-            if (connection != null) {\r
-                try {\r
-                    connection.close();\r
-                } catch (JMSException e) {\r
-                    log.error("Failed close connection." + e.getMessage(), e);\r
-                }\r
-            }\r
-        }\r
+        return correlationResult;\r
     }\r
 }\r
index 75aacb9..c30eff1 100644 (file)
@@ -38,7 +38,7 @@ public class I18nProxy {
     /*-----------------------Rule Management------------------------------- */\r
     public static final String RULE_MANAGEMENT_CALL_DELETE_RULE_REST_FAILED = "RULE_MANAGEMENT_CALL_DELETE_RULE_REST_FAILED";\r
     public static final String RULE_MANAGEMENT_CALL_DEPLOY_RULE_REST_FAILED = "RULE_MANAGEMENT_CALL_DEPLOY_RULE_REST_FAILED";\r
-    public static final String RULE_MANAGEMENT__CALL_CHECK_RULE_REST_FAILED = "RULE_MANAGEMENT__CALL_CHECK_RULE_REST_FAILED";\r
+    public static final String RULE_MANAGEMENT_CALL_CHECK_RULE_REST_FAILED = "RULE_MANAGEMENT_CALL_CHECK_RULE_REST_FAILED";\r
     public static final String RULE_MANAGEMENT_CREATE_QUERY_SQL_FAILED = "RULE_MANAGEMENT_CREATE_QUERY_SQL_FAILED";\r
     public static final String RULE_MANAGEMENT_QUERY_RULE_FAILED = "RULE_MANAGEMENT_QUERY_RULE_FAILED";\r
     public static final String RULE_MANAGEMENT_REQUEST_OBJECT_IS_EMPTY = "RULE_MANAGEMENT_REQUEST_OBJECT_IS_EMPTY";\r
index caef0b0..f030d3d 100644 (file)
  */\r
 package org.openo.holmes.common.utils;\r
 \r
-import com.fasterxml.jackson.core.JsonParseException;\r
 import com.fasterxml.jackson.core.JsonProcessingException;\r
-import com.fasterxml.jackson.databind.DeserializationFeature;\r
-import com.fasterxml.jackson.databind.JsonMappingException;\r
 import com.fasterxml.jackson.databind.ObjectMapper;\r
 import java.io.IOException;\r
 \r
@@ -40,16 +37,4 @@ public class JacksonUtil {
         }\r
         return objectMapper.readValue(json, cls);\r
     }\r
-\r
-    public static <T> T jsonToBeanByMatchAttribute(String json, Class<T> cls)\r
-        throws JsonParseException,\r
-        JsonMappingException, IOException {\r
-        if (JudgeNullUtil.isEmpty(json)) {\r
-            return null;\r
-        }\r
-        ObjectMapper objectMapper = new ObjectMapper();\r
-        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\r
-        return objectMapper.readValue(json, cls);\r
-    }\r
-\r
 }\r
index 1c8f72c..930905a 100644 (file)
@@ -25,7 +25,7 @@ public class LanguageUtil {
     }\r
 \r
     public static String getLanguage(HttpServletRequest servletRequest) {\r
-        String language = (String) servletRequest.getHeader("language-option");\r
+        String language = servletRequest.getHeader("language-option");\r
         if (JudgeNullUtil.isEmpty(language)) {\r
             language = AlarmConst.I18N_EN;\r
         }\r
@@ -38,7 +38,7 @@ public class LanguageUtil {
     }\r
 \r
     public static Locale getLocale(HttpServletRequest servletRequest) {\r
-        String language = (String) servletRequest.getHeader("language-option");\r
+        String language = servletRequest.getHeader("language-option");\r
         if (JudgeNullUtil.isEmpty(language)) {\r
             language = AlarmConst.I18N_EN;\r
         }\r
index 723b489..ec8fda6 100644 (file)
@@ -26,7 +26,7 @@ public class UserUtil {
 \r
     public static String getUserName(HttpServletRequest request) {\r
         String userName = AlarmConst.ADMIN;\r
-        String sessionName = (String) request.getHeader("username");\r
+        String sessionName = request.getHeader("username");\r
         if (sessionName != null) {\r
             userName = sessionName.toLowerCase();\r
         }\r
index b740d87..49858ab 100644 (file)
@@ -170,9 +170,9 @@ public class AlarmTest {
     @Test
     public void testGetAlarmTypeRuleId_notNull() throws Exception {
         final String ruleId = "ruleId";
-        final int rootAlarmTyep = 2;
-        alarm.getRootAlarmTypeMap().put(ruleId, rootAlarmTyep);
-        assertThat(rootAlarmTyep, equalTo(alarm.getRootAlarmType(ruleId)));
+        final int rootAlarmType = 2;
+        alarm.getRootAlarmTypeMap().put(ruleId, rootAlarmType);
+        assertThat(rootAlarmType, equalTo(alarm.getRootAlarmType(ruleId)));
     }
 
     @Test
index b56e4ee..18c774e 100644 (file)
@@ -18,10 +18,13 @@ package org.openo.holmes.common.utils;
 
 import static org.easymock.EasyMock.anyObject;
 import static org.easymock.EasyMock.expect;
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.Assert.assertThat;
 
 import io.dropwizard.db.DataSourceFactory;
 import io.dropwizard.jdbi.DBIFactory;
 import io.dropwizard.setup.Environment;
+import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -81,7 +84,7 @@ public class DbDaoUtilTest {
     }
 
     @Test
-    public void getDao() throws Exception {
+    public void getDao_normal() throws Exception {
         Whitebox.setInternalState(dbDaoUtil, "jdbi", jdbi);
         expect(jdbi.open(anyObject(Class.class))).andReturn(Class.class);
 
@@ -93,7 +96,22 @@ public class DbDaoUtilTest {
     }
 
     @Test
-    public void testGetHandle() throws Exception {
+    public void getDao_exception() throws Exception {
+        Whitebox.setInternalState(dbDaoUtil, "jdbi", jdbi);
+
+        expect(jdbi.open(anyObject(Class.class))).andThrow(new RuntimeException(""));
+
+        PowerMock.replayAll();
+
+        Object o = dbDaoUtil.getDao(String.class);
+
+        PowerMock.verifyAll();
+
+        assertThat(o, equalTo(null));
+    }
+
+    @Test
+    public void getHandle_normal() throws Exception {
         Handle handle = PowerMock.createMock(Handle.class);
 
         Whitebox.setInternalState(dbDaoUtil, "jdbi", jdbi);
@@ -105,9 +123,24 @@ public class DbDaoUtilTest {
 
         PowerMock.verifyAll();
     }
+    @Test
+    public void getHandle_exception() throws Exception {
+        Handle handle = PowerMock.createMock(Handle.class);
+
+        Whitebox.setInternalState(dbDaoUtil, "jdbi", jdbi);
+        expect(jdbi.open()).andThrow(new RuntimeException(""));
+
+        PowerMock.replayAll();
+
+        Handle handle1 = dbDaoUtil.getHandle();
+
+        PowerMock.verifyAll();
+
+        assertThat(handle1, equalTo(null));
+    }
 
     @Test
-    public void testClose() throws Exception {
+    public void close_normal() throws Exception {
         Whitebox.setInternalState(dbDaoUtil, "jdbi", jdbi);
         jdbi.close(anyObject());
 
@@ -118,6 +151,17 @@ public class DbDaoUtilTest {
         PowerMock.verifyAll();
     }
 
+    @Test
+    public void close_exception() throws Exception {
+        Whitebox.setInternalState(dbDaoUtil, "jdbi", jdbi);
+        jdbi.close(anyObject());
+        EasyMock.expectLastCall().andThrow(new RuntimeException(""));
+        PowerMock.replayAll();
+
+        dbDaoUtil.close(new Object());
+
+        PowerMock.verifyAll();
+    }
     @Test
     public void testGetJdbiDaoByOnDemand() throws Exception {
         Whitebox.setInternalState(dbDaoUtil, "jdbi", jdbi);
index 64b31f4..c3631ac 100644 (file)
@@ -21,6 +21,7 @@ import static org.hamcrest.core.IsEqual.equalTo;
 import static org.junit.Assert.assertThat;\r
 \r
 import java.util.Locale;\r
+import java.util.Map;\r
 import org.junit.Before;\r
 import org.junit.Test;\r
 \r
@@ -34,8 +35,28 @@ public class I18nProxyTest {
     }\r
 \r
     @Test\r
-    public void testGetValue() {\r
+    public void getValue_locale_and_key() {\r
         String result = i18nProxy.getValue(new Locale("zh"), "test");\r
         assertThat(result, equalTo(null));\r
     }\r
+    @Test\r
+    public void getValueByArgs(){\r
+        String result = i18nProxy.getValueByArgs(new Locale("zh"), "test",new String[]{"1"});\r
+        assertThat(result,equalTo(null));\r
+    }\r
+    @Test\r
+    public void getValue_by_key(){\r
+        Map<String,String> result = i18nProxy.getValue("test");\r
+        assertThat(result, equalTo(null));\r
+    }\r
+    @Test\r
+    public void jsonI18n(){\r
+        String result = i18nProxy.jsonI18n("test");\r
+        assertThat(result,equalTo(null));\r
+    }\r
+    @Test\r
+    public void i18nWithArgs(){\r
+        String result = i18nProxy.i18nWithArgs("test",new String[]{});\r
+        assertThat(result,equalTo("null"));\r
+    }\r
 }
\ No newline at end of file
index 25da9ac..a2a0542 100644 (file)
@@ -26,7 +26,7 @@ import org.junit.Test;
 public class JudgeNullUtilTest {\r
 \r
     @Test\r
-    public void isEmpty_array() {\r
+    public void isEmpty_array_length_zero() {\r
         boolean resultShorts = JudgeNullUtil.isEmpty(new short[]{});\r
         boolean resultInts = JudgeNullUtil.isEmpty(new int[]{});\r
         boolean resultLongs = JudgeNullUtil.isEmpty(new long[]{});\r
@@ -40,5 +40,4 @@ public class JudgeNullUtilTest {
         assertThat(true, equalTo(resultStrings));\r
         assertThat(true, equalTo(resultLists));\r
     }\r
-\r
 }
\ No newline at end of file