[ 
https://issues.apache.org/jira/browse/KYLIN-3597?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16718373#comment-16718373
 ] 

ASF GitHub Bot commented on KYLIN-3597:
---------------------------------------

shaofengshi closed pull request #383: KYLIN-3597 fix sonar issues
URL: https://github.com/apache/kylin/pull/383
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git 
a/core-common/src/main/java/org/apache/kylin/common/KylinVersion.java 
b/core-common/src/main/java/org/apache/kylin/common/KylinVersion.java
index ae18d0b57b..bbdb3a8645 100644
--- a/core-common/src/main/java/org/apache/kylin/common/KylinVersion.java
+++ b/core-common/src/main/java/org/apache/kylin/common/KylinVersion.java
@@ -34,8 +34,8 @@
 import com.google.common.collect.Iterables;
 
 public class KylinVersion implements Comparable {
-    private static final String COMMIT_SHA1_v15 = "commit_SHA1";
-    private static final String COMMIT_SHA1_v13 = "commit.sha1";
+    private static final String COMMIT_SHA1_V15 = "commit_SHA1";
+    private static final String COMMIT_SHA1_V13 = "commit.sha1";
 
     public final int major;
     public final int minor;
@@ -194,9 +194,9 @@ public static String getKylinClientInformation() {
 
     public static String getGitCommitInfo() {
         try {
-            File commitFile = new File(KylinConfig.getKylinHome(), 
COMMIT_SHA1_v15);
+            File commitFile = new File(KylinConfig.getKylinHome(), 
COMMIT_SHA1_V15);
             if (!commitFile.exists()) {
-                commitFile = new File(KylinConfig.getKylinHome(), 
COMMIT_SHA1_v13);
+                commitFile = new File(KylinConfig.getKylinHome(), 
COMMIT_SHA1_V13);
             }
             List<String> lines = FileUtils.readLines(commitFile, 
Charset.defaultCharset());
             StringBuilder sb = new StringBuilder();
diff --git 
a/core-common/src/main/java/org/apache/kylin/common/QueryContext.java 
b/core-common/src/main/java/org/apache/kylin/common/QueryContext.java
index a065a13f11..000f7bf28a 100644
--- a/core-common/src/main/java/org/apache/kylin/common/QueryContext.java
+++ b/core-common/src/main/java/org/apache/kylin/common/QueryContext.java
@@ -40,6 +40,9 @@
 public class QueryContext {
 
     private static final Logger logger = 
LoggerFactory.getLogger(QueryContext.class);
+    private static final String CSSR_SHOULD_BE_INIT_FOR_CONTEXT = 
"CubeSegmentStatisticsResult should be initialized for context {}";
+    private static final String CSSM_SHOULD_BE_INIT_FOR_CSSR = 
"cubeSegmentStatisticsMap should be initialized for CubeSegmentStatisticsResult 
with query type {}";
+    private static final String INPUT = " input ";
 
     public interface QueryStopListener {
         void stop(QueryContext query);
@@ -208,13 +211,12 @@ public void setContextRealization(int ctxId, String 
realizationName, int realiza
     public CubeSegmentStatistics getCubeSegmentStatistics(int ctxId, String 
cubeName, String segmentName) {
         CubeSegmentStatisticsResult cubeSegmentStatisticsResult = 
cubeSegmentStatisticsResultMap.get(ctxId);
         if (cubeSegmentStatisticsResult == null) {
-            logger.warn("CubeSegmentStatisticsResult should be initialized for 
context {}", ctxId);
+            logger.warn(CSSR_SHOULD_BE_INIT_FOR_CONTEXT, ctxId);
             return null;
         }
         ConcurrentMap<String, ConcurrentMap<String, CubeSegmentStatistics>> 
cubeSegmentStatisticsMap = cubeSegmentStatisticsResult.cubeSegmentStatisticsMap;
         if (cubeSegmentStatisticsMap == null) {
-            logger.warn(
-                    "cubeSegmentStatisticsMap should be initialized for 
CubeSegmentStatisticsResult with query type {}", 
cubeSegmentStatisticsResult.queryType);
+            logger.warn(CSSM_SHOULD_BE_INIT_FOR_CSSR, 
cubeSegmentStatisticsResult.queryType);
             return null;
         }
         ConcurrentMap<String, CubeSegmentStatistics> segmentStatisticsMap = 
cubeSegmentStatisticsMap.get(cubeName);
@@ -235,13 +237,12 @@ public CubeSegmentStatistics getCubeSegmentStatistics(int 
ctxId, String cubeName
     public void addCubeSegmentStatistics(int ctxId, CubeSegmentStatistics 
cubeSegmentStatistics) {
         CubeSegmentStatisticsResult cubeSegmentStatisticsResult = 
cubeSegmentStatisticsResultMap.get(ctxId);
         if (cubeSegmentStatisticsResult == null) {
-            logger.warn("CubeSegmentStatisticsResult should be initialized for 
context {}", ctxId);
+            logger.warn(CSSR_SHOULD_BE_INIT_FOR_CONTEXT, ctxId);
             return;
         }
         ConcurrentMap<String, ConcurrentMap<String, CubeSegmentStatistics>> 
cubeSegmentStatisticsMap = cubeSegmentStatisticsResult.cubeSegmentStatisticsMap;
         if (cubeSegmentStatisticsMap == null) {
-            logger.warn(
-                    "cubeSegmentStatisticsMap should be initialized for 
CubeSegmentStatisticsResult with query type {}", 
cubeSegmentStatisticsResult.queryType);
+            logger.warn(CSSM_SHOULD_BE_INIT_FOR_CSSR, 
cubeSegmentStatisticsResult.queryType);
             return;
         }
         String cubeName = cubeSegmentStatistics.cubeName;
@@ -262,14 +263,12 @@ public void addRPCStatistics(int ctxId, String rpcServer, 
String cubeName, Strin
 
         CubeSegmentStatisticsResult cubeSegmentStatisticsResult = 
cubeSegmentStatisticsResultMap.get(ctxId);
         if (cubeSegmentStatisticsResult == null) {
-            logger.warn("CubeSegmentStatisticsResult should be initialized for 
context {}", ctxId);
+            logger.warn(CSSR_SHOULD_BE_INIT_FOR_CONTEXT, ctxId);
             return;
         }
         ConcurrentMap<String, ConcurrentMap<String, CubeSegmentStatistics>> 
cubeSegmentStatisticsMap = cubeSegmentStatisticsResult.cubeSegmentStatisticsMap;
         if (cubeSegmentStatisticsMap == null) {
-            logger.warn(
-                    "cubeSegmentStatisticsMap should be initialized for 
CubeSegmentStatisticsResult with query type {}",
-                    cubeSegmentStatisticsResult.queryType);
+            logger.warn(CSSM_SHOULD_BE_INIT_FOR_CSSR, 
cubeSegmentStatisticsResult.queryType);
             return;
         }
         cubeSegmentStatisticsMap.putIfAbsent(cubeName, Maps.<String, 
CubeSegmentStatistics> newConcurrentMap());
@@ -285,14 +284,14 @@ public void addRPCStatistics(int ctxId, String rpcServer, 
String cubeName, Strin
             StringBuilder inconsistency = new StringBuilder();
             if (segmentStatistics.sourceCuboidId != sourceCuboidId) {
                 inconsistency.append(
-                        "sourceCuboidId exist " + 
segmentStatistics.sourceCuboidId + " input " + sourceCuboidId);
+                        "sourceCuboidId exist " + 
segmentStatistics.sourceCuboidId + INPUT + sourceCuboidId);
             }
             if (segmentStatistics.targetCuboidId != targetCuboidId) {
                 inconsistency.append(
-                        "targetCuboidId exist " + 
segmentStatistics.targetCuboidId + " input " + targetCuboidId);
+                        "targetCuboidId exist " + 
segmentStatistics.targetCuboidId + INPUT + targetCuboidId);
             }
             if (segmentStatistics.filterMask != filterMask) {
-                inconsistency.append("filterMask exist " + 
segmentStatistics.filterMask + " input " + filterMask);
+                inconsistency.append("filterMask exist " + 
segmentStatistics.filterMask + INPUT + filterMask);
             }
             logger.error("cube segment statistics wrapper is not consistent 
due to " + inconsistency.toString());
             return;
diff --git 
a/core-common/src/main/java/org/apache/kylin/common/metrics/metrics2/JsonFileMetricsReporter.java
 
b/core-common/src/main/java/org/apache/kylin/common/metrics/metrics2/JsonFileMetricsReporter.java
index 95c51162c6..40cb0a67f9 100644
--- 
a/core-common/src/main/java/org/apache/kylin/common/metrics/metrics2/JsonFileMetricsReporter.java
+++ 
b/core-common/src/main/java/org/apache/kylin/common/metrics/metrics2/JsonFileMetricsReporter.java
@@ -98,20 +98,14 @@ public void run() {
                         return;
                     }
 
-                    BufferedWriter bw = null;
-                    try {
+                    try (BufferedWriter bw = new BufferedWriter(
+                            new OutputStreamWriter(fs.create(tmpPath, true), 
StandardCharsets.UTF_8))) {
                         fs.delete(tmpPath, true);
-                        bw = new BufferedWriter(
-                                new OutputStreamWriter(fs.create(tmpPath, 
true), StandardCharsets.UTF_8));
                         bw.write(json);
                         fs.setPermission(tmpPath, 
FsPermission.createImmutable((short) 0644));
                     } catch (IOException e) {
                         LOGGER.error("Unable to write to temp file " + 
tmpPath, e);
                         return;
-                    } finally {
-                        if (bw != null) {
-                            bw.close();
-                        }
                     }
 
                     try {
diff --git 
a/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCConnectionManager.java
 
b/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCConnectionManager.java
index 5f56de1c74..dcb9a1bb49 100644
--- 
a/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCConnectionManager.java
+++ 
b/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCConnectionManager.java
@@ -39,6 +39,7 @@
 public class JDBCConnectionManager {
 
     private static final Logger logger = 
LoggerFactory.getLogger(JDBCConnectionManager.class);
+    private static final String PASSWORD = "password";
 
     private static JDBCConnectionManager INSTANCE = null;
 
@@ -74,7 +75,7 @@ private JDBCConnectionManager(KylinConfig config) {
         JDBCResourceStore.checkScheme(metadataUrl);
 
         LinkedHashMap<String, String> ret = new 
LinkedHashMap<>(metadataUrl.getAllParameters());
-        List<String> mandatoryItems = Arrays.asList("url", "username", 
"password");
+        List<String> mandatoryItems = Arrays.asList("url", "username", 
PASSWORD);
 
         for (String item : mandatoryItems) {
             Preconditions.checkNotNull(ret.get(item),
diff --git 
a/core-common/src/main/java/org/apache/kylin/common/restclient/RestClient.java 
b/core-common/src/main/java/org/apache/kylin/common/restclient/RestClient.java
index 9f95a7c316..adfa7612fe 100644
--- 
a/core-common/src/main/java/org/apache/kylin/common/restclient/RestClient.java
+++ 
b/core-common/src/main/java/org/apache/kylin/common/restclient/RestClient.java
@@ -30,7 +30,6 @@
 
 import javax.xml.bind.DatatypeConverter;
 
-import org.apache.commons.io.IOUtils;
 import org.apache.http.HttpResponse;
 import org.apache.http.auth.AuthScope;
 import org.apache.http.auth.UsernamePasswordCredentials;
@@ -60,6 +59,11 @@
 public class RestClient {
 
     private static final Logger logger = 
LoggerFactory.getLogger(RestClient.class);
+    private static final String UTF_8 = "UTF-8";
+    private static final String APPLICATION_JSON = "application/json";
+    private static final String INVALID_RESPONSE = "Invalid response ";
+    private static final String CUBES = "/cubes/";
+    private static final String WITH_URL = " with url ";
 
     protected static Pattern fullRestPattern = 
Pattern.compile("(?:([^:]+)[:]([^@]+)[@])?([^:]+)(?:[:](\\d+))?");
 
@@ -156,7 +160,7 @@ public void wipeCache(String entity, String event, String 
cacheKey) throws IOExc
         if (cacheKey.contains("/")) {
             url = baseUrl + "/cache/" + entity + "/" + event;
             request = new HttpPut(url);
-            request.setEntity(new StringEntity(cacheKey, 
ContentType.create("application/json", "UTF-8")));
+            request.setEntity(new StringEntity(cacheKey, 
ContentType.create(APPLICATION_JSON, UTF_8)));
         } else {
             url = baseUrl + "/cache/" + entity + "/" + cacheKey + "/" + event;
             request = new HttpPut(url);
@@ -168,7 +172,7 @@ public void wipeCache(String entity, String event, String 
cacheKey) throws IOExc
 
             if (response.getStatusLine().getStatusCode() != 200) {
                 String msg = EntityUtils.toString(response.getEntity());
-                throw new IOException("Invalid response " + 
response.getStatusLine().getStatusCode()
+                throw new IOException(INVALID_RESPONSE + 
response.getStatusLine().getStatusCode()
                         + " with cache wipe url " + url + "\n" + msg);
             }
         } finally {
@@ -187,7 +191,7 @@ public String getKylinProperties() throws IOException {
             msg = map.get("config");
 
             if (response.getStatusLine().getStatusCode() != 200)
-                throw new IOException("Invalid response " + 
response.getStatusLine().getStatusCode()
+                throw new IOException(INVALID_RESPONSE + 
response.getStatusLine().getStatusCode()
                         + " with cache wipe url " + url + "\n" + msg);
             return msg;
         } finally {
@@ -204,7 +208,7 @@ public boolean disableCache() throws IOException {
     }
 
     public boolean buildCube(String cubeName, long startTime, long endTime, 
String buildType) throws Exception {
-        String url = baseUrl + "/cubes/" + cubeName + "/build";
+        String url = baseUrl + CUBES + cubeName + "/build";
         HttpPut put = newPut(url);
         HttpResponse response = null;
         try {
@@ -213,11 +217,11 @@ public boolean buildCube(String cubeName, long startTime, 
long endTime, String b
             paraMap.put("endTime", endTime + "");
             paraMap.put("buildType", buildType);
             String jsonMsg = new ObjectMapper().writeValueAsString(paraMap);
-            put.setEntity(new StringEntity(jsonMsg, "UTF-8"));
+            put.setEntity(new StringEntity(jsonMsg, UTF_8));
             response = client.execute(put);
             getContent(response);
             if (response.getStatusLine().getStatusCode() != 200) {
-                throw new IOException("Invalid response " + 
response.getStatusLine().getStatusCode()
+                throw new IOException(INVALID_RESPONSE + 
response.getStatusLine().getStatusCode()
                         + " with build cube url " + url + "\n" + jsonMsg);
             } else {
                 return true;
@@ -228,19 +232,19 @@ public boolean buildCube(String cubeName, long startTime, 
long endTime, String b
     }
 
     public boolean disableCube(String cubeName) throws Exception {
-        return changeCubeStatus(baseUrl + "/cubes/" + cubeName + "/disable");
+        return changeCubeStatus(baseUrl + CUBES + cubeName + "/disable");
     }
 
     public boolean enableCube(String cubeName) throws Exception {
-        return changeCubeStatus(baseUrl + "/cubes/" + cubeName + "/enable");
+        return changeCubeStatus(baseUrl + CUBES + cubeName + "/enable");
     }
 
     public boolean purgeCube(String cubeName) throws Exception {
-        return changeCubeStatus(baseUrl + "/cubes/" + cubeName + "/purge");
+        return changeCubeStatus(baseUrl + CUBES + cubeName + "/purge");
     }
 
     public HashMap getCube(String cubeName) throws Exception {
-        String url = baseUrl + "/cubes/" + cubeName;
+        String url = baseUrl + CUBES + cubeName;
         HttpGet get = newGet(url);
         HttpResponse response = null;
         try {
@@ -258,12 +262,12 @@ private boolean changeCubeStatus(String url) throws 
Exception {
         try {
             HashMap<String, String> paraMap = new HashMap<String, String>();
             String jsonMsg = new ObjectMapper().writeValueAsString(paraMap);
-            put.setEntity(new StringEntity(jsonMsg, "UTF-8"));
+            put.setEntity(new StringEntity(jsonMsg, UTF_8));
             response = client.execute(put);
             getContent(response);
             if (response.getStatusLine().getStatusCode() != 200) {
-                throw new IOException("Invalid response " + 
response.getStatusLine().getStatusCode() + " with url "
-                        + url + "\n" + jsonMsg);
+                throw new IOException(
+                        INVALID_RESPONSE + 
response.getStatusLine().getStatusCode() + WITH_URL + url + "\n" + jsonMsg);
             } else {
                 return true;
             }
@@ -279,7 +283,7 @@ public HttpResponse query(String sql, String project) 
throws IOException {
         paraMap.put("sql", sql);
         paraMap.put("project", project);
         String jsonMsg = new ObjectMapper().writeValueAsString(paraMap);
-        post.setEntity(new StringEntity(jsonMsg, "UTF-8"));
+        post.setEntity(new StringEntity(jsonMsg, UTF_8));
         HttpResponse response = client.execute(post);
         return response;
     }
@@ -290,7 +294,7 @@ public void clearCacheForCubeMigration(String cube, String 
project, String model
         HttpPost post = new HttpPost(url);
 
         post.addHeader("Accept", "application/json, text/plain, */*");
-        post.addHeader("Content-Type", "application/json");
+        post.addHeader("Content-Type", APPLICATION_JSON);
 
         HashMap<String, Object> paraMap = new HashMap<String, Object>();
         paraMap.put("cube", cube);
@@ -298,10 +302,10 @@ public void clearCacheForCubeMigration(String cube, 
String project, String model
         paraMap.put("model", model);
         paraMap.put("tableToProjects", tableToProjects);
         String jsonMsg = JsonUtil.writeValueAsString(paraMap);
-        post.setEntity(new StringEntity(jsonMsg, "UTF-8"));
+        post.setEntity(new StringEntity(jsonMsg, UTF_8));
         HttpResponse response = client.execute(post);
         if (response.getStatusLine().getStatusCode() != 200) {
-            throw new IOException("Invalid response " + 
response.getStatusLine().getStatusCode());
+            throw new IOException(INVALID_RESPONSE + 
response.getStatusLine().getStatusCode());
         }
     }
 
@@ -311,8 +315,7 @@ public void buildLookupSnapshotCache(String project, String 
lookupTableName, Str
         HttpResponse response = client.execute(put);
         getContent(response);
         if (response.getStatusLine().getStatusCode() != 200) {
-            throw new IOException(
-                    "Invalid response " + 
response.getStatusLine().getStatusCode() + " with url " + url + "\n");
+            throw new IOException(INVALID_RESPONSE + 
response.getStatusLine().getStatusCode() + WITH_URL + url + "\n");
         }
     }
 
@@ -322,15 +325,14 @@ public String getLookupSnapshotCacheState(String 
lookupTableName, String snapsho
         HttpResponse response = client.execute(get);
         String content = getContent(response);
         if (response.getStatusLine().getStatusCode() != 200) {
-            throw new IOException(
-                    "Invalid response " + 
response.getStatusLine().getStatusCode() + " with url " + url + "\n");
+            throw new IOException(INVALID_RESPONSE + 
response.getStatusLine().getStatusCode() + WITH_URL + url + "\n");
         }
         return content;
     }
 
     private HashMap dealResponse(HttpResponse response) throws IOException {
         if (response.getStatusLine().getStatusCode() != 200) {
-            throw new IOException("Invalid response " + 
response.getStatusLine().getStatusCode());
+            throw new IOException(INVALID_RESPONSE + 
response.getStatusLine().getStatusCode());
         }
         String result = getContent(response);
         HashMap resultMap = new ObjectMapper().readValue(result, 
HashMap.class);
@@ -339,7 +341,7 @@ private HashMap dealResponse(HttpResponse response) throws 
IOException {
 
     private void addHttpHeaders(HttpRequestBase method) {
         method.addHeader("Accept", "application/json, text/plain, */*");
-        method.addHeader("Content-Type", "application/json");
+        method.addHeader("Content-Type", APPLICATION_JSON);
         String basicAuth = DatatypeConverter
                 .printBase64Binary((this.userName + ":" + 
this.password).getBytes(StandardCharsets.UTF_8));
         method.addHeader("Authorization", "Basic " + basicAuth);
@@ -371,7 +373,7 @@ private boolean setCache(boolean flag) throws IOException {
             HashMap<String, String> paraMap = new HashMap<String, String>();
             paraMap.put("key", "kylin.query.cache-enabled");
             paraMap.put("value", flag + "");
-            put.setEntity(new StringEntity(new 
ObjectMapper().writeValueAsString(paraMap), "UTF-8"));
+            put.setEntity(new StringEntity(new 
ObjectMapper().writeValueAsString(paraMap), UTF_8));
             response = client.execute(put);
             EntityUtils.consume(response.getEntity());
             if (response.getStatusLine().getStatusCode() != 200) {
@@ -385,20 +387,15 @@ private boolean setCache(boolean flag) throws IOException 
{
     }
 
     private String getContent(HttpResponse response) throws IOException {
-        InputStreamReader reader = null;
-        BufferedReader rd = null;
         StringBuffer result = new StringBuffer();
-        try {
-            reader = new InputStreamReader(response.getEntity().getContent(), 
StandardCharsets.UTF_8);
-            rd = new BufferedReader(reader);
-            String line = null;
+        try (BufferedReader rd = new BufferedReader(
+                new InputStreamReader(response.getEntity().getContent(), 
StandardCharsets.UTF_8))) {
+            String line;
             while ((line = rd.readLine()) != null) {
                 result.append(line);
             }
-        } finally {
-            IOUtils.closeQuietly(reader);
-            IOUtils.closeQuietly(rd);
         }
+
         return result.toString();
     }
 


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


> Fix sonar reported static code issues
> -------------------------------------
>
>                 Key: KYLIN-3597
>                 URL: https://issues.apache.org/jira/browse/KYLIN-3597
>             Project: Kylin
>          Issue Type: Improvement
>          Components: Others
>            Reporter: Shaofeng SHI
>            Priority: Major
>             Fix For: v2.6.0
>
>




--
This message was sent by Atlassian JIRA
(v7.6.3#76005)

Reply via email to