#1738 - Refactor add final, Object.equals, Integer.compare

This commit is contained in:
rob bygrave
2019-06-29 00:23:12 +12:00
parent 8bfae9deef
commit 7fa5e2aa8c
52 changed files with 102 additions and 120 deletions
+2 -2
View File
@@ -69,8 +69,8 @@ public enum CacheMode {
*/
GET(true, false);
private boolean get;
private boolean put;
private final boolean get;
private final boolean put;
CacheMode(boolean get, boolean put) {
this.get = get;
@@ -1,6 +1,7 @@
package io.ebean.bean;
import java.io.Serializable;
import java.util.Objects;
/**
* Identifies a unique node of an object graph.
@@ -85,8 +86,7 @@ public final class ObjectGraphNode implements Serializable {
}
ObjectGraphNode e = (ObjectGraphNode) obj;
//noinspection StringEquality
return ((e.path == path) || (e.path != null && e.path.equals(path)))
return (Objects.equals(e.path, path))
&& e.originQueryPoint.equals(originQueryPoint);
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ public enum ServerCacheType {
*/
QUERY("_Q");
private String code;
private final String code;
ServerCacheType(String code) {
this.code = code;
@@ -35,9 +35,9 @@ public enum TenantMode {
* (that holds configuration e.g.)
*/
DB_WITH_MASTER(true, true);
boolean dynamicDataSource;
boolean ddlEnabled;
final boolean dynamicDataSource;
final boolean ddlEnabled;
TenantMode(boolean dynamicDataSource, boolean ddlEnabled) {
this.dynamicDataSource = dynamicDataSource;
@@ -50,12 +50,12 @@ public enum TenantMode {
public boolean isDynamicDataSource() {
return dynamicDataSource;
}
/**
* Returns true, if DDL is enabled.
*/
public boolean isDdlEnabled() {
return ddlEnabled;
}
}
@@ -27,15 +27,13 @@ public class DbDefaultValue {
* The key for the NOW / current timestamp.
*/
public static final String NOW = "now";
/**
* The 'null' literal.
*/
public static final String NULL = "null";
protected Map<String, String> map = new LinkedHashMap<>();
protected final Map<String, String> map = new LinkedHashMap<>();
/**
* Set the DB now function.
@@ -82,10 +80,9 @@ public class DbDefaultValue {
return val != null ? val : dbDefaultLiteral;
}
/**
* This method checks & convert the {@link DbDefault#value()} to a valid SQL literal.
*
*
* This is mainly to quote string literals and verify integer/dates for correctness.
* <p>
* Note: There are some special cases:
@@ -98,24 +95,24 @@ public class DbDefaultValue {
* If you need really the String "null", you have to specify <code>@DbDefault("'null'")</code>
* which gives you the <code>default 'null'</code> statement.</li>
* <li>Any statement, that begins and ends with single quote will not be checked or get quoted again.</li>
* <li>A statement that begins with "$RAW:", e.g <code>@DbDefault("$RAW:N'SANDNES'")</code> will lead to
* <li>A statement that begins with "$RAW:", e.g <code>@DbDefault("$RAW:N'SANDNES'")</code> will lead to
* a <code>default N'SANDNES'</code> in DDL. Note that this is platform specific!</li>
* </ul>
*/
public static String toSqlLiteral(String defaultValue, Class<?> propertyType, int sqlType) {
if (propertyType == null
|| defaultValue == null
|| defaultValue == null
|| NULL.equals(defaultValue)
|| (defaultValue.startsWith("'") && defaultValue.endsWith("'"))
|| (defaultValue.startsWith("$RAW:"))) {
|| (defaultValue.startsWith("$RAW:"))) {
return defaultValue;
}
if (Boolean.class.isAssignableFrom(propertyType) || Boolean.TYPE.isAssignableFrom(propertyType)) {
return toBooleanLiteral(defaultValue);
}
if (Number.class.isAssignableFrom(propertyType)
if (Number.class.isAssignableFrom(propertyType)
|| Byte.TYPE.equals(propertyType)
|| Short.TYPE.equals(propertyType)
|| Integer.TYPE.equals(propertyType)
@@ -126,7 +123,7 @@ public class DbDefaultValue {
Double.valueOf(defaultValue); // verify if it is a number
return defaultValue;
}
// check if it is a date/time - in all other cases return quoted defaultValue
switch (sqlType) {
// date
@@ -155,7 +152,7 @@ public class DbDefaultValue {
}
throw new IllegalArgumentException("'" + value + "' is not a valid value for boolean");
}
/**
* This adds single qoutes around the <code>value</code> and doubles single quotes.
* "User's home" will return "'User''s home'"
@@ -175,7 +172,7 @@ public class DbDefaultValue {
return sb.toString();
}
private static String toDateLiteral(String value) {
if (NOW.equals(value)) {
return value; // this will get translated later
@@ -191,7 +188,7 @@ public class DbDefaultValue {
DatatypeConverter.parseTime(value); // verify
return toTextLiteral(value);
}
private static String toDateTimeLiteral(String value) {
if (NOW.equals(value)) {
return value; // this will get translated later
@@ -11,12 +11,12 @@ class DbPlatformTypeLookup {
/**
* A map to lookup the type by name.
*/
private Map<String, DbType> nameLookup = new HashMap<>();
private final Map<String, DbType> nameLookup = new HashMap<>();
/**
* A map to lookup the type by JDBC int value.
*/
private Map<Integer, DbType> idLookup = new HashMap<>();
private final Map<Integer, DbType> idLookup = new HashMap<>();
DbPlatformTypeLookup() {
addAll();
@@ -23,7 +23,7 @@ public class DbPlatformTypeMapping {
}
}
private static DbPlatformTypeLookup lookup = new DbPlatformTypeLookup();
private static final DbPlatformTypeLookup lookup = new DbPlatformTypeLookup();
private static final DbPlatformType BOOLEAN_LOGICAL = new BooleanLogicalType();
@@ -8,7 +8,7 @@ import java.util.Map;
*/
public class SqlErrorCodes {
private Map<String,DataErrorType> map = new HashMap<>();
private final Map<String,DataErrorType> map = new HashMap<>();
/**
* Map the codes to AcquireLockException.
@@ -10,7 +10,7 @@ import java.util.Set;
*/
public class QueryPlanRequest {
private List<MetaQueryPlan> plans = new ArrayList<>();
private final List<MetaQueryPlan> plans = new ArrayList<>();
private Connection connection;
@@ -10,7 +10,7 @@ import java.util.ServiceLoader;
*/
class MetricServiceProvider {
private static MetricFactory metricFactory = init();
private static final MetricFactory metricFactory = init();
private static MetricFactory init() {
@@ -8,7 +8,7 @@ import java.util.List;
*/
public class BeanCacheResult<T> {
private List<Entry<T>> list = new ArrayList<>();
private final List<Entry<T>> list = new ArrayList<>();
/**
* Add an entry.
@@ -12,8 +12,8 @@ import java.util.Map;
*/
public class NaturalKeyEntry {
private Map<String,Object> map = new HashMap<>();
private Object key;
private final Map<String,Object> map = new HashMap<>();
private final Object key;
private Object inValue;
/**
@@ -17,7 +17,7 @@ public class ScopedTransaction extends SpiTransactionProxy {
/**
* Stack of 'nested' transactions.
*/
private ArrayStack<ScopeTrans> stack = new ArrayStack<>();
private final ArrayStack<ScopeTrans> stack = new ArrayStack<>();
private ScopeTrans current;
@@ -106,9 +106,9 @@ public interface SpiQuery<T> extends Query<T>, TxnProfileEventCodes {
*/
UPDATE(FIND_UPDATE, "update", true);
private boolean update;
private String profileEventId;
private String label;
private final boolean update;
private final String profileEventId;
private final String label;
Type(String profileEventId, String label) {
this(profileEventId, label, false);
@@ -62,14 +62,14 @@ public class BaseTableDdl implements TableDdl {
* Used to check that indexes on foreign keys should be skipped as a unique index on the columns
* already exists.
*/
protected IndexSet indexSet = new IndexSet();
protected final IndexSet indexSet = new IndexSet();
/**
* Used when unique constraints specifically for OneToOne can't be created normally (MsSqlServer).
*/
protected List<Column> externalUnique = new ArrayList<>();
protected final List<Column> externalUnique = new ArrayList<>();
protected List<UniqueConstraint> externalCompoundUnique = new ArrayList<>();
protected final List<UniqueConstraint> externalCompoundUnique = new ArrayList<>();
// counters used when constraint names are truncated due to maximum length
// and these counters are used to keep the constraint name unique
@@ -82,9 +82,9 @@ public class BaseTableDdl implements TableDdl {
* Base tables that have associated history tables that need their triggers/functions regenerated as
* columns have been added, removed, included or excluded.
*/
protected Map<String, HistoryTableUpdate> regenerateHistoryTriggers = new LinkedHashMap<>();
protected final Map<String, HistoryTableUpdate> regenerateHistoryTriggers = new LinkedHashMap<>();
private boolean strictMode;
private final boolean strictMode;
private final HistorySupport historySupport;
@@ -8,6 +8,7 @@ import io.ebeaninternal.dbmigration.migration.DdlScript;
import io.ebeaninternal.server.deploy.DbMigrationInfo;
import java.util.List;
import java.util.Objects;
/**
* A column in the logical model.
@@ -309,7 +310,7 @@ public class MColumn {
}
protected static boolean different(String val1, String val2) {
return (val1 == null) ? val2 != null : !val1.equals(val2);
return !Objects.equals(val1, val2);
}
private boolean hasValue(String val) {
@@ -181,7 +181,7 @@ public class DJsonService implements SpiJsonService {
if (modifyAware) {
return ((ModifyAwareList<T>) list).asSet();
} else {
return new LinkedHashSet<T>(list);
return new LinkedHashSet<>(list);
}
}
@@ -11,7 +11,7 @@ import java.util.List;
*/
public class AutoTuneCollection {
List<Entry> entries = new ArrayList<>();
final List<Entry> entries = new ArrayList<>();
public Entry add(ObjectGraphOrigin origin, OrmQueryDetail detail, String sourceQuery) {
Entry entry = new Entry(origin, detail, sourceQuery);
@@ -91,17 +91,13 @@ public class DefaultBackgroundExecutor implements SpiBackgroundExecutor {
if (map == null) {
return schedulePool.schedule(c, delay, unit);
} else {
return schedulePool.schedule(new Callable<V>() {
@Override
public V call() throws Exception {
MDC.setContextMap(map);
try {
return c.call();
} finally {
MDC.clear();
}
return schedulePool.schedule(() -> {
MDC.setContextMap(map);
try {
return c.call();
} finally {
MDC.clear();
}
}, delay, unit);
}
}
@@ -160,7 +160,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer {
/**
* Clock to use for WhenModified and WhenCreated.
*/
private ClockService clockService;
private final ClockService clockService;
private final CallStackFactory callStackFactory;
@@ -24,7 +24,7 @@ public abstract class PersistRequest extends BeanRequest implements BatchPostExe
DELETE_PERMANENT(EVT_DELETE_PERMANENT),
UPDATESQL(EVT_UPDATESQL),
CALLABLESQL(EVT_CALLABLESQL);
String profileEventId;
final String profileEventId;
Type(String profileEventId) {
this.profileEventId = profileEventId;
@@ -85,7 +85,7 @@ public final class PersistRequestBean<T> extends PersistRequest implements BeanP
private DocStoreMode docStoreMode;
private ConcurrencyMode concurrencyMode;
private final ConcurrencyMode concurrencyMode;
/**
* The unique id used for logging summary.
@@ -29,7 +29,7 @@ public final class PersistRequestUpdateSql extends PersistRequest {
private boolean addBatch;
private boolean forceNoBatch;
private final boolean forceNoBatch;
private boolean batchThisRequest;
@@ -79,7 +79,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> implements ST
/**
* Descriptor for the 'target' when the property maps to an element collection.
*/
BeanDescriptor<T> elementDescriptor;
final BeanDescriptor<T> elementDescriptor;
/**
* Order by used when fetch joining the associated many.
@@ -185,7 +185,7 @@ public class ChainedBeanPersistController implements BeanPersistController {
int i1 = o1.getExecutionOrder();
int i2 = o2.getExecutionOrder();
return (i1 < i2 ? -1 : (i1 == i2 ? 0 : 1));
return Integer.compare(i1, i2);
}
}
@@ -89,10 +89,7 @@ public class ChainedBeanQueryAdapter implements BeanQueryAdapter {
@Override
public int compare(BeanQueryAdapter o1, BeanQueryAdapter o2) {
int i1 = o1.getExecutionOrder();
int i2 = o2.getExecutionOrder();
return (i1 < i2 ? -1 : (i1 == i2 ? 0 : 1));
return Integer.compare(o1.getExecutionOrder(), o2.getExecutionOrder());
}
}
@@ -4,7 +4,7 @@ import io.ebeaninternal.api.SpiCacheRegion;
class DCacheRegionNone implements SpiCacheRegion {
static SpiCacheRegion INSTANCE = new DCacheRegionNone();
static final SpiCacheRegion INSTANCE = new DCacheRegionNone();
@Override
public String getName() {
@@ -16,7 +16,7 @@ class DetermineAggPath {
// a top level aggregation (so here we need to exclude Id property)
return null;
}
return path.getManyPath(0, desc);
return path.getManyPath(desc);
}
static Path paths(String aggregation) {
@@ -82,9 +82,9 @@ class DetermineAggPath {
}
}
String getManyPath(int pos, DeployBeanDescriptor<?> desc) {
String getManyPath(DeployBeanDescriptor<?> desc) {
int pos = 0;
while (true) {
String path = paths[pos];
DeployBeanProperty details = desc.getBeanProperty(path);
if (details instanceof DeployBeanPropertyAssocMany<?>) {
@@ -11,7 +11,7 @@ class ElementEntityBean implements EntityBean {
private Object[] data;
private EntityBeanIntercept intercept;
private final EntityBeanIntercept intercept;
ElementEntityBean(String[] properties) {
this.properties = properties;
@@ -15,7 +15,7 @@ class ElementHelpList implements ElementHelp {
private static class Collector implements ElementCollector {
private List<Object> list = new ArrayList<>();
private final List<Object> list = new ArrayList<>();
@Override
public void addElement(Object element) {
@@ -15,7 +15,7 @@ class ElementHelpMap implements ElementHelp {
private static class Collector implements ElementCollector {
private Map<Object, Object> map = new LinkedHashMap<>();
private final Map<Object, Object> map = new LinkedHashMap<>();
@Override
public void addElement(Object element) {
@@ -15,7 +15,7 @@ class ElementHelpSet implements ElementHelp {
private static class Collector implements ElementCollector {
private Set<Object> set = new LinkedHashSet<>();
private final Set<Object> set = new LinkedHashSet<>();
@Override
public void addElement(Object element) {
@@ -100,7 +100,7 @@ public final class ImportedIdSimple implements ImportedId, Comparable<ImportedId
@Override
public int compareTo(ImportedIdSimple other) {
return (position < other.position ? -1 : (position == other.position ? 0 : 1));
return Integer.compare(position, other.position);
}
@Override
@@ -8,7 +8,7 @@ import java.io.IOException;
class CaseInsensitiveEqualExpression extends AbstractValueExpression {
private boolean not;
private final boolean not;
CaseInsensitiveEqualExpression(String propertyName, Object value, boolean not) {
super(propertyName, value);
@@ -60,7 +60,7 @@ public class DefaultExpressionList<T> implements SpiExpressionList<T> {
private final ExpressionList<T> parentExprList;
protected ExpressionFactory expr;
protected final ExpressionFactory expr;
String allDocNestedPath;
@@ -4,6 +4,7 @@ import io.ebeaninternal.api.SpiExpression;
import io.ebeaninternal.api.SpiExpressionRequest;
import java.io.IOException;
import java.util.Objects;
/**
* Generally speaking tests the value at a given path in the JSON document.
@@ -91,8 +92,8 @@ class JsonPathExpression extends AbstractExpression {
@Override
public boolean isSameByBind(SpiExpression other) {
JsonPathExpression that = (JsonPathExpression) other;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
return upperValue != null ? upperValue.equals(that.upperValue) : that.upperValue == null;
if (!Objects.equals(value, that.value)) return false;
return Objects.equals(upperValue, that.upperValue);
}
@Override
@@ -5,7 +5,7 @@ import java.util.Map;
class OperatorMapping {
Map<String, EqlOperator> map = new HashMap<>();
final Map<String, EqlOperator> map = new HashMap<>();
public OperatorMapping() {
map.put("eq", EqlOperator.EQ);
@@ -19,13 +19,7 @@ public class BatchDepthComparator implements Comparator<BatchedBeanHolder>, Seri
@Override
public int compare(BatchedBeanHolder b1, BatchedBeanHolder b2) {
if (b1.getOrder() < b2.getOrder()) {
return -1;
}
if (b1.getOrder() == b2.getOrder()) {
return 0;
}
return 1;
return Integer.compare(b1.getOrder(), b2.getOrder());
}
}
@@ -18,9 +18,9 @@ public enum DeleteMode {
*/
HARD(PersistRequest.Type.DELETE_PERMANENT, true);
private boolean hard;
private final boolean hard;
private PersistRequest.Type persistType;
private final PersistRequest.Type persistType;
DeleteMode(PersistRequest.Type persistType, boolean hard) {
this.persistType = persistType;
@@ -8,7 +8,7 @@ import java.util.Collection;
*/
public class MultiValueWrapper {
private final Collection<?> values;
private Class<?> type;
private final Class<?> type;
public MultiValueWrapper(Collection<?> values, Class<?> type) {
this.values = values;
@@ -36,7 +36,7 @@ public class SaveManyBeans extends SaveManyBase {
private final DeleteMode deleteMode;
private Collection<?> collection;
private DefaultPersister persister;
private final DefaultPersister persister;
private boolean deleteMissing;
private int sortOrder;
@@ -9,7 +9,7 @@ import java.util.List;
*/
public class TimedProfileLocationRegistry {
private static final List<TimedProfileLocation> list = Collections.synchronizedList(new ArrayList<TimedProfileLocation>());
private static final List<TimedProfileLocation> list = Collections.synchronizedList(new ArrayList<>());
/**
* Register the timed profile location instance.
@@ -183,7 +183,7 @@ public class CQuery<T> implements DbReadContext, CancelableQuery, SpiProfileTran
/**
* Flag set when read auditing.
*/
private boolean audit;
private final boolean audit;
/**
* Flag set when findIterate is being read audited meaning we log in batches.
@@ -4,13 +4,13 @@ import io.ebean.annotation.Platform;
public final class PlatformQueryPlan {
private static QueryPlanLogger explainLogger = new QueryPlanLoggerExplain();
private static final QueryPlanLogger explainLogger = new QueryPlanLoggerExplain();
private static QueryPlanLogger postgresLogger = new QueryPlanLoggerPostgres();
private static final QueryPlanLogger postgresLogger = new QueryPlanLoggerPostgres();
private static QueryPlanLogger sqlServerLogger = new QueryPlanLoggerSqlServer();
private static final QueryPlanLogger sqlServerLogger = new QueryPlanLoggerSqlServer();
private static QueryPlanLogger oracleLogger = new QueryPlanLoggerOracle();
private static final QueryPlanLogger oracleLogger = new QueryPlanLoggerOracle();
/**
* Returns the logger to log query plans for the given platform.
@@ -2,6 +2,8 @@ package io.ebeaninternal.server.query;
import io.ebeaninternal.api.CQueryPlanKey;
import java.util.Objects;
/**
* QueryPlanKey for RawSql queries.
*/
@@ -49,7 +51,7 @@ class RawSqlQueryPlanKey implements CQueryPlanKey {
if (rawSql != that.rawSql) return false;
if (rowNumberIncluded != that.rowNumberIncluded) return false;
if (!sql.equals(that.sql)) return false;
return logWhereSql != null ? logWhereSql.equals(that.logWhereSql) : that.logWhereSql == null;
return Objects.equals(logWhereSql, that.logWhereSql);
}
@Override
@@ -3,6 +3,8 @@ package io.ebeaninternal.server.querydefn;
import io.ebeaninternal.api.CQueryPlanKey;
import io.ebeaninternal.server.rawsql.SpiRawSql;
import java.util.Objects;
/**
* Query plan key for ORM queries.
*/
@@ -55,6 +57,6 @@ class OrmQueryPlanKey implements CQueryPlanKey {
if (maxRows != that.maxRows) return false;
if (firstRow != that.firstRow) return false;
if (!description.equals(that.description)) return false;
return rawSqlKey != null ? rawSqlKey.equals(that.rawSqlKey) : that.rawSqlKey == null;
return Objects.equals(rawSqlKey, that.rawSqlKey);
}
}
@@ -12,7 +12,7 @@ import java.util.List;
*/
class OrmQueryPropertiesParser {
private static Response EMPTY = new Response();
private static final Response EMPTY = new Response();
/**
* Immutable response of the parsed properties and options.
@@ -116,7 +116,7 @@ public class OrmUpdateProperties {
/**
* The set properties/expressions and their bind values.
*/
private LinkedHashMap<String, Value> values = new LinkedHashMap<>();
private final LinkedHashMap<String, Value> values = new LinkedHashMap<>();
/**
* Normal set property.
@@ -55,7 +55,7 @@ class DRawSqlParser {
private Sql parse() {
parseSqlFindKeywords(true);
parseSqlFindKeywords();
whereExprPos = findWhereExprPosition();
havingExprPos = findHavingExprPosition();
@@ -165,7 +165,7 @@ class DRawSqlParser {
}
}
private void parseSqlFindKeywords(boolean allKeywords) {
private void parseSqlFindKeywords() {
selectPos = textParser.findWordLower("select");
if (selectPos == -1) {
@@ -184,10 +184,6 @@ class DRawSqlParser {
throw new RuntimeException(msg + sql);
}
if (!allKeywords) {
return;
}
wherePos = textParser.findWordLower("where");
if (wherePos == -1) {
groupByPos = textParser.findWordLower("group", fromPos + 5);
@@ -11,6 +11,7 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Internal service API for Raw Sql.
@@ -432,8 +433,8 @@ public interface SpiRawSql extends RawSql {
Column that = (Column) o;
if (indexPos != that.indexPos) return false;
if (!dbColumn.equals(that.dbColumn)) return false;
if (dbAlias != null ? !dbAlias.equals(that.dbAlias) : that.dbAlias != null) return false;
return propertyName != null ? propertyName.equals(that.propertyName) : that.propertyName == null;
if (!Objects.equals(dbAlias, that.dbAlias)) return false;
return Objects.equals(propertyName, that.propertyName);
}
@Override
@@ -21,7 +21,7 @@ public class TableModState implements QueryCacheEntryValidate, ServerCacheNotify
private static final Logger log = LoggerFactory.getLogger("io.ebean.cache.TABLEMOD");
private Map<String, Long> tableModStamp = new ConcurrentHashMap<>();
private final Map<String, Long> tableModStamp = new ConcurrentHashMap<>();
public TableModState() {
}
@@ -76,21 +76,16 @@ public class DocMappingBuilder {
* Apply any override mappings from the top level docStore annotation.
*/
public void applyMapping() {
DocMapping[] mapping = docStore.mapping();
for (DocMapping docMapping : mapping) {
applyFieldMapping(null, docMapping);
for (DocMapping docMapping : docStore.mapping()) {
applyFieldMapping(docMapping);
}
}
private void applyFieldMapping(String prefix, DocMapping docMapping) {
private void applyFieldMapping(DocMapping docMapping) {
String name = docMapping.name();
String fullName = SplitName.add(prefix, name);
DocPropertyMapping mapping = map.get(fullName);
DocPropertyMapping mapping = map.get(docMapping.name());
if (mapping == null) {
throw new IllegalStateException("DocMapping for [" + fullName + "] but property not included in document?");
throw new IllegalStateException("DocMapping for [" + docMapping.name() + "] but property not included in document?");
}
mapping.apply(docMapping);
}