Fix NPE, replace forEach() with for() /because Java. Formatting.

This commit is contained in:
Greg Burd 2017-10-24 14:24:23 -04:00
parent c6b95f12b4
commit 1642f09ce9
11 changed files with 162 additions and 165 deletions

View file

@ -76,20 +76,20 @@ public abstract class AbstractSessionOperations {
}
}
public ResultSet execute(Statement statement, boolean showValues) {
return execute(statement, null, showValues);
}
public ResultSet execute(Statement statement, UnitOfWork uow, boolean showValues) {
return executeAsync(statement, uow, showValues).getUninterruptibly();
public ResultSet execute(Statement statement, boolean showValues) {
return execute(statement, null, showValues);
}
public ResultSetFuture executeAsync(Statement statement, boolean showValues) {
return executeAsync(statement, null, showValues);
}
public ResultSet execute(Statement statement, UnitOfWork uow, boolean showValues) {
return executeAsync(statement, uow, showValues).getUninterruptibly();
}
public ResultSetFuture executeAsync(Statement statement, UnitOfWork uow, boolean showValues) {
try {
public ResultSetFuture executeAsync(Statement statement, boolean showValues) {
return executeAsync(statement, null, showValues);
}
public ResultSetFuture executeAsync(Statement statement, UnitOfWork uow, boolean showValues) {
try {
log(statement, uow, showValues);
return currentSession().executeAsync(statement);
} catch (RuntimeException e) {
@ -99,10 +99,10 @@ public abstract class AbstractSessionOperations {
void log(Statement statement, UnitOfWork uow, boolean showValues) {
if (LOG.isInfoEnabled()) {
String uowString = "";
if (uow != null) {
uowString = "within UOW(" + uow.hashCode() + "): ";
}
String uowString = "";
if (uow != null) {
uowString = "within UOW(" + uow.hashCode() + "): ";
}
LOG.info(String.format("Execute statement %s%s", uowString, statement));
}
if (isShowCql()) {

View file

@ -34,16 +34,13 @@ import net.helenus.core.cache.Facet;
/** Encapsulates the concept of a "transaction" as a unit-of-work. */
public abstract class AbstractUnitOfWork<E extends Exception> implements UnitOfWork<E>, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(AbstractUnitOfWork.class);
private static final Logger LOG = LoggerFactory.getLogger(AbstractUnitOfWork.class);
private final List<AbstractUnitOfWork<E>> nested = new ArrayList<>();
private final HelenusSession session;
private final AbstractUnitOfWork<E> parent;
// Cache:
private final Table<String, String, Object> cache = HashBasedTable.create();
private List<CommitThunk> postCommit = new ArrayList<CommitThunk>();
private boolean aborted = false;
private boolean committed = false;
protected String purpose;
protected int cacheHits = 0;
protected int cacheMisses = 0;
@ -51,6 +48,9 @@ public abstract class AbstractUnitOfWork<E extends Exception> implements UnitOfW
protected Stopwatch elapsedTime;
protected Stopwatch databaseTime = Stopwatch.createUnstarted();
protected Stopwatch cacheLookupTime = Stopwatch.createUnstarted();
private List<CommitThunk> postCommit = new ArrayList<CommitThunk>();
private boolean aborted = false;
private boolean committed = false;
protected AbstractUnitOfWork(HelenusSession session, AbstractUnitOfWork<E> parent) {
Objects.requireNonNull(session, "containing session cannot be null");
@ -90,16 +90,16 @@ public abstract class AbstractUnitOfWork<E extends Exception> implements UnitOfW
}
@Override
public void record(int cache, int ops) {
if (cache > 0) {
cacheHits += cache;
} else {
cacheMisses += Math.abs(cache);
}
if (ops > 0) {
databaseLookups += ops;
}
}
public void record(int cache, int ops) {
if (cache > 0) {
cacheHits += cache;
} else {
cacheMisses += Math.abs(cache);
}
if (ops > 0) {
databaseLookups += ops;
}
}
public String logTimers(String what) {
double e = (double) elapsedTime.elapsed(TimeUnit.MICROSECONDS) / 1000.0;
@ -109,12 +109,13 @@ public abstract class AbstractUnitOfWork<E extends Exception> implements UnitOfW
double fc = (c / e) * 100.0;
double dat = d + c;
double daf = (dat / e) * 100;
String nested = this.nested.stream().map(uow -> String.valueOf(uow.hashCode())).collect(Collectors.joining(", "));
return String.format(Locale.US, "UOW(%s%s) %s (total: %,.3fms cache: %,.3fms %,2.2f%% (%,d hit, %,d miss) %,d database operation%s took %,.3fms %,2.2f%% [%,.3fms %,2.2f%%])%s",
hashCode(),
(this.nested.size() > 0 ? ", [" + nested + "]" : ""),
what, e, c, fc, cacheHits, cacheMisses, databaseLookups, (databaseLookups > 1) ? "s" : "",
d, fd, dat, daf, (purpose == null ? "" : " in " + purpose));
String nested = this.nested.stream().map(uow -> String.valueOf(uow.hashCode()))
.collect(Collectors.joining(", "));
return String.format(Locale.US,
"UOW(%s%s) %s (total: %,.3fms cache: %,.3fms %,2.2f%% (%,d hit, %,d miss) %,d database operation%s took %,.3fms %,2.2f%% [%,.3fms %,2.2f%%])%s",
hashCode(), (this.nested.size() > 0 ? ", [" + nested + "]" : ""), what, e, c, fc, cacheHits,
cacheMisses, databaseLookups, (databaseLookups > 1) ? "s" : "", d, fd, dat, daf,
(purpose == null ? "" : " in " + purpose));
}
private void applyPostCommitFunctions() {
@ -124,8 +125,8 @@ public abstract class AbstractUnitOfWork<E extends Exception> implements UnitOfW
}
}
if (LOG.isInfoEnabled()) {
LOG.info(logTimers("committed"));
}
LOG.info(logTimers("committed"));
}
}
@Override
@ -238,8 +239,8 @@ public abstract class AbstractUnitOfWork<E extends Exception> implements UnitOfW
if (!hasAborted()) {
elapsedTime.stop();
if (LOG.isInfoEnabled()) {
LOG.info(logTimers("aborted"));
}
LOG.info(logTimers("aborted"));
}
}
}

View file

@ -27,6 +27,9 @@ import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.datastax.driver.core.*;
import com.google.common.cache.Cache;
@ -42,6 +45,7 @@ import net.helenus.core.reflect.Drafted;
import net.helenus.core.reflect.HelenusPropertyNode;
import net.helenus.core.reflect.MapExportable;
import net.helenus.mapping.HelenusEntity;
import net.helenus.mapping.HelenusProperty;
import net.helenus.mapping.MappingUtil;
import net.helenus.mapping.value.*;
import net.helenus.support.DslPropertyException;
@ -51,14 +55,12 @@ import net.helenus.support.Fun.Tuple2;
import net.helenus.support.Fun.Tuple6;
import net.helenus.support.HelenusException;
import net.helenus.support.HelenusMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class HelenusSession extends AbstractSessionOperations implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(HelenusSession.class);
private static final Logger LOG = LoggerFactory.getLogger(HelenusSession.class);
private final int MAX_CACHE_SIZE = 10000;
private final int MAX_CACHE_SIZE = 10000;
private final int MAX_CACHE_EXPIRE_SECONDS = 600;
private final Session session;
@ -204,14 +206,14 @@ public final class HelenusSession extends AbstractSessionOperations implements C
if (facet instanceof UnboundFacet) {
UnboundFacet unboundFacet = (UnboundFacet) facet;
UnboundFacet.Binder binder = unboundFacet.binder();
unboundFacet.getProperties().forEach(prop -> {
for (HelenusProperty prop : unboundFacet.getProperties()) {
if (valueMap == null) {
Object value = BeanColumnValueProvider.INSTANCE.getColumnValue(pojo, -1, prop, false);
binder.setValueForProperty(prop, value.toString());
} else {
binder.setValueForProperty(prop, valueMap.get(prop.getPropertyName()).toString());
}
});
}
if (binder.isBound()) {
boundFacets.add(binder.bind());
}
@ -293,34 +295,28 @@ public final class HelenusSession extends AbstractSessionOperations implements C
}
public UnitOfWork begin() {
return this.begin(null);
return this.begin(null);
}
public synchronized UnitOfWork begin(UnitOfWork parent) {
StringBuilder purpose = null;
if (LOG.isInfoEnabled()) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
int frame = 2;
if (trace[2].getMethodName().equals("begin")) {
frame = 3;
}
purpose = new StringBuilder()
.append(trace[frame].getClassName())
.append(".")
.append(trace[frame].getMethodName())
.append("(")
.append(trace[frame].getFileName())
.append(":")
.append(trace[frame].getLineNumber())
.append(")");
}
StringBuilder purpose = null;
if (LOG.isInfoEnabled()) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
int frame = 2;
if (trace[2].getMethodName().equals("begin")) {
frame = 3;
}
purpose = new StringBuilder().append(trace[frame].getClassName()).append(".")
.append(trace[frame].getMethodName()).append("(").append(trace[frame].getFileName()).append(":")
.append(trace[frame].getLineNumber()).append(")");
}
try {
Class<? extends UnitOfWork> clazz = unitOfWorkClass;
Constructor<? extends UnitOfWork> ctor = clazz.getConstructor(HelenusSession.class, UnitOfWork.class);
UnitOfWork uow = ctor.newInstance(this, parent);
if (LOG.isInfoEnabled()) {
uow.setPurpose(purpose.toString());
}
if (LOG.isInfoEnabled()) {
uow.setPurpose(purpose.toString());
}
if (parent != null) {
parent.addNestedUnitOfWork(uow);
}

View file

@ -65,6 +65,6 @@ public interface UnitOfWork<X extends Exception> extends AutoCloseable {
Stopwatch getCacheLookupTimer();
void record(int cache, int ops);
void record(int cache, int ops);
}

View file

@ -44,7 +44,7 @@ import net.helenus.mapping.value.BeanColumnValueProvider;
import net.helenus.support.HelenusException;
public abstract class AbstractStatementOperation<E, O extends AbstractStatementOperation<E, O>> extends Operation<E> {
protected boolean enableCache = true;
protected boolean showValues = true;
protected TraceContext traceContext;
@ -323,14 +323,14 @@ public abstract class AbstractStatementOperation<E, O extends AbstractStatementO
optionalCachedResult = uow.cacheLookup(facets);
if (optionalCachedResult.isPresent()) {
uowCacheHits.mark();
uow.record(1, 0);
uow.record(1, 0);
result = (E) optionalCachedResult.get();
}
}
if (result == null) {
uowCacheMiss.mark();
uow.record(-1, 0);
uow.record(-1, 0);
}
return result;
@ -344,19 +344,16 @@ public abstract class AbstractStatementOperation<E, O extends AbstractStatementO
if (facet instanceof UnboundFacet) {
UnboundFacet unboundFacet = (UnboundFacet) facet;
UnboundFacet.Binder binder = unboundFacet.binder();
List<HelenusProperty> properties = unboundFacet.getProperties();
if (properties != null) {
properties.forEach(prop -> {
if (valueMap == null) {
Object value = BeanColumnValueProvider.INSTANCE.getColumnValue(pojo, -1, prop, false);
binder.setValueForProperty(prop, value.toString());
} else {
binder.setValueForProperty(prop, valueMap.get(prop.getPropertyName()).toString());
}
});
if (binder.isBound()) {
facets.add(binder.bind());
}
for (HelenusProperty prop : unboundFacet.getProperties()) {
if (valueMap == null) {
Object value = BeanColumnValueProvider.INSTANCE.getColumnValue(pojo, -1, prop, false);
binder.setValueForProperty(prop, value.toString());
} else {
binder.setValueForProperty(prop, valueMap.get(prop.getPropertyName()).toString());
}
}
if (binder.isBound()) {
facets.add(binder.bind());
}
} else {
facets.add(facet);

View file

@ -73,7 +73,8 @@ public abstract class Operation<E> {
timer.start();
}
ResultSetFuture futureResultSet = session.executeAsync(statement, uow, showValues);
if (uow != null) uow.record(0, 1);
if (uow != null)
uow.record(0, 1);
ResultSet resultSet = futureResultSet.getUninterruptibly(); // TODO(gburd): (timeout, units);
if (uow != null)

View file

@ -38,6 +38,7 @@ import net.helenus.core.cache.Facet;
import net.helenus.core.cache.UnboundFacet;
import net.helenus.core.reflect.HelenusPropertyNode;
import net.helenus.mapping.HelenusEntity;
import net.helenus.mapping.HelenusProperty;
import net.helenus.mapping.MappingUtil;
import net.helenus.mapping.OrderingDirection;
import net.helenus.mapping.value.ColumnValueProvider;
@ -206,16 +207,18 @@ public final class SelectOperation<E> extends AbstractFilterStreamOperation<E, S
if (facet instanceof UnboundFacet) {
UnboundFacet unboundFacet = (UnboundFacet) facet;
UnboundFacet.Binder binder = unboundFacet.binder();
unboundFacet.getProperties().forEach(prop -> {
Filter filter = filters.get(prop);
if (filter != null) {
Object[] postulates = filter.postulateValues();
for (Object p : postulates) {
binder.setValueForProperty(prop, p.toString());
for (HelenusProperty prop : unboundFacet.getProperties()) {
if (filters != null) {
Filter filter = filters.get(prop);
if (filter != null) {
Object[] postulates = filter.postulateValues();
for (Object p : postulates) {
binder.setValueForProperty(prop, p.toString());
}
}
}
});
}
if (binder.isBound()) {
boundFacets.add(binder.bind());
}

View file

@ -15,11 +15,11 @@
*/
package net.helenus.mapping;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;
import net.helenus.mapping.validator.DistinctValidator;
import javax.validation.ConstraintValidator;
import org.apache.commons.lang3.ClassUtils;
import com.datastax.driver.core.DefaultMetadata;
@ -33,10 +33,9 @@ import net.helenus.core.annotation.Cacheable;
import net.helenus.core.cache.Facet;
import net.helenus.core.cache.UnboundFacet;
import net.helenus.mapping.annotation.*;
import net.helenus.mapping.validator.DistinctValidator;
import net.helenus.support.HelenusMappingException;
import javax.validation.ConstraintValidator;
public final class HelenusMappingEntity implements HelenusEntity {
private final Class<?> iface;
@ -129,11 +128,12 @@ public final class HelenusMappingEntity implements HelenusEntity {
facetsBuilder.add(new UnboundFacet(primaryKeyProperties));
primaryKeyProperties = null;
}
for (ConstraintValidator<?,?> constraint : MappingUtil.getValidators(prop.getGetterMethod())) {
if (constraint.getClass().isAssignableFrom(DistinctValidator.class));
UnboundFacet facet = new UnboundFacet(prop);
facetsBuilder.add(facet);
break;
for (ConstraintValidator<?, ?> constraint : MappingUtil.getValidators(prop.getGetterMethod())) {
if (constraint.getClass().isAssignableFrom(DistinctValidator.class))
;
UnboundFacet facet = new UnboundFacet(prop);
facetsBuilder.add(facet);
break;
}
}
}

View file

@ -222,59 +222,59 @@ public final class Constraints {
public @interface UpperCase {
}
/**
* Pattern annotation is LowerCase annotation is using to ensure that value is
* upper case before storing it
*
* <p>
* Can be used only for @java.lang.CharSequence
*
* <p>
* It does not have effect on selects and data retrieval operations
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy = PatternValidator.class)
public @interface Pattern {
/**
* Pattern annotation is LowerCase annotation is using to ensure that value is
* upper case before storing it
*
* <p>
* Can be used only for @java.lang.CharSequence
*
* <p>
* It does not have effect on selects and data retrieval operations
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy = PatternValidator.class)
public @interface Pattern {
/**
* User defined regex expression to check match of the value
*
* @return Java regex pattern
*/
String value();
/**
* User defined regex expression to check match of the value
*
* @return Java regex pattern
*/
String value();
/**
* Regex flags composition
*
* @return Java regex flags
*/
int flags();
}
/**
* Regex flags composition
*
* @return Java regex flags
*/
int flags();
}
/**
* Distinct annotation is used to signal, but not ensure that a value should be
* distinct in the database.
*
* <p>
* Can be used only for @java.lang.CharSequence
*
* <p>
* It does not have effect on selects and data retrieval operations
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy = DistinctValidator.class)
public @interface Distinct {
/**
* Distinct annotation is used to signal, but not ensure that a value should be
* distinct in the database.
*
* <p>
* Can be used only for @java.lang.CharSequence
*
* <p>
* It does not have effect on selects and data retrieval operations
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy = DistinctValidator.class)
public @interface Distinct {
/**
* User defined Enum to further restrict the items in the set.
*
* @return Java
*/
Class<? extends Enum> value() default Enum.class;
/**
* User defined Enum to further restrict the items in the set.
*
* @return Java
*/
Class<? extends Enum> value() default Enum.class;
}
}
}

View file

@ -66,9 +66,9 @@ public @interface Index {
*/
boolean caseSensitive() default true;
/**
*
* @return
*/
boolean distinct() default false;
/**
*
* @return
*/
boolean distinct() default false;
}

View file

@ -15,8 +15,6 @@
*/
package net.helenus.mapping.validator;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
@ -24,13 +22,14 @@ import net.helenus.mapping.annotation.Constraints;
public final class DistinctValidator implements ConstraintValidator<Constraints.Distinct, CharSequence> {
@Override
public void initialize(Constraints.Distinct constraintAnnotation) {
}
@Override
public void initialize(Constraints.Distinct constraintAnnotation) {
}
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
//TODO(gburd): if there is an Enum type supplied, check that value is valid Enum.name()
return true;
}
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
// TODO(gburd): if there is an Enum type supplied, check that value is valid
// Enum.name()
return true;
}
}