From 5c6d5fcadc23df50f5cffb1e55c93cd746a2707a Mon Sep 17 00:00:00 2001 From: wenshao Date: Wed, 29 Aug 2012 15:36:45 +0800 Subject: [PATCH] fixed sonar rule violations --- .../alibaba/druid/pool/DruidDataSource.java | 4 +- .../druid/sql/ast/expr/SQLBetweenExpr.java | 5 +- .../druid/sql/ast/expr/SQLInListExpr.java | 5 +- .../ast/statement/SQLSelectQueryBlock.java | 8 +- .../mysql/visitor/MySqlOutputVisitor.java | 23 +-- .../oracle/ast/stmt/OracleConstraint.java | 7 +- .../ast/stmt/OracleSelectQueryBlock.java | 10 +- .../oracle/parser/OracleSelectParser.java | 13 +- .../sql/visitor/SQLASTOutputVisitor.java | 14 +- .../com/alibaba/druid/stat/JdbcSqlStat.java | 16 +- .../druid/support/console/DruidStat.java | 12 +- .../druid/support/console/TableFormatter.java | 8 +- .../support/console/TabledDataPrinter.java | 140 ++++++++---------- .../java/com/alibaba/druid/util/Base64.java | 12 +- .../alibaba/druid/util/LazyCompositeData.java | 8 +- .../com/alibaba/druid/util/MapComparator.java | 8 +- .../alibaba/druid/util/ThreadLocalRandom.java | 124 +++++++--------- 17 files changed, 206 insertions(+), 211 deletions(-) diff --git a/src/main/java/com/alibaba/druid/pool/DruidDataSource.java b/src/main/java/com/alibaba/druid/pool/DruidDataSource.java index 01eb315ba9..1e920a115a 100644 --- a/src/main/java/com/alibaba/druid/pool/DruidDataSource.java +++ b/src/main/java/com/alibaba/druid/pool/DruidDataSource.java @@ -537,7 +537,9 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat } } else if (JdbcUtils.MYSQL.equals(this.dbType)) { if (!this.isTestWhileIdle()) { - if (LOG.isWarnEnabled()) LOG.warn("Your dbType is mysql, recommend set testWhileIdle is true"); + if (LOG.isWarnEnabled()) { + LOG.warn("Your dbType is mysql, recommend set testWhileIdle is true"); + } } } } diff --git a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBetweenExpr.java b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBetweenExpr.java index f32704d7d0..5ddc9b7a35 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBetweenExpr.java +++ b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBetweenExpr.java @@ -50,8 +50,9 @@ public class SQLBetweenExpr extends SQLExprImpl implements Serializable { public void output(StringBuffer buf) { this.testExpr.output(buf); - if (this.not) buf.append(" NOT BETWEEN "); - else { + if (this.not) { + buf.append(" NOT BETWEEN "); + } else { buf.append(" BETWEEN "); } this.beginExpr.output(buf); diff --git a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLInListExpr.java b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLInListExpr.java index 9ce6c13eef..cfc79d5ef6 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLInListExpr.java +++ b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLInListExpr.java @@ -72,8 +72,9 @@ public class SQLInListExpr extends SQLExprImpl implements Serializable { public void output(StringBuffer buf) { this.expr.output(buf); - if (this.not) buf.append("NOT IN "); - else { + if (this.not) { + buf.append("NOT IN "); + } else { buf.append("IN "); } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java index feec54aa4a..b2cb7b96bf 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java @@ -100,9 +100,11 @@ public class SQLSelectQueryBlock extends SQLSelectQuery { public void output(StringBuffer buf) { buf.append("SELECT "); - if (SQLSetQuantifier.ALL == this.distionOption) buf.append("ALL "); - else if (SQLSetQuantifier.DISTINCT == this.distionOption) buf.append("DISTINCT "); - else if (SQLSetQuantifier.UNIQUE == this.distionOption) { + if (SQLSetQuantifier.ALL == this.distionOption) { + buf.append("ALL "); + } else if (SQLSetQuantifier.DISTINCT == this.distionOption) { + buf.append("DISTINCT "); + } else if (SQLSetQuantifier.UNIQUE == this.distionOption) { buf.append("UNIQUE "); } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java index 028921749f..50e65a8080 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java @@ -170,9 +170,11 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV print(' '); } - if (SQLSetQuantifier.ALL == x.getDistionOption()) print("ALL "); - else if (SQLSetQuantifier.DISTINCT == x.getDistionOption()) print("DISTINCT "); - else if (SQLSetQuantifier.DISTINCTROW == x.getDistionOption()) { + if (SQLSetQuantifier.ALL == x.getDistionOption()) { + print("ALL "); + } else if (SQLSetQuantifier.DISTINCT == x.getDistionOption()) { + print("DISTINCT "); + } else if (SQLSetQuantifier.DISTINCTROW == x.getDistionOption()) { print("DISTINCTROW "); } @@ -495,7 +497,8 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV print("@@global."); } else { String varName = x.getName(); - if ((!varName.startsWith("@")) && (!varName.equals("?")) && (!varName.startsWith("#")) && (!varName.startsWith("$"))) { + if ((!varName.startsWith("@")) && (!varName.equals("?")) && (!varName.startsWith("#")) + && (!varName.startsWith("$"))) { print("@@"); } } @@ -2568,7 +2571,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV public void endVisit(MySqlAlterTableAddIndex x) { } - + @Override public boolean visit(MySqlAlterTableAddUnique x) { print("ADD "); @@ -2576,9 +2579,9 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV print(x.getType()); print(" "); } - + print("UNIQUE "); - + if (x.getName() != null) { x.getName().accept(this); print(' '); @@ -2586,17 +2589,17 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV print("("); printAndAccept(x.getItems(), ", "); print(")"); - + if (x.getUsing() != null) { print(" USING "); print(x.getUsing()); } return false; } - + @Override public void endVisit(MySqlAlterTableAddUnique x) { - + } @Override diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleConstraint.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleConstraint.java index 801de0b555..d41261f41d 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleConstraint.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleConstraint.java @@ -35,8 +35,11 @@ public abstract class OracleConstraint extends OracleSQLObjectImpl { } public void setName(String name) { - if (name == null) this.name = null; - else this.name = new SQLIdentifierExpr(name); + if (name == null) { + this.name = null; + } else { + this.name = new SQLIdentifierExpr(name); + } } public void setName(SQLName name) { diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectQueryBlock.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectQueryBlock.java index 8641801335..d26cc5b3e9 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectQueryBlock.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectQueryBlock.java @@ -30,7 +30,7 @@ public class OracleSelectQueryBlock extends SQLSelectQueryBlock { private static final long serialVersionUID = 1L; - private final List hints = new ArrayList(1); + private final List hints = new ArrayList(1); private OracleSelectHierachicalQueryClause hierachicalQueryClause; private ModelClause modelClause; @@ -93,9 +93,11 @@ public class OracleSelectQueryBlock extends SQLSelectQueryBlock { public void output(StringBuffer buf) { buf.append("SELECT "); - if (SQLSetQuantifier.ALL == this.distionOption) buf.append("ALL "); - else if (SQLSetQuantifier.DISTINCT == this.distionOption) buf.append("DISTINCT "); - else if (SQLSetQuantifier.UNIQUE == this.distionOption) { + if (SQLSetQuantifier.ALL == this.distionOption) { + buf.append("ALL "); + } else if (SQLSetQuantifier.DISTINCT == this.distionOption) { + buf.append("DISTINCT "); + } else if (SQLSetQuantifier.UNIQUE == this.distionOption) { buf.append("UNIQUE "); } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java index 35998bdfee..94dfc06e2f 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java @@ -72,7 +72,7 @@ import com.alibaba.druid.sql.parser.Token; public class OracleSelectParser extends SQLSelectParser { public OracleSelectParser(String sql){ - super (new OracleExprParser(sql)); + super(new OracleExprParser(sql)); } public OracleSelectParser(SQLExprParser exprParser){ @@ -194,8 +194,9 @@ public class OracleSelectParser extends SQLSelectParser { if (identifierEquals("READ")) { lexer.nextToken(); - if (identifierEquals("ONLY")) lexer.nextToken(); - else { + if (identifierEquals("ONLY")) { + lexer.nextToken(); + } else { throw new ParserException("syntax error"); } @@ -203,8 +204,9 @@ public class OracleSelectParser extends SQLSelectParser { } else if (lexer.token() == (Token.CHECK)) { lexer.nextToken(); - if (identifierEquals("OPTION")) lexer.nextToken(); - else { + if (identifierEquals("OPTION")) { + lexer.nextToken(); + } else { throw new ParserException("syntax error"); } @@ -348,7 +350,6 @@ public class OracleSelectParser extends SQLSelectParser { model.setReturnRowsClause(returnRowsClause); } - while (identifierEquals("REFERENCE")) { ReferenceModelClause referenceModelClause = new ReferenceModelClause(); lexer.nextToken(); diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java index 3ea42f7244..83bdbb4ea4 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java @@ -245,7 +245,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { for (int i = groupList.size() - 1; i >= 0; --i) { SQLExpr item = groupList.get(i); visitBinaryLeft(item, x.getOperator()); - + if (relational) { println(); } else { @@ -255,7 +255,6 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { print(" "); } - visitorBinaryRight(x); if (isRoot && relational) { @@ -376,8 +375,9 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { } public boolean visit(SQLExistsExpr x) { - if (x.isNot()) print("NOT EXISTS ("); - else { + if (x.isNot()) { + print("NOT EXISTS ("); + } else { print("EXISTS ("); } incrementIndent(); @@ -426,12 +426,12 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { public boolean visit(SQLAggregateExpr x) { print(x.getMethodName()); print("("); - + if (x.getOption() != null) { print(x.getOption().toString()); print(' '); } - + printAndAccept(x.getArguments(), ", "); print(")"); return false; @@ -1123,7 +1123,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { print("*/"); return false; } - + @Override public boolean visit(SQLCreateDatabaseStatement x) { print("CREATE DATABASE "); diff --git a/src/main/java/com/alibaba/druid/stat/JdbcSqlStat.java b/src/main/java/com/alibaba/druid/stat/JdbcSqlStat.java index 2ab364dbd2..15ecc98457 100644 --- a/src/main/java/com/alibaba/druid/stat/JdbcSqlStat.java +++ b/src/main/java/com/alibaba/druid/stat/JdbcSqlStat.java @@ -251,7 +251,9 @@ public final class JdbcSqlStat implements JdbcSqlStatMBean { } for (;;) { long max = updateCountMax.get(); - if (delta <= max) break; + if (delta <= max) { + break; + } if (updateCountMax.compareAndSet(max, delta)) { break; } @@ -307,19 +309,19 @@ public final class JdbcSqlStat implements JdbcSqlStatMBean { public void addReadBytesLength(long length) { this.readBytesLength.addAndGet(length); } - + public long getReaderOpenCount() { return readerOpenCount.get(); } - + public void addReaderOpenCount(int count) { this.readerOpenCount.addAndGet(count); } - + public long getInputStreamOpenCount() { return inputStreamOpenCount.get(); } - + public void addInputStreamOpenCount(int count) { this.inputStreamOpenCount.addAndGet(count); } @@ -366,7 +368,9 @@ public final class JdbcSqlStat implements JdbcSqlStatMBean { this.fetchRowCount.addAndGet(delta); for (;;) { long max = fetchRowCountMax.get(); - if (delta <= max) break; + if (delta <= max) { + break; + } if (fetchRowCountMax.compareAndSet(max, delta)) { break; } diff --git a/src/main/java/com/alibaba/druid/support/console/DruidStat.java b/src/main/java/com/alibaba/druid/support/console/DruidStat.java index 73f207764d..534977b83d 100644 --- a/src/main/java/com/alibaba/druid/support/console/DruidStat.java +++ b/src/main/java/com/alibaba/druid/support/console/DruidStat.java @@ -98,9 +98,7 @@ public class DruidStat { try { vm = VirtualMachine.attach(name); } catch (AttachNotSupportedException x) { - IOException ioe = new IOException(x.getMessage()); - ioe.initCause(x); - throw ioe; + throw new IOException(x.getMessage(), x); } String home = vm.getSystemProperties().getProperty("java.home"); @@ -122,13 +120,9 @@ public class DruidStat { try { vm.loadAgent(agent, "com.sun.management.jmxremote"); } catch (AgentLoadException x) { - IOException ioe = new IOException(x.getMessage()); - ioe.initCause(x); - throw ioe; + throw new IOException(x.getMessage(), x); } catch (AgentInitializationException x) { - IOException ioe = new IOException(x.getMessage()); - ioe.initCause(x); - throw ioe; + throw new IOException(x.getMessage(), x); } // get the connector address diff --git a/src/main/java/com/alibaba/druid/support/console/TableFormatter.java b/src/main/java/com/alibaba/druid/support/console/TableFormatter.java index acbaef1d7d..725c4515bd 100644 --- a/src/main/java/com/alibaba/druid/support/console/TableFormatter.java +++ b/src/main/java/com/alibaba/druid/support/console/TableFormatter.java @@ -69,9 +69,13 @@ public class TableFormatter { } public static String padStr(String old, int length) { - if (old == null ) return ""; + if (old == null ) { + return ""; + } int vlen = displayLen(old); - if (vlen > length) return old; + if (vlen > length) { + return old; + } StringBuffer sb = new StringBuffer(old); for (int i=0; i< length -vlen ; i++) { sb.append(" "); diff --git a/src/main/java/com/alibaba/druid/support/console/TabledDataPrinter.java b/src/main/java/com/alibaba/druid/support/console/TabledDataPrinter.java index 8645e71a51..d316e89064 100644 --- a/src/main/java/com/alibaba/druid/support/console/TabledDataPrinter.java +++ b/src/main/java/com/alibaba/druid/support/console/TabledDataPrinter.java @@ -23,62 +23,45 @@ import com.alibaba.druid.sql.SQLUtils; public class TabledDataPrinter { - private static final int SQL_MAX_LEN = 32; - private static final int MAX_COL = 4; - - private static final String[] sqlRowTitle = new String[] { - "ID", "SQL", "ExecCount", "ExecTime", - "ExecMax","Txn", "Error","Update","FetchRow","Running","Concurrent", - "ExecHisto", "ExecRsHisto","FetchRowHisto","UpdateHisto" }; - - - private static final String[] sqlRowField = new String[] { - "ID", "SQL", "ExecuteCount", "TotalTime", "MaxTimespan", - "InTransactionCount", "ErrorCount", "EffectedRowCount", "FetchRowCount", - "RunningCount","ConcurrentMax","Histogram","ExecuteAndResultHoldTimeHistogram", - "FetchRowCountHistogram","EffectedRowCountHistogram" }; - - private static final String[] sqlColField = new String[] { - "ID", "DataSource", "SQL", "ExecuteCount", "ErrorCount", - "TotalTime", "LastTime", "MaxTimespan", "LastError", "EffectedRowCount", - "FetchRowCount", "MaxTimespanOccurTime", "BatchSizeMax", "BatchSizeTotal", "ConcurrentMax", - "RunningCount", "Name", "File", - "LastErrorMessage", "LastErrorClass", "LastErrorStackTrace", "LastErrorTime", - "DbType", "URL", "InTransactionCount", - "Histogram", "LastSlowParameters", "ResultSetHoldTime", "ExecuteAndResultSetHoldTime", "FetchRowCountHistogram", - "EffectedRowCountHistogram", "ExecuteAndResultHoldTimeHistogram", "EffectedRowCountMax", "FetchRowCountMax", "ClobOpenCount" }; + private static final int SQL_MAX_LEN = 32; + private static final int MAX_COL = 4; + private static final String[] sqlRowTitle = new String[] { "ID", "SQL", "ExecCount", "ExecTime", "ExecMax", "Txn", + "Error", "Update", "FetchRow", "Running", "Concurrent", "ExecHisto", "ExecRsHisto", "FetchRowHisto", + "UpdateHisto" }; - private static final String[] dsRowTitle = new String[] { - "Name", "DbType", - "PoolingCount", "PoolingPeak", "PoolingPeakTime", - "ActiveCount", "ActivePeak", "ActivePeakTime", - "ExecuteCount", "ErrorCount", "CommitCount", "RollbackCount" }; + private static final String[] sqlRowField = new String[] { "ID", "SQL", "ExecuteCount", "TotalTime", "MaxTimespan", + "InTransactionCount", "ErrorCount", "EffectedRowCount", "FetchRowCount", "RunningCount", "ConcurrentMax", + "Histogram", "ExecuteAndResultHoldTimeHistogram", "FetchRowCountHistogram", "EffectedRowCountHistogram" }; - private static final String[] dsRowField = new String[] { - "Name", "DbType", - "PoolingCount", "PoolingPeak", "PoolingPeakTime", - "ActiveCount", "ActivePeak", "ActivePeakTime", - "ExecuteCount", "ErrorCount", "CommitCount", "RollbackCount" }; + private static final String[] sqlColField = new String[] { "ID", "DataSource", "SQL", "ExecuteCount", "ErrorCount", + "TotalTime", "LastTime", "MaxTimespan", "LastError", "EffectedRowCount", "FetchRowCount", + "MaxTimespanOccurTime", "BatchSizeMax", "BatchSizeTotal", "ConcurrentMax", "RunningCount", "Name", "File", + "LastErrorMessage", "LastErrorClass", "LastErrorStackTrace", "LastErrorTime", "DbType", "URL", + "InTransactionCount", "Histogram", "LastSlowParameters", "ResultSetHoldTime", + "ExecuteAndResultSetHoldTime", "FetchRowCountHistogram", "EffectedRowCountHistogram", + "ExecuteAndResultHoldTimeHistogram", "EffectedRowCountMax", "FetchRowCountMax", "ClobOpenCount" }; + private static final String[] dsRowTitle = new String[] { "Name", "DbType", "PoolingCount", "PoolingPeak", + "PoolingPeakTime", "ActiveCount", "ActivePeak", "ActivePeakTime", "ExecuteCount", "ErrorCount", + "CommitCount", "RollbackCount" }; - private static final String[] dsColField = new String[] { - "Identity", "Name", "DbType", "DriverClassName", "URL", "UserName", "FilterClassNames", - "WaitThreadCount", "NotEmptyWaitCount", "NotEmptyWaitMillis", - "PoolingCount", "PoolingPeak", "PoolingPeakTime", - "ActiveCount", "ActivePeak", "ActivePeakTime", - "InitialSize", "MinIdle", "MaxActive", - "QueryTimeout", "TransactionQueryTimeout", "LoginTimeout", "ValidConnectionCheckerClassName", "ExceptionSorterClassName", - "TestOnBorrow", "TestOnReturn", "TestWhileIdle", - "DefaultAutoCommit", "DefaultReadOnly", "DefaultTransactionIsolation", - "LogicConnectCount", "LogicCloseCount", "LogicConnectErrorCount", - "PhysicalConnectCount", "PhysicalCloseCount", "PhysicalConnectErrorCount", - "ExecuteCount", "ErrorCount", "CommitCount", "RollbackCount", - "PSCacheAccessCount", "PSCacheHitCount", "PSCacheMissCount", - "StartTransactionCount", "TransactionHistogram", - "ConnectionHoldTimeHistogram", "RemoveAbandoned", "ClobOpenCount" }; + private static final String[] dsRowField = new String[] { "Name", "DbType", "PoolingCount", "PoolingPeak", + "PoolingPeakTime", "ActiveCount", "ActivePeak", "ActivePeakTime", "ExecuteCount", "ErrorCount", + "CommitCount", "RollbackCount" }; - public static void printActiveConnStack(List> content,Option opt) { + private static final String[] dsColField = new String[] { "Identity", "Name", "DbType", "DriverClassName", "URL", + "UserName", "FilterClassNames", "WaitThreadCount", "NotEmptyWaitCount", "NotEmptyWaitMillis", + "PoolingCount", "PoolingPeak", "PoolingPeakTime", "ActiveCount", "ActivePeak", "ActivePeakTime", + "InitialSize", "MinIdle", "MaxActive", "QueryTimeout", "TransactionQueryTimeout", "LoginTimeout", + "ValidConnectionCheckerClassName", "ExceptionSorterClassName", "TestOnBorrow", "TestOnReturn", + "TestWhileIdle", "DefaultAutoCommit", "DefaultReadOnly", "DefaultTransactionIsolation", + "LogicConnectCount", "LogicCloseCount", "LogicConnectErrorCount", "PhysicalConnectCount", + "PhysicalCloseCount", "PhysicalConnectErrorCount", "ExecuteCount", "ErrorCount", "CommitCount", + "RollbackCount", "PSCacheAccessCount", "PSCacheHitCount", "PSCacheMissCount", "StartTransactionCount", + "TransactionHistogram", "ConnectionHoldTimeHistogram", "RemoveAbandoned", "ClobOpenCount" }; + + public static void printActiveConnStack(List> content, Option opt) { for (List stack : content) { for (String line : stack) { System.out.println(line); @@ -87,7 +70,7 @@ public class TabledDataPrinter { } } - public static void printDataSourceData(List> content,Option opt) { + public static void printDataSourceData(List> content, Option opt) { if (opt.getStyle() == Option.PrintStyle.HORIZONTAL) { System.out.println(getFormattedOutput(content, dsRowTitle, dsRowField)); } else { @@ -96,23 +79,22 @@ public class TabledDataPrinter { } public static void printSqlData(List> content, Option opt) { - if (opt.getId() != -1) { - List> matchedContent = new ArrayList>(); - for (Map sqlStat : content) { - Integer idStr = (Integer)sqlStat.get("ID"); - if (idStr.intValue() == opt.getId()) { - matchedContent.add(sqlStat); - String dbType = (String) sqlStat.get("DbType"); - String sql = (String) sqlStat.get("SQL"); - System.out.println(SQLUtils.format(sql, dbType)); - System.out.println("===============================\n"); - break; - } - } - content = matchedContent; + if (opt.getId() != -1) { + List> matchedContent = new ArrayList>(); + for (Map sqlStat : content) { + Integer idStr = (Integer) sqlStat.get("ID"); + if (idStr.intValue() == opt.getId()) { + matchedContent.add(sqlStat); + String dbType = (String) sqlStat.get("DbType"); + String sql = (String) sqlStat.get("SQL"); + System.out.println(SQLUtils.format(sql, dbType)); + System.out.println("===============================\n"); + break; + } + } + content = matchedContent; - - } + } if (opt.getStyle() == Option.PrintStyle.HORIZONTAL) { System.out.println(getFormattedOutput(content, sqlRowTitle, sqlRowField)); } else { @@ -120,17 +102,16 @@ public class TabledDataPrinter { } } - public static String getFormattedOutput(List> content, - String[] title , String[] rowField) { + public static String getFormattedOutput(List> content, String[] title, String[] rowField) { List printContents = new ArrayList(); printContents.add(title); - + for (Map sqlStat : content) { String[] row = new String[rowField.length]; for (int i = 0; i < rowField.length; ++i) { Object value = sqlStat.get(rowField[i]); - row[i] = handleAndConvert(value,rowField[i]); + row[i] = handleAndConvert(value, rowField[i]); } printContents.add(row); } @@ -138,19 +119,18 @@ public class TabledDataPrinter { return formattedStr; } - public static String getVerticalFormattedOutput(List> content, String[] titleFields) { List printContents = new ArrayList(); - int maxCol = content.size() > MAX_COL ? MAX_COL: content.size(); - + int maxCol = content.size() > MAX_COL ? MAX_COL : content.size(); + for (int i = 0; i < titleFields.length; ++i) { - String[] row = new String[maxCol+1]; + String[] row = new String[maxCol + 1]; row[0] = titleFields[i]; - for (int j=0; j< maxCol ; j++) { - Map sqlStat = content.get(j); + for (int j = 0; j < maxCol; j++) { + Map sqlStat = content.get(j); Object value = sqlStat.get(titleFields[i]); - row[j+1] = handleAndConvert(value, titleFields[i]); + row[j + 1] = handleAndConvert(value, titleFields[i]); } printContents.add(row); } @@ -161,11 +141,11 @@ public class TabledDataPrinter { public static String handleAndConvert(Object value, String fieldName) { if (value == null) value = ""; if (fieldName.equals("SQL")) { - String sql = (String)value; + String sql = (String) value; sql = sql.replace("\n", " "); sql = sql.replace("\t", " "); if (sql.length() > SQL_MAX_LEN) { - sql = sql.substring(0,SQL_MAX_LEN-3) + "..."; + sql = sql.substring(0, SQL_MAX_LEN - 3) + "..."; } value = sql; } diff --git a/src/main/java/com/alibaba/druid/util/Base64.java b/src/main/java/com/alibaba/druid/util/Base64.java index 9da6277189..185c6d475f 100644 --- a/src/main/java/com/alibaba/druid/util/Base64.java +++ b/src/main/java/com/alibaba/druid/util/Base64.java @@ -124,7 +124,9 @@ public class Base64 { byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt); int sLen = s.length(); int numGroups = sLen / 4; - if (4 * numGroups != sLen) throw new IllegalArgumentException("String length must be a multiple of four."); + if (4 * numGroups != sLen) { + throw new IllegalArgumentException("String length must be a multiple of four."); + } int missingBytesInLastGroup = 0; int numFullGroups = numGroups; if (sLen != 0) { @@ -132,7 +134,9 @@ public class Base64 { missingBytesInLastGroup++; numFullGroups--; } - if (s.charAt(sLen - 2) == '=') missingBytesInLastGroup++; + if (s.charAt(sLen - 2) == '=') { + missingBytesInLastGroup++; + } } byte[] result = new byte[3 * numGroups - missingBytesInLastGroup]; @@ -172,7 +176,9 @@ public class Base64 { */ private static int base64toInt(char c, byte[] alphaToInt) { int result = alphaToInt[c]; - if (result < 0) throw new IllegalArgumentException("Illegal character " + c); + if (result < 0) { + throw new IllegalArgumentException("Illegal character " + c); + } return result; } diff --git a/src/main/java/com/alibaba/druid/util/LazyCompositeData.java b/src/main/java/com/alibaba/druid/util/LazyCompositeData.java index 2dfc4b89bb..8ff6b0c517 100644 --- a/src/main/java/com/alibaba/druid/util/LazyCompositeData.java +++ b/src/main/java/com/alibaba/druid/util/LazyCompositeData.java @@ -147,7 +147,9 @@ public abstract class LazyCompositeData implements CompositeData, Serializable { Set allItems = type1.keySet(); // Check all items in the type1 exist in type2 - if (!type2.keySet().containsAll(allItems)) return false; + if (!type2.keySet().containsAll(allItems)) { + return false; + } for (Iterator iter = allItems.iterator(); iter.hasNext();) { String item = (String) iter.next(); @@ -183,7 +185,9 @@ public abstract class LazyCompositeData implements CompositeData, Serializable { List list2 = type2.getIndexNames(); // check if the list of index names are the same - if (!list1.equals(list2)) return false; + if (!list1.equals(list2)) { + return false; + } return isTypeMatched(type1.getRowType(), type2.getRowType()); } diff --git a/src/main/java/com/alibaba/druid/util/MapComparator.java b/src/main/java/com/alibaba/druid/util/MapComparator.java index 3ea301c655..6afd71ba43 100644 --- a/src/main/java/com/alibaba/druid/util/MapComparator.java +++ b/src/main/java/com/alibaba/druid/util/MapComparator.java @@ -50,7 +50,9 @@ public class MapComparator implements Compar public int compare(Map o1, Map o2) { int result = compare_0(o1, o2); - if (isDesc) result = -result; + if (isDesc) { + result = -result; + } return result; } @@ -61,7 +63,9 @@ public class MapComparator implements Compar if (keyStr.matches(".+\\[[0-9]+\\]")) { Object value = map.get(keyStr.substring(0, keyStr.indexOf("["))); - if (value == null) return null; + if (value == null) { + return null; + } Integer index = StringUtils.subStringToInteger(keyStr, "[", "]"); if (value.getClass().isArray() && Array.getLength(value) >= index) { diff --git a/src/main/java/com/alibaba/druid/util/ThreadLocalRandom.java b/src/main/java/com/alibaba/druid/util/ThreadLocalRandom.java index aab64dc5bc..1859ed23c0 100644 --- a/src/main/java/com/alibaba/druid/util/ThreadLocalRandom.java +++ b/src/main/java/com/alibaba/druid/util/ThreadLocalRandom.java @@ -15,81 +15,71 @@ */ package com.alibaba.druid.util; - - import java.util.Random; /** - * A random number generator isolated to the current thread. Like the - * global {@link java.util.Random} generator used by the {@link - * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized - * with an internally generated seed that may not otherwise be - * modified. When applicable, use of {@code ThreadLocalRandom} rather - * than shared {@code Random} objects in concurrent programs will - * typically encounter much less overhead and contention. Use of - * {@code ThreadLocalRandom} is particularly appropriate when multiple - * tasks (for example, each a {@link ForkJoinTask}) use random numbers - * in parallel in thread pools. - * - *

Usages of this class should typically be of the form: - * {@code ThreadLocalRandom.current().nextX(...)} (where - * {@code X} is {@code Int}, {@code Long}, etc). - * When all usages are of this form, it is never possible to - * accidently share a {@code ThreadLocalRandom} across multiple threads. - * - *

This class also provides additional commonly used bounded random - * generation methods. - * + * A random number generator isolated to the current thread. Like the global {@link java.util.Random} generator used by + * the {@link java.lang.Math} class, a {@code ThreadLocalRandom} is initialized with an internally generated seed that + * may not otherwise be modified. When applicable, use of {@code ThreadLocalRandom} rather than shared {@code Random} + * objects in concurrent programs will typically encounter much less overhead and contention. Use of + * {@code ThreadLocalRandom} is particularly appropriate when multiple tasks (for example, each a {@link ForkJoinTask}) + * use random numbers in parallel in thread pools. + *

+ * Usages of this class should typically be of the form: {@code ThreadLocalRandom.current().nextX(...)} (where {@code X} + * is {@code Int}, {@code Long}, etc). When all usages are of this form, it is never possible to accidently share a + * {@code ThreadLocalRandom} across multiple threads. + *

+ * This class also provides additional commonly used bounded random generation methods. + * * @since 1.7 * @author Doug Lea */ public class ThreadLocalRandom extends Random { + // same constants as Random, but must be redeclared because private - private static final long multiplier = 0x5DEECE66DL; - private static final long addend = 0xBL; - private static final long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; /** * The random seed. We can't use super.seed. */ - private long rnd; + private long rnd; /** - * Initialization flag to permit calls to setSeed to succeed only - * while executing the Random constructor. We can't allow others - * since it would cause setting seed in one part of a program to - * unintentionally impact other usages by the thread. + * Initialization flag to permit calls to setSeed to succeed only while executing the Random constructor. We can't + * allow others since it would cause setting seed in one part of a program to unintentionally impact other usages by + * the thread. */ - boolean initialized; + boolean initialized; // Padding to help avoid memory contention among seed updates in // different TLRs in the common case that they are located near // each other. @SuppressWarnings("unused") - private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; /** * The actual ThreadLocal */ - private static final ThreadLocal localRandom = - new ThreadLocal() { - protected ThreadLocalRandom initialValue() { - return new ThreadLocalRandom(); - } - }; + private static final ThreadLocal localRandom = new ThreadLocal() { + protected ThreadLocalRandom initialValue() { + return new ThreadLocalRandom(); + } + }; /** * Constructor called only by localRandom.initialValue. */ - ThreadLocalRandom() { + ThreadLocalRandom(){ super(); initialized = true; } /** * Returns the current thread's {@code ThreadLocalRandom}. - * + * * @return the current thread's {@code ThreadLocalRandom} */ public static ThreadLocalRandom current() { @@ -97,9 +87,8 @@ public class ThreadLocalRandom extends Random { } /** - * Throws {@code UnsupportedOperationException}. Setting seeds in - * this generator is not supported. - * + * Throws {@code UnsupportedOperationException}. Setting seeds in this generator is not supported. + * * @throws UnsupportedOperationException always */ public void setSeed(long seed) { @@ -111,17 +100,16 @@ public class ThreadLocalRandom extends Random { protected int next(int bits) { rnd = (rnd * multiplier + addend) & mask; - return (int) (rnd >>> (48-bits)); + return (int) (rnd >>> (48 - bits)); } /** - * Returns a pseudorandom, uniformly distributed value between the - * given least value (inclusive) and bound (exclusive). - * + * Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound + * (exclusive). + * * @param least the least value returned * @param bound the upper bound (exclusive) - * @throws IllegalArgumentException if least greater than or equal - * to bound + * @throws IllegalArgumentException if least greater than or equal to bound * @return the next value */ public int nextInt(int least, int bound) { @@ -132,11 +120,9 @@ public class ThreadLocalRandom extends Random { } /** - * Returns a pseudorandom, uniformly distributed value - * between 0 (inclusive) and the specified value (exclusive). - * - * @param n the bound on the random number to be returned. Must be - * positive. + * Returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive). + * + * @param n the bound on the random number to be returned. Must be positive. * @return the next value * @throws IllegalArgumentException if n is not positive */ @@ -154,22 +140,22 @@ public class ThreadLocalRandom extends Random { int bits = next(2); long half = n >>> 1; long nextn = ((bits & 2) == 0) ? half : n - half; - if ((bits & 1) == 0) + if ((bits & 1) == 0) { offset += n - nextn; + } n = nextn; } return offset + nextInt((int) n); } /** - * Returns a pseudorandom, uniformly distributed value between the - * given least value (inclusive) and bound (exclusive). - * + * Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound + * (exclusive). + * * @param least the least value returned * @param bound the upper bound (exclusive) * @return the next value - * @throws IllegalArgumentException if least greater than or equal - * to bound + * @throws IllegalArgumentException if least greater than or equal to bound */ public long nextLong(long least, long bound) { if (least >= bound) { @@ -179,11 +165,10 @@ public class ThreadLocalRandom extends Random { } /** - * Returns a pseudorandom, uniformly distributed {@code double} value - * between 0 (inclusive) and the specified value (exclusive). - * - * @param n the bound on the random number to be returned. Must be - * positive. + * Returns a pseudorandom, uniformly distributed {@code double} value between 0 (inclusive) and the specified value + * (exclusive). + * + * @param n the bound on the random number to be returned. Must be positive. * @return the next value * @throws IllegalArgumentException if n is not positive */ @@ -195,14 +180,13 @@ public class ThreadLocalRandom extends Random { } /** - * Returns a pseudorandom, uniformly distributed value between the - * given least value (inclusive) and bound (exclusive). - * + * Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound + * (exclusive). + * * @param least the least value returned * @param bound the upper bound (exclusive) * @return the next value - * @throws IllegalArgumentException if least greater than or equal - * to bound + * @throws IllegalArgumentException if least greater than or equal to bound */ public double nextDouble(double least, double bound) { if (least >= bound) {