Format all Java files with google-java-format Change-Id: Iff8da485f1a01bd9c829464b28ea79aa5b821f7e
diff --git a/src/main/java/com/google/gwtorm/client/Column.java b/src/main/java/com/google/gwtorm/client/Column.java index 8ed6f0d..a3e4f45 100644 --- a/src/main/java/com/google/gwtorm/client/Column.java +++ b/src/main/java/com/google/gwtorm/client/Column.java
@@ -21,11 +21,10 @@ /** * Annotation marking an entity field for persistence in the data store. - * <p> - * Fields marked with <code>Column</code> must not be final and must not be - * private. Fields which might be accessed cross-packages (such as those - * declared in a common Key type like {@link StringKey}) must be declared with - * public access so generated code can access them directly. + * + * <p>Fields marked with <code>Column</code> must not be final and must not be private. Fields which + * might be accessed cross-packages (such as those declared in a common Key type like {@link + * StringKey}) must be declared with public access so generated code can access them directly. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @@ -36,18 +35,12 @@ /** @return unique identity of this field within its parent object. */ int id(); - /** - * @return name of the column in the data store. Defaults to the field name. - */ + /** @return name of the column in the data store. Defaults to the field name. */ String name() default ""; - /** - * @return maximum length (in characters). Only valid for String. - */ + /** @return maximum length (in characters). Only valid for String. */ int length() default 0; - /** - * @return is a value required. Defaults to true (NOT NULL). - */ + /** @return is a value required. Defaults to true (NOT NULL). */ boolean notNull() default true; }
diff --git a/src/main/java/com/google/gwtorm/client/CompoundKey.java b/src/main/java/com/google/gwtorm/client/CompoundKey.java index 0087ccb..1c66d18 100644 --- a/src/main/java/com/google/gwtorm/client/CompoundKey.java +++ b/src/main/java/com/google/gwtorm/client/CompoundKey.java
@@ -18,21 +18,17 @@ /** * Abstract key type composed of other keys. - * <p> - * Applications should subclass this type to create their own entity-specific - * key classes. + * + * <p>Applications should subclass this type to create their own entity-specific key classes. * * @param <P> the parent key type. Use {@link Key} if no parent key is needed. */ @SuppressWarnings("serial") -public abstract class CompoundKey<P extends Key<?>> implements Key<P>, - Serializable { +public abstract class CompoundKey<P extends Key<?>> implements Key<P>, Serializable { /** @return the member key components, minus the parent key. */ public abstract Key<?>[] members(); - /** - * @return the parent key instance; null if this is a root level key. - */ + /** @return the parent key instance; null if this is a root level key. */ @Override public P getParentKey() { return null;
diff --git a/src/main/java/com/google/gwtorm/client/IntKey.java b/src/main/java/com/google/gwtorm/client/IntKey.java index f64493b..08c90e0 100644 --- a/src/main/java/com/google/gwtorm/client/IntKey.java +++ b/src/main/java/com/google/gwtorm/client/IntKey.java
@@ -18,25 +18,20 @@ /** * Abstract key type using a single integer value. - * <p> - * Applications should subclass this type to create their own entity-specific - * key classes. + * + * <p>Applications should subclass this type to create their own entity-specific key classes. * * @param <P> the parent key type. Use {@link Key} if no parent key is needed. */ @SuppressWarnings("serial") public abstract class IntKey<P extends Key<?>> implements Key<P>, Serializable { - /** - * @return id of the entity instance. - */ + /** @return id of the entity instance. */ public abstract int get(); /** @param newValue the new value of this key. */ protected abstract void set(int newValue); - /** - * @return the parent key instance; null if this is a root level key. - */ + /** @return the parent key instance; null if this is a root level key. */ @Override public P getParentKey() { return null;
diff --git a/src/main/java/com/google/gwtorm/client/Key.java b/src/main/java/com/google/gwtorm/client/Key.java index b5b3d3a..69a2248 100644 --- a/src/main/java/com/google/gwtorm/client/Key.java +++ b/src/main/java/com/google/gwtorm/client/Key.java
@@ -16,10 +16,9 @@ /** * Generic type for an entity key. - * <p> - * Although not required, entities should make their primary key type implement - * this interface, permitting traversal up through the containment hierarchy of - * the entity keys. + * + * <p>Although not required, entities should make their primary key type implement this interface, + * permitting traversal up through the containment hierarchy of the entity keys. * * @param <P> type of the parent key. If no parent, use {@link Key} itself. */
diff --git a/src/main/java/com/google/gwtorm/client/KeyUtil.java b/src/main/java/com/google/gwtorm/client/KeyUtil.java index c4b4551..d815ea6 100644 --- a/src/main/java/com/google/gwtorm/client/KeyUtil.java +++ b/src/main/java/com/google/gwtorm/client/KeyUtil.java
@@ -20,12 +20,11 @@ /** * Set the encoder implementation to a valid implementation. - * <p> - * Server-side code needs to set the encoder to a - * {@link com.google.gwtorm.server.StandardKeyEncoder} instance prior to - * invoking any methods in this class. Typically this is done by the - * {@link com.google.gwtorm.server.SchemaFactory} implementation's static - * initializer. + * + * <p>Server-side code needs to set the encoder to a {@link + * com.google.gwtorm.server.StandardKeyEncoder} instance prior to invoking any methods in this + * class. Typically this is done by the {@link com.google.gwtorm.server.SchemaFactory} + * implementation's static initializer. */ public static void setEncoderImpl(final Encoder e) { ENCODER_IMPL = e; @@ -37,8 +36,8 @@ * @param <T> type of the key entity. * @param a first key to test; may be null. * @param b second key to test; may be null. - * @return true if both <code>a</code> and <code>b</code> are null, or if both - * are not-null and <code>a.equals(b)</code> is true. Otherwise false. + * @return true if both <code>a</code> and <code>b</code> are null, or if both are not-null and + * <code>a.equals(b)</code> is true. Otherwise false. */ public static <T extends Key<?>> boolean eq(final T a, final T b) { if (a == b) { @@ -52,11 +51,10 @@ /** * Encode a string to be safe for use within a URL like string. - * <p> - * The returned encoded string has URL component characters escaped with hex - * escapes (e.g. ' ' is '+' and '%' is '%25'). The special character '/' is - * left literal. The comma character (',') is always encoded, permitting - * multiple encoded string values to be joined together safely. + * + * <p>The returned encoded string has URL component characters escaped with hex escapes (e.g. ' ' + * is '+' and '%' is '%25'). The special character '/' is left literal. The comma character (',') + * is always encoded, permitting multiple encoded string values to be joined together safely. * * @param e the string to encode, must not be null. * @return the encoded string. @@ -90,17 +88,16 @@ if (comma < 0 && parent != null) { throw new IllegalArgumentException("Not enough components: " + in); } - assert(parent != null); + assert (parent != null); parent.fromString(in.substring(0, comma)); return decode(in.substring(comma + 1)); } - public static abstract class Encoder { + public abstract static class Encoder { public abstract String encode(String e); public abstract String decode(String e); } - private KeyUtil() { - } + private KeyUtil() {} }
diff --git a/src/main/java/com/google/gwtorm/client/LongKey.java b/src/main/java/com/google/gwtorm/client/LongKey.java index 986285e..a983064 100644 --- a/src/main/java/com/google/gwtorm/client/LongKey.java +++ b/src/main/java/com/google/gwtorm/client/LongKey.java
@@ -18,25 +18,20 @@ /** * Abstract key type using a single long value. - * <p> - * Applications should subclass this type to create their own entity-specific - * key classes. + * + * <p>Applications should subclass this type to create their own entity-specific key classes. * * @param <P> the parent key type. Use {@link Key} if no parent key is needed. */ @SuppressWarnings("serial") public abstract class LongKey<P extends Key<?>> implements Key<P>, Serializable { - /** - * @return id of the entity instance. - */ + /** @return id of the entity instance. */ public abstract long get(); /** @param newValue the new value of this key. */ protected abstract void set(long newValue); - /** - * @return the parent key instance; null if this is a root level key. - */ + /** @return the parent key instance; null if this is a root level key. */ @Override public P getParentKey() { return null;
diff --git a/src/main/java/com/google/gwtorm/client/RowVersion.java b/src/main/java/com/google/gwtorm/client/RowVersion.java index 3cae45c..e9c0d3a 100644 --- a/src/main/java/com/google/gwtorm/client/RowVersion.java +++ b/src/main/java/com/google/gwtorm/client/RowVersion.java
@@ -21,16 +21,14 @@ /** * Annotation marking a field as the row version used for optimistic locking. - * <p> - * Fields marked with <code>RowVersion</code> must also be marked with - * {@link Column} and must be of type <code>int</code>. The field will be - * automatically incremented during INSERT and UPDATE operations, and will be - * tested during UPDATE and DELETE operations. Concurrent modifications of the - * same entity fail as the row version won't match. - * <p> - * At most one RowVersion annotation should appear in any entity. + * + * <p>Fields marked with <code>RowVersion</code> must also be marked with {@link Column} and must be + * of type <code>int</code>. The field will be automatically incremented during INSERT and UPDATE + * operations, and will be tested during UPDATE and DELETE operations. Concurrent modifications of + * the same entity fail as the row version won't match. + * + * <p>At most one RowVersion annotation should appear in any entity. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) -public @interface RowVersion { -} +public @interface RowVersion {}
diff --git a/src/main/java/com/google/gwtorm/client/ShortKey.java b/src/main/java/com/google/gwtorm/client/ShortKey.java index abda6d1..efc7f57 100644 --- a/src/main/java/com/google/gwtorm/client/ShortKey.java +++ b/src/main/java/com/google/gwtorm/client/ShortKey.java
@@ -18,26 +18,20 @@ /** * Abstract key type using a single short value. - * <p> - * Applications should subclass this type to create their own entity-specific - * key classes. + * + * <p>Applications should subclass this type to create their own entity-specific key classes. * * @param <P> the parent key type. Use {@link Key} if no parent key is needed. */ @SuppressWarnings("serial") -public abstract class ShortKey<P extends Key<?>> implements Key<P>, - Serializable { - /** - * @return id of the entity instance. - */ +public abstract class ShortKey<P extends Key<?>> implements Key<P>, Serializable { + /** @return id of the entity instance. */ public abstract short get(); /** @param newValue the new value of this key. */ protected abstract void set(short newValue); - /** - * @return the parent key instance; null if this is a root level key. - */ + /** @return the parent key instance; null if this is a root level key. */ @Override public P getParentKey() { return null;
diff --git a/src/main/java/com/google/gwtorm/client/StringKey.java b/src/main/java/com/google/gwtorm/client/StringKey.java index a4dcf4c..e56661f 100644 --- a/src/main/java/com/google/gwtorm/client/StringKey.java +++ b/src/main/java/com/google/gwtorm/client/StringKey.java
@@ -18,26 +18,21 @@ /** * Abstract key type using a single string value. - * <p> - * Applications should subclass this type to create their own entity-specific - * key classes. + * + * <p>Applications should subclass this type to create their own entity-specific key classes. * * @param <P> the parent key type. Use {@link Key} if no parent key is needed. */ @SuppressWarnings("serial") -public abstract class StringKey<P extends Key<?>> implements Key<P>, - Serializable, Comparable<StringKey<?>> { - /** - * @return name of the entity instance. - */ +public abstract class StringKey<P extends Key<?>> + implements Key<P>, Serializable, Comparable<StringKey<?>> { + /** @return name of the entity instance. */ public abstract String get(); /** @param newValue the new value of this key. */ protected abstract void set(String newValue); - /** - * @return the parent key instance; null if this is a root level key. - */ + /** @return the parent key instance; null if this is a root level key. */ @Override public P getParentKey() { return null; @@ -60,8 +55,7 @@ } final StringKey<P> q = cast(b); - return get().equals(q.get()) - && KeyUtil.eq(getParentKey(), q.getParentKey()); + return get().equals(q.get()) && KeyUtil.eq(getParentKey(), q.getParentKey()); } @Override
diff --git a/src/main/java/com/google/gwtorm/jdbc/AccessGen.java b/src/main/java/com/google/gwtorm/jdbc/AccessGen.java index 9cfe6f5..de65541 100644 --- a/src/main/java/com/google/gwtorm/jdbc/AccessGen.java +++ b/src/main/java/com/google/gwtorm/jdbc/AccessGen.java
@@ -25,13 +25,6 @@ import com.google.gwtorm.server.CodeGenSupport; import com.google.gwtorm.server.GeneratedClassLoader; import com.google.gwtorm.server.OrmException; - -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -39,6 +32,11 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; /** Generates a concrete implementation of an {@link Access} extension. */ class AccessGen implements Opcodes { @@ -68,13 +66,11 @@ private String implTypeName; private Type entityType; - AccessGen(final GeneratedClassLoader loader, - final RelationModel rm, final SqlDialect sd) { + AccessGen(final GeneratedClassLoader loader, final RelationModel rm, final SqlDialect sd) { classLoader = loader; model = rm; dialect = sd; - entityType = - Type.getObjectType(model.getEntityTypeClassName().replace('.', '/')); + entityType = Type.getObjectType(model.getEntityTypeClassName().replace('.', '/')); } public Class<?> create() throws OrmException { @@ -106,8 +102,8 @@ if (model.getPrimaryKey() != null) { implementKeyQuery(model.getPrimaryKey()); - if ((model.getPrimaryKey().getField().isNested() || !model - .getPrimaryKey().getField().getPrimitiveType().isPrimitive()) + if ((model.getPrimaryKey().getField().isNested() + || !model.getPrimaryKey().getField().getPrimitiveType().isPrimitive()) && model.getPrimaryKey().getAllLeafColumns().size() == 1) { overrideGetMany(); } @@ -134,21 +130,27 @@ private void init() { superTypeName = Type.getInternalName(JdbcAccess.class); implClassName = - model.getEntityTypeClassName() + "_Access_" + model.getMethodName() - + "_" + Util.createRandomName(); + model.getEntityTypeClassName() + + "_Access_" + + model.getMethodName() + + "_" + + Util.createRandomName(); implTypeName = implClassName.replace('.', '/'); cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - cw.visit(V1_3, ACC_PUBLIC | ACC_FINAL | ACC_SUPER, implTypeName, null, - superTypeName, new String[] {model.getAccessInterfaceName().replace( - '.', '/')}); + cw.visit( + V1_3, + ACC_PUBLIC | ACC_FINAL | ACC_SUPER, + implTypeName, + null, + superTypeName, + new String[] {model.getAccessInterfaceName().replace('.', '/')}); } private void implementConstructor() { final String consName = "<init>"; final String consDesc = - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type - .getType(JdbcSchema.class)}); + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.getType(JdbcSchema.class)}); final MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); mv.visitCode(); @@ -160,12 +162,14 @@ mv.visitEnd(); } - private void implementGetString(final String methodName, - final String returnValue) { + private void implementGetString(final String methodName, final String returnValue) { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, methodName, Type - .getMethodDescriptor(Type.getType(String.class), new Type[] {}), - null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + methodName, + Type.getMethodDescriptor(Type.getType(String.class), new Type[] {}), + null, + null); mv.visitCode(); mv.visitLdcInsn(returnValue); mv.visitInsn(ARETURN); @@ -175,8 +179,12 @@ private void implementGetRelationID() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getRelationID", Type - .getMethodDescriptor(Type.INT_TYPE, new Type[] {}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "getRelationID", + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {}), + null, + null); mv.visitCode(); new CodeGenSupport(mv).push(model.getRelationID()); mv.visitInsn(IRETURN); @@ -184,12 +192,14 @@ mv.visitEnd(); } - private void implementMissingGetString(final String methodName, - final String why) { + private void implementMissingGetString(final String methodName, final String why) { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, methodName, Type - .getMethodDescriptor(Type.getType(String.class), new Type[] {}), - null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + methodName, + Type.getMethodDescriptor(Type.getType(String.class), new Type[] {}), + null, + null); mv.visitCode(); throwUnsupported(mv, model.getMethodName() + " does not support " + why); mv.visitInsn(RETURN); @@ -202,25 +212,34 @@ mv.visitTypeInsn(NEW, eType.getInternalName()); mv.visitInsn(DUP); mv.visitLdcInsn(message); - mv.visitMethodInsn(INVOKESPECIAL, eType.getInternalName(), "<init>", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type - .getType(String.class)})); + mv.visitMethodInsn( + INVOKESPECIAL, + eType.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.getType(String.class)})); mv.visitInsn(ATHROW); } private void implementPrimaryKey() { final KeyModel pk = model.getPrimaryKey(); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "primaryKey", Type - .getMethodDescriptor(Type.getType(Key.class), new Type[] {Type - .getType(Object.class)}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "primaryKey", + Type.getMethodDescriptor( + Type.getType(Key.class), new Type[] {Type.getType(Object.class)}), + null, + null); mv.visitCode(); if (pk != null && pk.getField().isNested()) { final ColumnModel pkf = pk.getField(); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, entityType.getInternalName()); - mv.visitFieldInsn(GETFIELD, entityType.getInternalName(), pkf - .getFieldName(), CodeGenSupport.toType(pkf).getDescriptor()); + mv.visitFieldInsn( + GETFIELD, + entityType.getInternalName(), + pkf.getFieldName(), + CodeGenSupport.toType(pkf).getDescriptor()); } else { mv.visitInsn(ACONST_NULL); } @@ -233,18 +252,24 @@ final KeyModel pk = model.getPrimaryKey(); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "get", Type.getMethodDescriptor( - Type.getType(Object.class), new Type[] {Type.getType(Key.class)}), - null, new String[] {Type.getType(OrmException.class) - .getInternalName()}); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "get", + Type.getMethodDescriptor( + Type.getType(Object.class), new Type[] {Type.getType(Key.class)}), + null, + new String[] {Type.getType(OrmException.class).getInternalName()}); mv.visitCode(); if (pk != null && pk.getField().isNested()) { final Type keyType = CodeGenSupport.toType(pk.getField()); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, keyType.getInternalName()); - mv.visitMethodInsn(INVOKEVIRTUAL, implTypeName, pk.getName(), Type - .getMethodDescriptor(entityType, new Type[] {keyType})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + implTypeName, + pk.getName(), + Type.getMethodDescriptor(entityType, new Type[] {keyType})); mv.visitInsn(ARETURN); } else { throwUnsupported(mv, model.getMethodName() + " does not support get(Key)"); @@ -255,13 +280,19 @@ private void implementNewEntityInstance() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "newEntityInstance", Type - .getMethodDescriptor(Type.getType(Object.class), new Type[] {}), - null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "newEntityInstance", + Type.getMethodDescriptor(Type.getType(Object.class), new Type[] {}), + null, + null); mv.visitCode(); mv.visitTypeInsn(NEW, entityType.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, entityType.getInternalName(), "<init>", + mv.visitMethodInsn( + INVOKESPECIAL, + entityType.getInternalName(), + "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); @@ -270,11 +301,14 @@ private void implementBindOne(final DmlType type) { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, type.methodName, Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] { - Type.getType(PreparedStatement.class), - Type.getType(Object.class)}), null, new String[] {Type.getType( - SQLException.class).getInternalName()}); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + type.methodName, + Type.getMethodDescriptor( + Type.VOID_TYPE, + new Type[] {Type.getType(PreparedStatement.class), Type.getType(Object.class)}), + null, + new String[] {Type.getType(SQLException.class).getInternalName()}); mv.visitCode(); if (type != DmlType.INSERT && model.getPrimaryKey() == null) { @@ -331,8 +365,8 @@ mv.visitEnd(); } - private void doBindOne(final MethodVisitor mv, final CodeGenSupport cgs, - final ColumnModel field) { + private void doBindOne( + final MethodVisitor mv, final CodeGenSupport cgs, final ColumnModel field) { if (field.isNested() && field.isNotNull()) { for (final ColumnModel c : field.getAllLeafColumns()) { doBindOne(mv, cgs, c); @@ -368,11 +402,14 @@ private void implementBindOneFetch() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "bindOneFetch", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] { - Type.getType(ResultSet.class), Type.getType(Object.class)}), - null, new String[] {Type.getType(SQLException.class) - .getInternalName()}); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "bindOneFetch", + Type.getMethodDescriptor( + Type.VOID_TYPE, + new Type[] {Type.getType(ResultSet.class), Type.getType(Object.class)}), + null, + new String[] {Type.getType(SQLException.class).getInternalName()}); mv.visitCode(); mv.visitVarInsn(ALOAD, 2); @@ -382,8 +419,7 @@ final CodeGenSupport cgs = new CodeGenSupport(mv); cgs.setEntityType(entityType); - if (model.getPrimaryKey() != null - && model.getPrimaryKey().getField().isNested()) { + if (model.getPrimaryKey() != null && model.getPrimaryKey().getField().isNested()) { final ColumnModel pkf = model.getPrimaryKey().getField(); final Type vType = CodeGenSupport.toType(pkf); final int oldIdx = cgs.getColumnIndex(); @@ -391,8 +427,11 @@ cgs.fieldSetBegin(); mv.visitTypeInsn(NEW, vType.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, vType.getInternalName(), "<init>", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKESPECIAL, + vType.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); cgs.fieldSetEnd(); cgs.resetColumnIndex(oldIdx); } @@ -410,8 +449,11 @@ mv.visitEnd(); } - private void doFetchOne(final MethodVisitor mv, final CodeGenSupport cgs, - final ColumnModel field, final int reportLiveInto) { + private void doFetchOne( + final MethodVisitor mv, + final CodeGenSupport cgs, + final ColumnModel field, + final int reportLiveInto) { if (field.isNested()) { int oldIdx = cgs.getColumnIndex(); final Type vType = CodeGenSupport.toType(field); @@ -429,8 +471,11 @@ cgs.fieldSetBegin(); mv.visitTypeInsn(NEW, vType.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, vType.getInternalName(), "<init>", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKESPECIAL, + vType.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); cgs.fieldSetEnd(); cgs.resetColumnIndex(oldIdx); @@ -465,8 +510,7 @@ } else { final int dupTo; - if (reportLiveInto >= 0 - && CodeGenSupport.toType(field).getSort() == Type.OBJECT) { + if (reportLiveInto >= 0 && CodeGenSupport.toType(field).getSort() == Type.OBJECT) { dupTo = cgs.newLocal(); } else { dupTo = -1; @@ -484,9 +528,11 @@ cgs.freeLocal(dupTo); } else { cgs.pushSqlHandle(); - mv.visitMethodInsn(INVOKEINTERFACE, Type.getType(ResultSet.class) - .getInternalName(), "wasNull", Type.getMethodDescriptor( - Type.BOOLEAN_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKEINTERFACE, + Type.getType(ResultSet.class).getInternalName(), + "wasNull", + Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {})); mv.visitJumpInsn(IFNE, wasnull); } mv.visitIincInsn(reportLiveInto, 1); @@ -501,8 +547,7 @@ query.append(model.getSelectSql(dialect, REL_ALIAS)); query.append(" WHERE "); int nth = 1; - for (final Iterator<ColumnModel> i = info.getAllLeafColumns().iterator(); i - .hasNext();) { + for (final Iterator<ColumnModel> i = info.getAllLeafColumns().iterator(); i.hasNext(); ) { final ColumnModel c = i.next(); query.append(REL_ALIAS); query.append('.'); @@ -515,39 +560,46 @@ } final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, info.getName(), Type - .getMethodDescriptor(entityType, new Type[] {keyType}), null, + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + info.getName(), + Type.getMethodDescriptor(entityType, new Type[] {keyType}), + null, new String[] {Type.getType(OrmException.class).getInternalName()}); mv.visitCode(); final int keyvar = 1, psvar = keyvar + keyType.getSize(); mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(query.toString()); - mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "prepareStatement", Type - .getMethodDescriptor(Type.getType(PreparedStatement.class), - new Type[] {Type.getType(String.class)})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + superTypeName, + "prepareStatement", + Type.getMethodDescriptor( + Type.getType(PreparedStatement.class), new Type[] {Type.getType(String.class)})); mv.visitVarInsn(ASTORE, psvar); - final CodeGenSupport cgs = new CodeGenSupport(mv) { - @Override - public void pushSqlHandle() { - mv.visitVarInsn(ALOAD, psvar); - } + final CodeGenSupport cgs = + new CodeGenSupport(mv) { + @Override + public void pushSqlHandle() { + mv.visitVarInsn(ALOAD, psvar); + } - @Override - public void pushFieldValue() { - appendGetField(getFieldReference()); - } + @Override + public void pushFieldValue() { + appendGetField(getFieldReference()); + } - @Override - protected void appendGetField(final ColumnModel c) { - if (c.getParent() == null) { - loadVar(keyType, keyvar); - } else { - super.appendGetField(c); - } - } - }; + @Override + protected void appendGetField(final ColumnModel c) { + if (c.getParent() == null) { + loadVar(keyType, keyvar); + } else { + super.appendGetField(c); + } + } + }; for (final ColumnModel c : info.getAllLeafColumns()) { cgs.setFieldReference(c); dialect.getSqlTypeInfo(c).generatePreparedStatementSet(cgs); @@ -555,9 +607,12 @@ mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, psvar); - mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "queryOne", Type - .getMethodDescriptor(Type.getType(Object.class), new Type[] {Type - .getType(PreparedStatement.class)})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + superTypeName, + "queryOne", + Type.getMethodDescriptor( + Type.getType(Object.class), new Type[] {Type.getType(PreparedStatement.class)})); mv.visitTypeInsn(CHECKCAST, entityType.getInternalName()); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); @@ -576,10 +631,13 @@ query.append(" IN"); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getBySqlIn", Type - .getMethodDescriptor(Type - .getType(com.google.gwtorm.server.ResultSet.class), - new Type[] {Type.getType(Collection.class)}), null, + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "getBySqlIn", + Type.getMethodDescriptor( + Type.getType(com.google.gwtorm.server.ResultSet.class), + new Type[] {Type.getType(Collection.class)}), + null, new String[] {Type.getType(OrmException.class).getInternalName()}); mv.visitCode(); @@ -592,15 +650,21 @@ mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(query.toString()); mv.visitVarInsn(ALOAD, keyset); - mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "prepareBySqlIn", Type - .getMethodDescriptor(Type.getType(PreparedStatement.class), new Type[] { - Type.getType(String.class), Type.getType(Collection.class)})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + superTypeName, + "prepareBySqlIn", + Type.getMethodDescriptor( + Type.getType(PreparedStatement.class), + new Type[] {Type.getType(String.class), Type.getType(Collection.class)})); mv.visitVarInsn(ASTORE, psvar); mv.visitVarInsn(ALOAD, keyset); - mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Collection.class), - "iterator", Type.getMethodDescriptor(Type.getType(Iterator.class), - new Type[] {})); + mv.visitMethodInsn( + INVOKEINTERFACE, + Type.getInternalName(Collection.class), + "iterator", + Type.getMethodDescriptor(Type.getType(Iterator.class), new Type[] {})); mv.visitVarInsn(ASTORE, itrvar); mv.visitInsn(ICONST_1); @@ -610,43 +674,48 @@ final Label again = new Label(); mv.visitLabel(again); mv.visitVarInsn(ALOAD, itrvar); - mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Iterator.class), - "hasNext", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKEINTERFACE, + Type.getInternalName(Iterator.class), + "hasNext", + Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {})); mv.visitJumpInsn(IFEQ, endbind); mv.visitVarInsn(ALOAD, itrvar); - mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Iterator.class), - "next", Type.getMethodDescriptor(Type.getType(Object.class), - new Type[] {})); - mv.visitTypeInsn(CHECKCAST, CodeGenSupport.toType(pk.getField()) - .getInternalName()); + mv.visitMethodInsn( + INVOKEINTERFACE, + Type.getInternalName(Iterator.class), + "next", + Type.getMethodDescriptor(Type.getType(Object.class), new Type[] {})); + mv.visitTypeInsn(CHECKCAST, CodeGenSupport.toType(pk.getField()).getInternalName()); mv.visitVarInsn(ASTORE, keyvar); - final CodeGenSupport cgs = new CodeGenSupport(mv) { - @Override - public void pushSqlHandle() { - mv.visitVarInsn(ALOAD, psvar); - } + final CodeGenSupport cgs = + new CodeGenSupport(mv) { + @Override + public void pushSqlHandle() { + mv.visitVarInsn(ALOAD, psvar); + } - @Override - public void pushFieldValue() { - appendGetField(getFieldReference()); - } + @Override + public void pushFieldValue() { + appendGetField(getFieldReference()); + } - @Override - public void pushColumnIndex() { - mv.visitVarInsn(ILOAD, colvar); - } + @Override + public void pushColumnIndex() { + mv.visitVarInsn(ILOAD, colvar); + } - @Override - protected void appendGetField(final ColumnModel c) { - if (c.getParent() == null) { - mv.visitVarInsn(ALOAD, keyvar); - } else { - super.appendGetField(c); - } - } - }; + @Override + protected void appendGetField(final ColumnModel c) { + if (c.getParent() == null) { + mv.visitVarInsn(ALOAD, keyvar); + } else { + super.appendGetField(c); + } + } + }; cgs.setFieldReference(pkcol); dialect.getSqlTypeInfo(pkcol).generatePreparedStatementSet(cgs); @@ -656,8 +725,12 @@ mv.visitLabel(endbind); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, psvar); - mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "queryList", Type - .getMethodDescriptor(Type.getType(com.google.gwtorm.server.ResultSet.class), + mv.visitMethodInsn( + INVOKEVIRTUAL, + superTypeName, + "queryList", + Type.getMethodDescriptor( + Type.getType(com.google.gwtorm.server.ResultSet.class), new Type[] {Type.getType(PreparedStatement.class)})); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); @@ -683,42 +756,48 @@ final int psvar = nextVar++; final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, info.getName(), Type - .getMethodDescriptor(Type - .getType(com.google.gwtorm.server.ResultSet.class), pTypes), - null, new String[] {Type.getType(OrmException.class) - .getInternalName()}); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + info.getName(), + Type.getMethodDescriptor( + Type.getType(com.google.gwtorm.server.ResultSet.class), pTypes), + null, + new String[] {Type.getType(OrmException.class).getInternalName()}); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(info.getSelectSql(dialect, REL_ALIAS)); - mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "prepareStatement", Type - .getMethodDescriptor(Type.getType(PreparedStatement.class), - new Type[] {Type.getType(String.class)})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + superTypeName, + "prepareStatement", + Type.getMethodDescriptor( + Type.getType(PreparedStatement.class), new Type[] {Type.getType(String.class)})); mv.visitVarInsn(ASTORE, psvar); final int argIdx[] = new int[] {0}; - final CodeGenSupport cgs = new CodeGenSupport(mv) { - @Override - public void pushSqlHandle() { - mv.visitVarInsn(ALOAD, psvar); - } + final CodeGenSupport cgs = + new CodeGenSupport(mv) { + @Override + public void pushSqlHandle() { + mv.visitVarInsn(ALOAD, psvar); + } - @Override - public void pushFieldValue() { - appendGetField(getFieldReference()); - } + @Override + public void pushFieldValue() { + appendGetField(getFieldReference()); + } - @Override - protected void appendGetField(final ColumnModel c) { - final int n = argIdx[0]; - if (c == pCols.get(n)) { - loadVar(pTypes[n], pVars[n]); - } else { - super.appendGetField(c); - } - } - }; + @Override + protected void appendGetField(final ColumnModel c) { + final int n = argIdx[0]; + if (c == pCols.get(n)) { + loadVar(pTypes[n], pVars[n]); + } else { + super.appendGetField(c); + } + } + }; for (final ColumnModel c : pCols) { if (c.isNested()) { for (final ColumnModel n : c.getAllLeafColumns()) { @@ -737,18 +816,19 @@ mv.visitVarInsn(ALOAD, psvar); if (hasLimitParam) { if (dialect.selectHasLimit()) { - CodeGenSupport cgs2 = new CodeGenSupport(mv) { - @Override - public void pushSqlHandle() { - mv.visitVarInsn(ALOAD, psvar); - } + CodeGenSupport cgs2 = + new CodeGenSupport(mv) { + @Override + public void pushSqlHandle() { + mv.visitVarInsn(ALOAD, psvar); + } - @Override - public void pushFieldValue() { - final int n = argIdx[0]; - loadVar(pTypes[n], pVars[n]); - } - }; + @Override + public void pushFieldValue() { + final int n = argIdx[0]; + loadVar(pTypes[n], pVars[n]); + } + }; cgs2.resetColumnIndex(cgs.getColumnIndex() + 1); dialect.getSqlTypeInfo(Integer.TYPE).generatePreparedStatementSet(cgs2); } @@ -756,16 +836,22 @@ } else { cgs.push(info.getStaticLimit()); } - mv.visitMethodInsn(INVOKEINTERFACE, Type.getType( - PreparedStatement.class).getInternalName(), "setMaxRows", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE})); + mv.visitMethodInsn( + INVOKEINTERFACE, + Type.getType(PreparedStatement.class).getInternalName(), + "setMaxRows", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE})); } } mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, psvar); - mv.visitMethodInsn(INVOKEVIRTUAL, superTypeName, "queryList", Type - .getMethodDescriptor(Type.getType(com.google.gwtorm.server.ResultSet.class), + mv.visitMethodInsn( + INVOKEVIRTUAL, + superTypeName, + "queryList", + Type.getMethodDescriptor( + Type.getType(com.google.gwtorm.server.ResultSet.class), new Type[] {Type.getType(PreparedStatement.class)})); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1);
diff --git a/src/main/java/com/google/gwtorm/jdbc/Database.java b/src/main/java/com/google/gwtorm/jdbc/Database.java index 0de0f11..2db2833 100644 --- a/src/main/java/com/google/gwtorm/jdbc/Database.java +++ b/src/main/java/com/google/gwtorm/jdbc/Database.java
@@ -26,24 +26,21 @@ import com.google.gwtorm.server.SchemaFactory; import com.google.gwtorm.server.SchemaGen; import com.google.gwtorm.server.StandardKeyEncoder; - import java.sql.Connection; import java.sql.SQLException; - import javax.sql.DataSource; /** * Constructor for application {@link Schema} extensions. - * <p> - * Applications should use the Database class to create instances of their - * Schema extension interface, and thus open and connect to the JDBC data store. - * <p> - * Creating a new Database instance is expensive, due to the type analysis and - * code generation performed to implement the Schema and Access interfaces. - * Applications should create and cache their Database instance for the live of - * the application. - * <p> - * Database instances are thread-safe, but returned Schema instances are not. + * + * <p>Applications should use the Database class to create instances of their Schema extension + * interface, and thus open and connect to the JDBC data store. + * + * <p>Creating a new Database instance is expensive, due to the type analysis and code generation + * performed to implement the Schema and Access interfaces. Applications should create and cache + * their Database instance for the live of the application. + * + * <p>Database instances are thread-safe, but returned Schema instances are not. * * @param <T> */ @@ -62,11 +59,10 @@ * * @param ds JDBC connection information * @param schema application extension of the Schema interface to implement. - * @throws OrmException the schema interface is incorrectly defined, or the - * driver class is not available through the current class loader. + * @throws OrmException the schema interface is incorrectly defined, or the driver class is not + * available through the current class loader. */ - public Database(final DataSource ds, final Class<T> schema) - throws OrmException { + public Database(final DataSource ds, final Class<T> schema) throws OrmException { dataSource = ds; SqlDialect dialect; @@ -89,16 +85,21 @@ } @SuppressWarnings({"unchecked", "rawtypes"}) - private Class<T> generate(final SqlDialect dialect, - final GeneratedClassLoader loader) throws OrmException { - return new SchemaGen(loader, schemaModel, getClass(), JdbcSchema.class, - new SchemaGen.AccessGenerator() { - @Override - public Class<?> create(GeneratedClassLoader loader, RelationModel rm) - throws OrmException { - return new AccessGen(loader, rm, dialect).create(); - } - }).create(); + private Class<T> generate(final SqlDialect dialect, final GeneratedClassLoader loader) + throws OrmException { + return new SchemaGen( + loader, + schemaModel, + getClass(), + JdbcSchema.class, + new SchemaGen.AccessGenerator() { + @Override + public Class<?> create(GeneratedClassLoader loader, RelationModel rm) + throws OrmException { + return new AccessGen(loader, rm, dialect).create(); + } + }) + .create(); } SqlDialect getDialect() { @@ -113,9 +114,8 @@ * Open a new connection to the database and get a Schema wrapper. * * @return a new JDBC connection, wrapped up in the application's Schema. - * @throws OrmException the connection could not be opened to the database. - * The JDBC exception detail should be examined to determine the root - * cause of the connection failure. + * @throws OrmException the connection could not be opened to the database. The JDBC exception + * detail should be examined to determine the root cause of the connection failure. */ @Override public T open() throws OrmException {
diff --git a/src/main/java/com/google/gwtorm/jdbc/JdbcAccess.java b/src/main/java/com/google/gwtorm/jdbc/JdbcAccess.java index 7335427..c1ca085 100644 --- a/src/main/java/com/google/gwtorm/jdbc/JdbcAccess.java +++ b/src/main/java/com/google/gwtorm/jdbc/JdbcAccess.java
@@ -22,7 +22,6 @@ import com.google.gwtorm.server.ListResultSet; import com.google.gwtorm.server.OrmConcurrencyException; import com.google.gwtorm.server.OrmException; - import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -32,8 +31,7 @@ import java.util.List; /** Internal base class for implementations of {@link Access}. */ -public abstract class JdbcAccess<T, K extends Key<?>> extends - AbstractAccess<T, K> { +public abstract class JdbcAccess<T, K extends Key<?>> extends AbstractAccess<T, K> { private final JdbcSchema schema; protected JdbcAccess(final JdbcSchema s) { @@ -66,30 +64,30 @@ case 0: // Nothing requested, nothing to return. // - return new ListResultSet<>(Collections.<T> emptyList()); + return new ListResultSet<>(Collections.<T>emptyList()); - case 1: { - // Only one key requested, use a faster equality lookup. - // - final T entity = get(keySet.iterator().next()); - if (entity != null) { - return new ListResultSet<>(Collections.singletonList(entity)); + case 1: + { + // Only one key requested, use a faster equality lookup. + // + final T entity = get(keySet.iterator().next()); + if (entity != null) { + return new ListResultSet<>(Collections.singletonList(entity)); + } + return new ListResultSet<>(Collections.<T>emptyList()); } - return new ListResultSet<>(Collections.<T> emptyList()); - } default: return getBySqlIn(keySet); } } - protected com.google.gwtorm.server.ResultSet<T> getBySqlIn( - final Collection<K> keys) throws OrmException { + protected com.google.gwtorm.server.ResultSet<T> getBySqlIn(final Collection<K> keys) + throws OrmException { return super.get(keys); } - protected PreparedStatement prepareStatement(final String sql) - throws OrmException { + protected PreparedStatement prepareStatement(final String sql) throws OrmException { try { return schema.getConnection().prepareStatement(sql); } catch (SQLException e) { @@ -97,8 +95,8 @@ } } - protected PreparedStatement prepareBySqlIn(final String sql, - final Collection<K> keys) throws OrmException { + protected PreparedStatement prepareBySqlIn(final String sql, final Collection<K> keys) + throws OrmException { final int n = keys.size(); final StringBuilder buf = new StringBuilder(sql.length() + n << 1 + 1); buf.append(sql); @@ -138,15 +136,15 @@ } } - protected com.google.gwtorm.server.ResultSet<T> queryList( - final PreparedStatement ps) throws OrmException { + protected com.google.gwtorm.server.ResultSet<T> queryList(final PreparedStatement ps) + throws OrmException { final ResultSet rs; try { rs = ps.executeQuery(); if (!rs.next()) { rs.close(); ps.close(); - return new ListResultSet<>(Collections.<T> emptyList()); + return new ListResultSet<>(Collections.<T>emptyList()); } } catch (SQLException err) { try { @@ -174,8 +172,8 @@ } } - private void insertIndividually(Iterable<T> instances) throws SQLException, - OrmConcurrencyException { + private void insertIndividually(Iterable<T> instances) + throws SQLException, OrmConcurrencyException { PreparedStatement ps = null; try { boolean concurrencyViolationDetected = false; @@ -199,8 +197,8 @@ } } - private void insertAsBatch(final Iterable<T> instances) throws SQLException, - OrmConcurrencyException { + private void insertAsBatch(final Iterable<T> instances) + throws SQLException, OrmConcurrencyException { PreparedStatement ps = null; try { int cnt = 0; @@ -235,8 +233,8 @@ } } - private void updateIndividually(Iterable<T> instances) throws SQLException, - OrmConcurrencyException { + private void updateIndividually(Iterable<T> instances) + throws SQLException, OrmConcurrencyException { PreparedStatement ps = null; try { boolean concurrencyViolationDetected = false; @@ -260,8 +258,8 @@ } } - private void updateAsBatch(final Iterable<T> instances) throws SQLException, - OrmConcurrencyException { + private void updateAsBatch(final Iterable<T> instances) + throws SQLException, OrmConcurrencyException { PreparedStatement ps = null; try { int cnt = 0; @@ -285,11 +283,9 @@ * Attempt to update instances. * * @param instances the instances to attempt to update - * @return collection of instances that cannot be updated as they are not yet - * existing + * @return collection of instances that cannot be updated as they are not yet existing */ - private Collection<T> attemptUpdate(final Iterable<T> instances) - throws OrmException { + private Collection<T> attemptUpdate(final Iterable<T> instances) throws OrmException { if (schema.getDialect().canDetermineIndividualBatchUpdateCounts()) { return attemptUpdateAsBatch(instances); } else { @@ -297,8 +293,7 @@ } } - private Collection<T> attemptUpdatesIndividually(Iterable<T> instances) - throws OrmException { + private Collection<T> attemptUpdatesIndividually(Iterable<T> instances) throws OrmException { Collection<T> inserts = null; try { PreparedStatement ps = null; @@ -314,7 +309,8 @@ if (inserts == null) { inserts = new ArrayList<>(); } - inserts.add(o); } + inserts.add(o); + } allInstances.add(o); } } finally { @@ -342,8 +338,7 @@ } } - private Collection<T> attemptUpdateAsBatch(final Iterable<T> instances) - throws OrmException { + private Collection<T> attemptUpdateAsBatch(final Iterable<T> instances) throws OrmException { Collection<T> inserts = null; try { PreparedStatement ps = null; @@ -405,8 +400,8 @@ } } - private void deleteIndividually(Iterable<T> instances) throws SQLException, - OrmConcurrencyException { + private void deleteIndividually(Iterable<T> instances) + throws SQLException, OrmConcurrencyException { PreparedStatement ps = null; try { boolean concurrencyViolationDetected = false; @@ -430,8 +425,8 @@ } } - private void deleteAsBatch(final Iterable<T> instances) throws SQLException, - OrmConcurrencyException { + private void deleteAsBatch(final Iterable<T> instances) + throws SQLException, OrmConcurrencyException { PreparedStatement ps = null; try { int cnt = 0; @@ -459,7 +454,7 @@ final int numberOfRowsUpdated = schema.getDialect().executeBatch(ps); if (numberOfRowsUpdated != cnt) { - throw new OrmConcurrencyException(); + throw new OrmConcurrencyException(); } } @@ -497,15 +492,11 @@ protected abstract String getDeleteOneSql(); - protected abstract void bindOneInsert(PreparedStatement ps, T entity) - throws SQLException; + protected abstract void bindOneInsert(PreparedStatement ps, T entity) throws SQLException; - protected abstract void bindOneUpdate(PreparedStatement ps, T entity) - throws SQLException; + protected abstract void bindOneUpdate(PreparedStatement ps, T entity) throws SQLException; - protected abstract void bindOneDelete(PreparedStatement ps, T entity) - throws SQLException; + protected abstract void bindOneDelete(PreparedStatement ps, T entity) throws SQLException; - protected abstract void bindOneFetch(ResultSet rs, T entity) - throws SQLException; + protected abstract void bindOneFetch(ResultSet rs, T entity) throws SQLException; }
diff --git a/src/main/java/com/google/gwtorm/jdbc/JdbcExecutor.java b/src/main/java/com/google/gwtorm/jdbc/JdbcExecutor.java index b310535..e9750da 100644 --- a/src/main/java/com/google/gwtorm/jdbc/JdbcExecutor.java +++ b/src/main/java/com/google/gwtorm/jdbc/JdbcExecutor.java
@@ -16,7 +16,6 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement;
diff --git a/src/main/java/com/google/gwtorm/jdbc/JdbcResultSet.java b/src/main/java/com/google/gwtorm/jdbc/JdbcResultSet.java index af9a49b..6e26b4d 100644 --- a/src/main/java/com/google/gwtorm/jdbc/JdbcResultSet.java +++ b/src/main/java/com/google/gwtorm/jdbc/JdbcResultSet.java
@@ -17,7 +17,6 @@ import com.google.gwtorm.client.Key; import com.google.gwtorm.server.AbstractResultSet; import com.google.gwtorm.server.OrmRuntimeException; - import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
diff --git a/src/main/java/com/google/gwtorm/jdbc/JdbcSchema.java b/src/main/java/com/google/gwtorm/jdbc/JdbcSchema.java index 1173140..0a84978 100644 --- a/src/main/java/com/google/gwtorm/jdbc/JdbcSchema.java +++ b/src/main/java/com/google/gwtorm/jdbc/JdbcSchema.java
@@ -26,7 +26,6 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.Schema; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.SQLException; import java.util.HashSet; @@ -111,8 +110,7 @@ } } - private void createSequences(final StatementExecutor e) throws OrmException, - SQLException { + private void createSequences(final StatementExecutor e) throws OrmException, SQLException { final SqlDialect dialect = dbDef.getDialect(); final SchemaModel model = dbDef.getSchemaModel(); @@ -124,8 +122,7 @@ } } - private void createRelations(final StatementExecutor e) throws SQLException, - OrmException { + private void createRelations(final StatementExecutor e) throws SQLException, OrmException { final SqlDialect dialect = dbDef.getDialect(); final SchemaModel model = dbDef.getSchemaModel(); Set<String> have = dialect.listTables(getConnection()); @@ -139,8 +136,9 @@ private void addColumns(final StatementExecutor e, final RelationModel rel) throws SQLException, OrmException { final SqlDialect dialect = dbDef.getDialect(); - Set<String> have = dialect.listColumns( // - getConnection(), rel.getRelationName().toLowerCase()); + Set<String> have = + dialect.listColumns( // + getConnection(), rel.getRelationName().toLowerCase()); for (final ColumnModel c : rel.getColumns()) { if (!have.contains(c.getColumnName().toLowerCase())) { dialect.addColumn(e, rel.getRelationName(), c); @@ -148,16 +146,15 @@ } } - public void renameTable(final StatementExecutor e, String from, String to) - throws OrmException { + public void renameTable(final StatementExecutor e, String from, String to) throws OrmException { Preconditions.checkNotNull(e); Preconditions.checkNotNull(from); Preconditions.checkNotNull(to); getDialect().renameTable(e, from, to); } - public void renameField(final StatementExecutor e, String table, String from, - String to) throws OrmException { + public void renameField(final StatementExecutor e, String table, String from, String to) + throws OrmException { final RelationModel rel = findRelationModel(table); if (rel == null) { throw new OrmException("Relation " + table + " not defined"); @@ -169,8 +166,8 @@ getDialect().renameColumn(e, table, from, col); } - public void renameColumn(final StatementExecutor e, String table, String from, - String to) throws OrmException { + public void renameColumn(final StatementExecutor e, String table, String from, String to) + throws OrmException { final RelationModel rel = findRelationModel(table); if (rel == null) { throw new OrmException("Relation " + table + " not defined"); @@ -205,8 +202,7 @@ } } - private void pruneSequences(final StatementExecutor e) throws SQLException, - OrmException { + private void pruneSequences(final StatementExecutor e) throws SQLException, OrmException { final SqlDialect dialect = dbDef.getDialect(); final SchemaModel model = dbDef.getSchemaModel(); HashSet<String> want = new HashSet<>(); @@ -220,8 +216,7 @@ } } - private void pruneRelations(final StatementExecutor e) throws SQLException, - OrmException { + private void pruneRelations(final StatementExecutor e) throws SQLException, OrmException { final SqlDialect dialect = dbDef.getDialect(); final SchemaModel model = dbDef.getSchemaModel(); HashSet<String> want = new HashSet<>(); @@ -242,8 +237,9 @@ for (final ColumnModel c : rel.getColumns()) { want.add(c.getColumnName().toLowerCase()); } - for (String column : dialect.listColumns( // - getConnection(), rel.getRelationName().toLowerCase())) { + for (String column : + dialect.listColumns( // + getConnection(), rel.getRelationName().toLowerCase())) { if (!want.contains(column)) { dialect.dropColumn(e, rel.getRelationName(), column); }
diff --git a/src/main/java/com/google/gwtorm/jdbc/SimpleDataSource.java b/src/main/java/com/google/gwtorm/jdbc/SimpleDataSource.java index 2536e50..abefb66 100644 --- a/src/main/java/com/google/gwtorm/jdbc/SimpleDataSource.java +++ b/src/main/java/com/google/gwtorm/jdbc/SimpleDataSource.java
@@ -28,7 +28,6 @@ import java.util.List; import java.util.Properties; import java.util.logging.Logger; - import javax.sql.DataSource; /** A simple non-pooling DataSource representation. */ @@ -40,14 +39,13 @@ /** * Create a non-pooling data source. - * <p> - * The JDBC properties information must define at least <code>url</code> and - * <code>driver</code>, but may also include driver specific properties such - * as <code>username</code> and <code>password</code>. + * + * <p>The JDBC properties information must define at least <code>url</code> and <code>driver + * </code>, but may also include driver specific properties such as <code>username</code> and + * <code>password</code>. * * @param dbInfo JDBC connection information. The property table is copied. - * @throws SQLException the driver class is not available through the current - * class loader. + * @throws SQLException the driver class is not available through the current class loader. */ public SimpleDataSource(final Properties dbInfo) throws SQLException { connectionInfo = new Properties(); @@ -90,8 +88,7 @@ logWriter = new PrintWriter(System.out); } - private static SQLException badClasspath(final String classpath, - final MalformedURLException e1) { + private static SQLException badClasspath(final String classpath, final MalformedURLException e1) { final SQLException sqle; sqle = new SQLException("Invalid driver classpath " + classpath); sqle.initCause(e1); @@ -107,8 +104,7 @@ } @Override - public Connection getConnection(String user, String password) - throws SQLException { + public Connection getConnection(String user, String password) throws SQLException { if (driver != null) { final Properties info = new Properties(connectionInfo); if (user != null) { @@ -138,8 +134,7 @@ } @Override - public void setLoginTimeout(int seconds) { - } + public void setLoginTimeout(int seconds) {} @Override public boolean isWrapperFor(Class<?> iface) { @@ -156,8 +151,8 @@ throw new SQLFeatureNotSupportedException(); } - private static synchronized Driver loadDriver(final String driver, - final ClassLoader loader) throws SQLException { + private static synchronized Driver loadDriver(final String driver, final ClassLoader loader) + throws SQLException { // I've seen some drivers (*cough* Informix *cough*) which won't load // on multiple threads at the same time. Forcing our code to synchronize // around loading the driver ensures we won't ever ask for the same driver
diff --git a/src/main/java/com/google/gwtorm/nosql/AccessGen.java b/src/main/java/com/google/gwtorm/nosql/AccessGen.java index 0a8bbd9..41de1a6 100644 --- a/src/main/java/com/google/gwtorm/nosql/AccessGen.java +++ b/src/main/java/com/google/gwtorm/nosql/AccessGen.java
@@ -27,18 +27,16 @@ import com.google.gwtorm.server.GeneratedClassLoader; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.ResultSet; - -import org.antlr.runtime.tree.Tree; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; +import org.antlr.runtime.tree.Tree; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; /** Generates a concrete implementation of a {@link NoSqlAccess} extension. */ class AccessGen implements Opcodes { @@ -50,8 +48,7 @@ private static final Type byteArray = Type.getType(byte[].class); private static final Type ormException = Type.getType(OrmException.class); private static final Type resultSet = Type.getType(ResultSet.class); - private static final Type indexKeyBuilder = - Type.getType(IndexKeyBuilder.class); + private static final Type indexKeyBuilder = Type.getType(IndexKeyBuilder.class); private static final String F_OBJECT_CODEC = "objectCodec"; private static final String F_INDEXES = "indexes"; @@ -68,16 +65,17 @@ private String implClassName; private String implTypeName; - AccessGen(final GeneratedClassLoader loader, final RelationModel rm, + AccessGen( + final GeneratedClassLoader loader, + final RelationModel rm, final Class<? extends NoSqlSchema> schemaClazz, - @SuppressWarnings("rawtypes") - final Class<? extends NoSqlAccess> accessClazz) throws OrmException { + @SuppressWarnings("rawtypes") final Class<? extends NoSqlAccess> accessClazz) + throws OrmException { classLoader = loader; model = rm; try { - modelClass = - Class.forName(model.getEntityTypeClassName(), true, classLoader); + modelClass = Class.forName(model.getEntityTypeClassName(), true, classLoader); } catch (ClassNotFoundException cnfe) { throw new OrmException("Cannot locate model class", cnfe); } @@ -88,8 +86,7 @@ key = model.getPrimaryKey(); if (key == null) { - throw new OrmException("Relation " + rm.getMethodName() - + " has no primary key"); + throw new OrmException("Relation " + rm.getMethodName() + " has no primary key"); } } @@ -187,52 +184,69 @@ private void init() { implClassName = - model.getEntityTypeClassName() + "_Access_" + model.getMethodName() - + "_" + Util.createRandomName(); + model.getEntityTypeClassName() + + "_Access_" + + model.getMethodName() + + "_" + + Util.createRandomName(); implTypeName = implClassName.replace('.', '/'); cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - cw.visit(V1_3, ACC_PUBLIC | ACC_FINAL | ACC_SUPER, implTypeName, null, - accessType.getInternalName(), new String[] {model - .getAccessInterfaceName().replace('.', '/')}); + cw.visit( + V1_3, + ACC_PUBLIC | ACC_FINAL | ACC_SUPER, + implTypeName, + null, + accessType.getInternalName(), + new String[] {model.getAccessInterfaceName().replace('.', '/')}); } private void implementStaticFields() { - cw.visitField(ACC_PRIVATE | ACC_STATIC, F_OBJECT_CODEC, - protobufCodec.getDescriptor(), null, null).visitEnd(); - cw.visitField(ACC_PRIVATE | ACC_STATIC, F_INDEXES, - Type.getType(IndexFunction[].class).getDescriptor(), null, null) + cw.visitField( + ACC_PRIVATE | ACC_STATIC, F_OBJECT_CODEC, protobufCodec.getDescriptor(), null, null) + .visitEnd(); + cw.visitField( + ACC_PRIVATE | ACC_STATIC, + F_INDEXES, + Type.getType(IndexFunction[].class).getDescriptor(), + null, + null) .visitEnd(); for (final QueryModel q : model.getQueries()) { if (needsIndexFunction(q)) { - cw.visitField(ACC_PRIVATE | ACC_STATIC, "index_" + q.getName(), - indexFunction.getDescriptor(), null, null).visitEnd(); + cw.visitField( + ACC_PRIVATE | ACC_STATIC, + "index_" + q.getName(), + indexFunction.getDescriptor(), + null, + null) + .visitEnd(); } } } private void implementConstructor() { final String consName = "<init>"; - final String consDesc = - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {schemaType}); - final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); + final String consDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {schemaType}); + final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); - mv.visitMethodInsn(INVOKESPECIAL, accessType.getInternalName(), consName, - consDesc); + mv.visitMethodInsn(INVOKESPECIAL, accessType.getInternalName(), consName, consDesc); mv.visitInsn(RETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); } - private void implementGetString(final String methodName, - final String returnValue) { + private void implementGetString(final String methodName, final String returnValue) { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, methodName, Type - .getMethodDescriptor(string, new Type[] {}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + methodName, + Type.getMethodDescriptor(string, new Type[] {}), + null, + null); mv.visitCode(); mv.visitLdcInsn(returnValue); mv.visitInsn(ARETURN); @@ -242,8 +256,12 @@ private void implementGetRelationID() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getRelationID", Type - .getMethodDescriptor(Type.INT_TYPE, new Type[] {}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "getRelationID", + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {}), + null, + null); mv.visitCode(); new CodeGenSupport(mv).push(model.getRelationID()); mv.visitInsn(IRETURN); @@ -253,11 +271,14 @@ private void implementGetObjectCodec() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getObjectCodec", Type - .getMethodDescriptor(protobufCodec, new Type[] {}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "getObjectCodec", + Type.getMethodDescriptor(protobufCodec, new Type[] {}), + null, + null); mv.visitCode(); - mv.visitFieldInsn(GETSTATIC, implTypeName, F_OBJECT_CODEC, protobufCodec - .getDescriptor()); + mv.visitFieldInsn(GETSTATIC, implTypeName, F_OBJECT_CODEC, protobufCodec.getDescriptor()); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); @@ -265,12 +286,15 @@ private void implementGetIndexes() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getIndexes", Type - .getMethodDescriptor(Type.getType(IndexFunction[].class), - new Type[] {}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "getIndexes", + Type.getMethodDescriptor(Type.getType(IndexFunction[].class), new Type[] {}), + null, + null); mv.visitCode(); - mv.visitFieldInsn(GETSTATIC, implTypeName, F_INDEXES, Type.getType( - IndexFunction[].class).getDescriptor()); + mv.visitFieldInsn( + GETSTATIC, implTypeName, F_INDEXES, Type.getType(IndexFunction[].class).getDescriptor()); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); @@ -279,12 +303,19 @@ private void implementPrimaryKey() { final ColumnModel f = key.getField(); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "primaryKey", Type - .getMethodDescriptor(ormKey, new Type[] {object}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "primaryKey", + Type.getMethodDescriptor(ormKey, new Type[] {object}), + null, + null); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, entityType.getInternalName()); - mv.visitFieldInsn(GETFIELD, entityType.getInternalName(), f.getFieldName(), + mv.visitFieldInsn( + GETFIELD, + entityType.getInternalName(), + f.getFieldName(), CodeGenSupport.toType(f).getDescriptor()); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); @@ -295,17 +326,19 @@ final List<ColumnModel> pCols = Collections.singletonList(key.getField()); final Type argType = CodeGenSupport.toType(key.getField()); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "encodePrimaryKey", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {indexKeyBuilder, - ormKey}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "encodePrimaryKey", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {indexKeyBuilder, ormKey}), + null, + null); mv.visitCode(); mv.visitVarInsn(ALOAD, 2); mv.visitTypeInsn(CHECKCAST, argType.getInternalName()); mv.visitVarInsn(ASTORE, 2); - final QueryCGS cgs = - new QueryCGS(mv, new Type[] {argType}, pCols, new int[] {2}, 1); + final QueryCGS cgs = new QueryCGS(mv, new Type[] {argType}, pCols, new int[] {2}, 1); for (ColumnModel f : pCols) { IndexFunctionGen.encodeField(new QueryModel.OrderBy(f, false), mv, cgs); } @@ -318,15 +351,21 @@ private void implementKeyQuery(KeyModel key) { final Type keyType = CodeGenSupport.toType(key.getField()); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, key.getName(), Type - .getMethodDescriptor(entityType, new Type[] {keyType}), null, + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + key.getName(), + Type.getMethodDescriptor(entityType, new Type[] {keyType}), + null, new String[] {Type.getType(OrmException.class).getInternalName()}); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); - mv.visitMethodInsn(INVOKESPECIAL, accessType.getInternalName(), "get", Type - .getMethodDescriptor(object, new Type[] {ormKey})); + mv.visitMethodInsn( + INVOKESPECIAL, + accessType.getInternalName(), + "get", + Type.getMethodDescriptor(object, new Type[] {ormKey})); mv.visitTypeInsn(CHECKCAST, entityType.getInternalName()); mv.visitInsn(ARETURN); @@ -352,8 +391,11 @@ } final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, info.getName(), Type - .getMethodDescriptor(resultSet, pTypes), null, + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + info.getName(), + Type.getMethodDescriptor(resultSet, pTypes), + null, new String[] {ormException.getInternalName()}); mv.visitCode(); @@ -364,8 +406,11 @@ final int fromBuf = nextVar++; mv.visitTypeInsn(NEW, indexKeyBuilder.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, indexKeyBuilder.getInternalName(), - "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKESPECIAL, + indexKeyBuilder.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); mv.visitVarInsn(ASTORE, fromBuf); QueryCGS cgs = new QueryCGS(mv, pTypes, pCols, pVars, fromBuf); @@ -376,8 +421,11 @@ final int toBuf = nextVar++; mv.visitTypeInsn(NEW, indexKeyBuilder.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, indexKeyBuilder.getInternalName(), - "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKESPECIAL, + indexKeyBuilder.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); mv.visitVarInsn(ASTORE, toBuf); cgs = new QueryCGS(mv, pTypes, pCols, pVars, toBuf); @@ -388,17 +436,23 @@ // mv.visitVarInsn(ALOAD, 0); if (needsIndexFunction(info)) { - mv.visitFieldInsn(GETSTATIC, implTypeName, "index_" + info.getName(), - indexFunction.getDescriptor()); + mv.visitFieldInsn( + GETSTATIC, implTypeName, "index_" + info.getName(), indexFunction.getDescriptor()); } mv.visitVarInsn(ALOAD, fromBuf); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - "toByteArray", Type.getMethodDescriptor(byteArray, new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + "toByteArray", + Type.getMethodDescriptor(byteArray, new Type[] {})); mv.visitVarInsn(ALOAD, toBuf); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - "toByteArray", Type.getMethodDescriptor(byteArray, new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + "toByteArray", + Type.getMethodDescriptor(byteArray, new Type[] {})); // Set the limit on the number of results. // @@ -417,16 +471,22 @@ cgs.push(info.hasOrderBy() ? 1 : 0); if (needsIndexFunction(info)) { - mv.visitMethodInsn(INVOKEVIRTUAL, accessType.getInternalName(), - "scanIndex", Type.getMethodDescriptor(resultSet, new Type[] { - indexFunction, byteArray, byteArray, Type.INT_TYPE, - Type.BOOLEAN_TYPE})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + accessType.getInternalName(), + "scanIndex", + Type.getMethodDescriptor( + resultSet, + new Type[] {indexFunction, byteArray, byteArray, Type.INT_TYPE, Type.BOOLEAN_TYPE})); } else { // No where and no order by clause? Use the primary key instead. // - mv.visitMethodInsn(INVOKEVIRTUAL, accessType.getInternalName(), - "scanPrimaryKey", Type.getMethodDescriptor(resultSet, new Type[] { - byteArray, byteArray, Type.INT_TYPE, Type.BOOLEAN_TYPE})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + accessType.getInternalName(), + "scanPrimaryKey", + Type.getMethodDescriptor( + resultSet, new Type[] {byteArray, byteArray, Type.INT_TYPE, Type.BOOLEAN_TYPE})); } mv.visitInsn(ARETURN); @@ -438,8 +498,9 @@ return info.hasWhere() || info.hasOrderBy(); } - private void encodeFields(QueryModel qm, List<Tree> query, MethodVisitor mv, - QueryCGS cgs, boolean fromKey) throws OrmException { + private void encodeFields( + QueryModel qm, List<Tree> query, MethodVisitor mv, QueryCGS cgs, boolean fromKey) + throws OrmException { final boolean toKey = !fromKey; Tree lastNode = null; @@ -490,9 +551,13 @@ break; default: - throw new OrmException("Unsupported query token in " - + model.getMethodName() + "." + qm.getName() + ": " - + node.toStringTree()); + throw new OrmException( + "Unsupported query token in " + + model.getMethodName() + + "." + + qm.getName() + + ": " + + node.toStringTree()); } cgs.nextParameter(); @@ -501,13 +566,16 @@ private void checkLastNode(QueryModel qm, Tree lastNode) throws OrmException { if (lastNode != null) { - throw new OrmException(lastNode.getText() + " must be last operator in " - + model.getMethodName() + "." + qm.getName()); + throw new OrmException( + lastNode.getText() + + " must be last operator in " + + model.getMethodName() + + "." + + qm.getName()); } } - private void encodeField(Tree node, MethodVisitor mv, QueryCGS cgs) - throws OrmException { + private void encodeField(Tree node, MethodVisitor mv, QueryCGS cgs) throws OrmException { ColumnModel f = ((QueryParser.Column) node.getChild(0)).getField(); IndexFunctionGen.encodeField(new QueryModel.OrderBy(f, false), mv, cgs); } @@ -520,29 +588,31 @@ switch (node.getType()) { case 0: // nil node used to join other nodes together case QueryParser.WHERE: - case QueryParser.AND: { - List<Tree> res = new ArrayList<>(); - for (int i = 0; i < node.getChildCount(); i++) { - res.addAll(compareOpsOnly(node.getChild(i))); + case QueryParser.AND: + { + List<Tree> res = new ArrayList<>(); + for (int i = 0; i < node.getChildCount(); i++) { + res.addAll(compareOpsOnly(node.getChild(i))); + } + return res; } - return res; - } case QueryParser.GT: case QueryParser.GE: case QueryParser.EQ: case QueryParser.LE: - case QueryParser.LT: { - final Tree lhs = node.getChild(0); - final Tree rhs = node.getChild(1); - if (lhs.getType() != QueryParser.ID) { - throw new OrmException("Unsupported query token"); + case QueryParser.LT: + { + final Tree lhs = node.getChild(0); + final Tree rhs = node.getChild(1); + if (lhs.getType() != QueryParser.ID) { + throw new OrmException("Unsupported query token"); + } + if (rhs.getType() == QueryParser.PLACEHOLDER) { + return Collections.singletonList(node); + } + break; } - if (rhs.getType() == QueryParser.PLACEHOLDER) { - return Collections.singletonList(node); - } - break; - } case QueryParser.ORDER: case QueryParser.LIMIT: @@ -561,8 +631,8 @@ private final int bufvar; private int currentp; - private QueryCGS(MethodVisitor method, Type[] pTypes, - List<ColumnModel> pCols, int[] pVars, int bufvar) { + private QueryCGS( + MethodVisitor method, Type[] pTypes, List<ColumnModel> pCols, int[] pVars, int bufvar) { super(method); this.pTypes = pTypes; this.pCols = pCols;
diff --git a/src/main/java/com/google/gwtorm/nosql/CounterShard.java b/src/main/java/com/google/gwtorm/nosql/CounterShard.java index 4761bce..5c5ccb3 100644 --- a/src/main/java/com/google/gwtorm/nosql/CounterShard.java +++ b/src/main/java/com/google/gwtorm/nosql/CounterShard.java
@@ -20,20 +20,18 @@ /** * A single slice of an incrementing counter. - * <p> - * <b>This shard class is not thread safe.</b> Implementors using this type must - * perform synchronization through external mechanisms such as a row-level lock. - * <p> - * NoSQL implementations can use this object to store counters and keep track of - * their values within {@code nextLong(String)}. To improve allocation - * performance counters may be sliced into shards, with allocation coming out of - * a randomly selected shard, and each shard being replenished from a master - * shard when it {@link #isEmpty()}. + * + * <p><b>This shard class is not thread safe.</b> Implementors using this type must perform + * synchronization through external mechanisms such as a row-level lock. + * + * <p>NoSQL implementations can use this object to store counters and keep track of their values + * within {@code nextLong(String)}. To improve allocation performance counters may be sliced into + * shards, with allocation coming out of a randomly selected shard, and each shard being replenished + * from a master shard when it {@link #isEmpty()}. */ public class CounterShard { /** Standard encoder/decoder for this class. */ - public static final ProtobufCodec<CounterShard> CODEC = - CodecFactory.encoder(CounterShard.class); + public static final ProtobufCodec<CounterShard> CODEC = CodecFactory.encoder(CounterShard.class); /** Current value in this shard, this is the next to assign out. */ @Column(id = 1) @@ -43,8 +41,7 @@ @Column(id = 2) protected long max; - protected CounterShard() { - } + protected CounterShard() {} /** * Create a new shard with a specific starting value, with no maximum. @@ -59,8 +56,8 @@ * Create a new shard with a specific starting point and maximum. * * @param next the first value this shard will hand out. - * @param max the highest value the shard will stop at. The shard will not - * actually hand out this value. + * @param max the highest value the shard will stop at. The shard will not actually hand out this + * value. */ public CounterShard(long next, long max) { this.current = next; @@ -76,8 +73,7 @@ * Obtain the next value from this shard. * * @return the next value - * @throws IllegalStateException the shard {@link #isEmpty()} and cannot hand - * out any more values. + * @throws IllegalStateException the shard {@link #isEmpty()} and cannot hand out any more values. */ public long next() { if (isEmpty()) {
diff --git a/src/main/java/com/google/gwtorm/nosql/IndexFunction.java b/src/main/java/com/google/gwtorm/nosql/IndexFunction.java index edc83b9..951bb70 100644 --- a/src/main/java/com/google/gwtorm/nosql/IndexFunction.java +++ b/src/main/java/com/google/gwtorm/nosql/IndexFunction.java
@@ -16,13 +16,12 @@ /** * A function to produce a NoSQL secondary index key from an object. - * <p> - * An index function computes a row key for a secondary index table by appending - * the relevant values to the builder's internal buffer in the order they are - * referenced in the query. - * <p> - * Typically an IndexFunction is automatically code generated at runtime by - * {@link IndexFunctionGen}. + * + * <p>An index function computes a row key for a secondary index table by appending the relevant + * values to the builder's internal buffer in the order they are referenced in the query. + * + * <p>Typically an IndexFunction is automatically code generated at runtime by {@link + * IndexFunctionGen}. * * @param <T> type of the object the index record references. */ @@ -32,10 +31,10 @@ /** * Should this object exist in the index? - * <p> - * Objects that shouldn't appear in this index are skipped because field - * values are currently {@code null}, or because one or more field values do - * not match the constants used in the query that defines the index. + * + * <p>Objects that shouldn't appear in this index are skipped because field values are currently + * {@code null}, or because one or more field values do not match the constants used in the query + * that defines the index. * * @param object the object to read fields from. * @return true if the object should be indexed by this index.
diff --git a/src/main/java/com/google/gwtorm/nosql/IndexFunctionGen.java b/src/main/java/com/google/gwtorm/nosql/IndexFunctionGen.java index ecded5d..73ab914 100644 --- a/src/main/java/com/google/gwtorm/nosql/IndexFunctionGen.java +++ b/src/main/java/com/google/gwtorm/nosql/IndexFunctionGen.java
@@ -21,14 +21,6 @@ import com.google.gwtorm.server.CodeGenSupport; import com.google.gwtorm.server.GeneratedClassLoader; import com.google.gwtorm.server.OrmException; - -import org.antlr.runtime.tree.Tree; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -36,13 +28,18 @@ import java.util.Iterator; import java.util.List; import java.util.Set; +import org.antlr.runtime.tree.Tree; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; /** Generates {@link IndexFunction} implementations. */ class IndexFunctionGen<T> implements Opcodes { private static final Type string = Type.getType(String.class); private static final Type object = Type.getType(Object.class); - private static final Type indexKeyBuilder = - Type.getType(IndexKeyBuilder.class); + private static final Type indexKeyBuilder = Type.getType(IndexKeyBuilder.class); private final GeneratedClassLoader classLoader; private final QueryModel query; @@ -55,8 +52,7 @@ private String implClassName; private String implTypeName; - IndexFunctionGen(final GeneratedClassLoader loader, final QueryModel qm, - final Class<T> t) { + IndexFunctionGen(final GeneratedClassLoader loader, final QueryModel qm, final Class<T> t) { classLoader = loader; query = qm; @@ -149,21 +145,23 @@ private void init() { superTypeName = Type.getInternalName(IndexFunction.class); implClassName = - pojo.getName() + "_IndexFunction_" + query.getName() + "_" - + Util.createRandomName(); + pojo.getName() + "_IndexFunction_" + query.getName() + "_" + Util.createRandomName(); implTypeName = implClassName.replace('.', '/'); cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - cw.visit(V1_3, ACC_PUBLIC | ACC_FINAL | ACC_SUPER, implTypeName, null, - superTypeName, new String[] {}); + cw.visit( + V1_3, + ACC_PUBLIC | ACC_FINAL | ACC_SUPER, + implTypeName, + null, + superTypeName, + new String[] {}); } private void implementConstructor() { final String consName = "<init>"; - final String consDesc = - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}); - final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); + final String consDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}); + final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); @@ -176,9 +174,12 @@ private void implementGetName() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "getName", Type - .getMethodDescriptor(Type.getType(String.class), new Type[] {}), - null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "getName", + Type.getMethodDescriptor(Type.getType(String.class), new Type[] {}), + null, + null); mv.visitCode(); mv.visitLdcInsn(query.getName()); mv.visitInsn(ARETURN); @@ -188,8 +189,12 @@ private void implementIncludes() throws OrmException { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "includes", Type.getMethodDescriptor( - Type.BOOLEAN_TYPE, new Type[] {object}), null, null); + cw.visitMethod( + ACC_PUBLIC, + "includes", + Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {object}), + null, + null); mv.visitCode(); final IncludeCGS cgs = new IncludeCGS(mv); cgs.setEntityType(pojoType); @@ -219,8 +224,8 @@ mv.visitEnd(); } - private static void checkNotNullFields(Collection<ColumnModel> myFields, - Set<ColumnModel> checked, MethodVisitor mv, IncludeCGS cgs) + private static void checkNotNullFields( + Collection<ColumnModel> myFields, Set<ColumnModel> checked, MethodVisitor mv, IncludeCGS cgs) throws OrmException { for (ColumnModel f : myFields) { if (f.isNested()) { @@ -231,8 +236,8 @@ } } - private static void checkNotNullScalar(MethodVisitor mv, - Set<ColumnModel> checked, IncludeCGS cgs, ColumnModel f) + private static void checkNotNullScalar( + MethodVisitor mv, Set<ColumnModel> checked, IncludeCGS cgs, ColumnModel f) throws OrmException { checkParentNotNull(f.getParent(), checked, mv, cgs); cgs.setFieldReference(f); @@ -247,36 +252,40 @@ break; case Type.ARRAY: - case Type.OBJECT: { - if (f.getPrimitiveType() == byte[].class) { - cgs.pushFieldValue(); - mv.visitJumpInsn(IFNULL, cgs.no); + case Type.OBJECT: + { + if (f.getPrimitiveType() == byte[].class) { + cgs.pushFieldValue(); + mv.visitJumpInsn(IFNULL, cgs.no); - } else if (f.getPrimitiveType() == String.class) { - cgs.pushFieldValue(); - mv.visitJumpInsn(IFNULL, cgs.no); + } else if (f.getPrimitiveType() == String.class) { + cgs.pushFieldValue(); + mv.visitJumpInsn(IFNULL, cgs.no); - } else if (f.getPrimitiveType() == java.sql.Timestamp.class - || f.getPrimitiveType() == java.util.Date.class - || f.getPrimitiveType() == java.sql.Date.class) { - cgs.pushFieldValue(); - mv.visitJumpInsn(IFNULL, cgs.no); + } else if (f.getPrimitiveType() == java.sql.Timestamp.class + || f.getPrimitiveType() == java.util.Date.class + || f.getPrimitiveType() == java.sql.Date.class) { + cgs.pushFieldValue(); + mv.visitJumpInsn(IFNULL, cgs.no); - } else { - throw new OrmException("Type " + f.getPrimitiveType() - + " not supported for field " + f.getPathToFieldName()); + } else { + throw new OrmException( + "Type " + + f.getPrimitiveType() + + " not supported for field " + + f.getPathToFieldName()); + } + break; } - break; - } default: - throw new OrmException("Type " + f.getPrimitiveType() - + " not supported for field " + f.getPathToFieldName()); + throw new OrmException( + "Type " + f.getPrimitiveType() + " not supported for field " + f.getPathToFieldName()); } } - private static void checkParentNotNull(ColumnModel f, - Set<ColumnModel> checked, MethodVisitor mv, IncludeCGS cgs) { + private static void checkParentNotNull( + ColumnModel f, Set<ColumnModel> checked, MethodVisitor mv, IncludeCGS cgs) { if (f != null && checked.add(f)) { checkParentNotNull(f.getParent(), checked, mv, cgs); cgs.setFieldReference(f); @@ -285,10 +294,9 @@ } } - private void checkConstants(Tree node, MethodVisitor mv, IncludeCGS cgs) - throws OrmException { + private void checkConstants(Tree node, MethodVisitor mv, IncludeCGS cgs) throws OrmException { switch (node.getType()) { - // These don't impact the constant evaluation + // These don't impact the constant evaluation case QueryParser.ORDER: case QueryParser.LIMIT: break; @@ -305,52 +313,55 @@ case QueryParser.LE: case QueryParser.GT: case QueryParser.GE: - case QueryParser.EQ: { - final Tree lhs = node.getChild(0); - final Tree rhs = node.getChild(1); - if (lhs.getType() != QueryParser.ID) { - throw new OrmException("Unsupported query token"); - } + case QueryParser.EQ: + { + final Tree lhs = node.getChild(0); + final Tree rhs = node.getChild(1); + if (lhs.getType() != QueryParser.ID) { + throw new OrmException("Unsupported query token"); + } - cgs.setFieldReference(((QueryParser.Column) lhs).getField()); - switch (rhs.getType()) { - case QueryParser.PLACEHOLDER: - // Parameter evaluated at runtime - break; + cgs.setFieldReference(((QueryParser.Column) lhs).getField()); + switch (rhs.getType()) { + case QueryParser.PLACEHOLDER: + // Parameter evaluated at runtime + break; - case QueryParser.TRUE: - cgs.pushFieldValue(); - mv.visitJumpInsn(IFEQ, cgs.no); - break; - - case QueryParser.FALSE: - cgs.pushFieldValue(); - mv.visitJumpInsn(IFNE, cgs.no); - break; - - case QueryParser.CONSTANT_INTEGER: - cgs.pushFieldValue(); - cgs.push(Integer.parseInt(rhs.getText())); - mv.visitJumpInsn(IF_ICMPNE, cgs.no); - break; - - case QueryParser.CONSTANT_STRING: - if (cgs.getFieldReference().getPrimitiveType() == Character.TYPE) { - cgs.push(dequote(rhs.getText()).charAt(0)); + case QueryParser.TRUE: cgs.pushFieldValue(); - mv.visitJumpInsn(IF_ICMPNE, cgs.no); - } else { - mv.visitLdcInsn(dequote(rhs.getText())); - cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, string.getInternalName(), - "equals", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, - new Type[] {object})); mv.visitJumpInsn(IFEQ, cgs.no); - } - break; + break; + + case QueryParser.FALSE: + cgs.pushFieldValue(); + mv.visitJumpInsn(IFNE, cgs.no); + break; + + case QueryParser.CONSTANT_INTEGER: + cgs.pushFieldValue(); + cgs.push(Integer.parseInt(rhs.getText())); + mv.visitJumpInsn(IF_ICMPNE, cgs.no); + break; + + case QueryParser.CONSTANT_STRING: + if (cgs.getFieldReference().getPrimitiveType() == Character.TYPE) { + cgs.push(dequote(rhs.getText()).charAt(0)); + cgs.pushFieldValue(); + mv.visitJumpInsn(IF_ICMPNE, cgs.no); + } else { + mv.visitLdcInsn(dequote(rhs.getText())); + cgs.pushFieldValue(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + string.getInternalName(), + "equals", + Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {object})); + mv.visitJumpInsn(IFEQ, cgs.no); + } + break; + } + break; } - break; - } default: throw new OrmException("Unsupported query token " + node.toStringTree()); @@ -363,8 +374,12 @@ private void implementEncode() throws OrmException { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "encode", Type.getMethodDescriptor( - Type.VOID_TYPE, new Type[] {indexKeyBuilder, object}), null, null); + cw.visitMethod( + ACC_PUBLIC, + "encode", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {indexKeyBuilder, object}), + null, + null); mv.visitCode(); final EncodeCGS cgs = new EncodeCGS(mv); cgs.setEntityType(pojoType); @@ -380,8 +395,9 @@ mv.visitEnd(); } - static void encodeFields(Collection<QueryModel.OrderBy> myFields, - final MethodVisitor mv, final EncodeCGS cgs) throws OrmException { + static void encodeFields( + Collection<QueryModel.OrderBy> myFields, final MethodVisitor mv, final EncodeCGS cgs) + throws OrmException { Iterator<QueryModel.OrderBy> i = myFields.iterator(); while (i.hasNext()) { QueryModel.OrderBy f = i.next(); @@ -392,8 +408,8 @@ } } - static void encodeField(QueryModel.OrderBy f, final MethodVisitor mv, - final EncodeCGS cgs) throws OrmException { + static void encodeField(QueryModel.OrderBy f, final MethodVisitor mv, final EncodeCGS cgs) + throws OrmException { if (f.column.isNested()) { encodeFields(orderByLeaves(Collections.singletonList(f)), mv, cgs); } else { @@ -401,8 +417,8 @@ } } - private static void encodeScalar(QueryModel.OrderBy f, final MethodVisitor mv, - final EncodeCGS cgs) throws OrmException { + private static void encodeScalar( + QueryModel.OrderBy f, final MethodVisitor mv, final EncodeCGS cgs) throws OrmException { String method = f.descending ? "desc" : "add"; ColumnModel c = f.column; cgs.setFieldReference(c); @@ -416,56 +432,73 @@ cgs.pushBuilder(); cgs.pushFieldValue(); mv.visitInsn(I2L); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - method, Type.getMethodDescriptor(Type.VOID_TYPE, - new Type[] {Type.LONG_TYPE})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + method, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.LONG_TYPE})); break; case Type.LONG: cgs.pushBuilder(); cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - method, Type.getMethodDescriptor(Type.VOID_TYPE, - new Type[] {Type.LONG_TYPE})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + method, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.LONG_TYPE})); break; case Type.ARRAY: - case Type.OBJECT: { - if (c.getPrimitiveType() == byte[].class) { - cgs.pushBuilder(); - cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - method, Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type - .getType(byte[].class)})); + case Type.OBJECT: + { + if (c.getPrimitiveType() == byte[].class) { + cgs.pushBuilder(); + cgs.pushFieldValue(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + method, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.getType(byte[].class)})); - } else if (c.getPrimitiveType() == String.class) { - cgs.pushBuilder(); - cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - method, Type.getMethodDescriptor(Type.VOID_TYPE, - new Type[] {string})); + } else if (c.getPrimitiveType() == String.class) { + cgs.pushBuilder(); + cgs.pushFieldValue(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + method, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {string})); - } else if (c.getPrimitiveType() == java.sql.Timestamp.class - || c.getPrimitiveType() == java.util.Date.class - || c.getPrimitiveType() == java.sql.Date.class) { - cgs.pushBuilder(); - cgs.pushFieldValue(); - String tsType = Type.getType(c.getPrimitiveType()).getInternalName(); - mv.visitMethodInsn(INVOKEVIRTUAL, tsType, "getTime", Type - .getMethodDescriptor(Type.LONG_TYPE, new Type[] {})); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - method, Type.getMethodDescriptor(Type.VOID_TYPE, - new Type[] {Type.LONG_TYPE})); - } else { - throw new OrmException("Type " + c.getPrimitiveType() - + " not supported for field " + c.getPathToFieldName()); + } else if (c.getPrimitiveType() == java.sql.Timestamp.class + || c.getPrimitiveType() == java.util.Date.class + || c.getPrimitiveType() == java.sql.Date.class) { + cgs.pushBuilder(); + cgs.pushFieldValue(); + String tsType = Type.getType(c.getPrimitiveType()).getInternalName(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + tsType, + "getTime", + Type.getMethodDescriptor(Type.LONG_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + method, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.LONG_TYPE})); + } else { + throw new OrmException( + "Type " + + c.getPrimitiveType() + + " not supported for field " + + c.getPathToFieldName()); + } + break; } - break; - } default: - throw new OrmException("Type " + c.getPrimitiveType() - + " not supported for field " + c.getPathToFieldName()); + throw new OrmException( + "Type " + c.getPrimitiveType() + " not supported for field " + c.getPathToFieldName()); } } @@ -489,20 +522,29 @@ void infinity() { pushBuilder(); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - "infinity", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + "infinity", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); } void delimiter() { pushBuilder(); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - "delimiter", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + "delimiter", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); } void nul() { pushBuilder(); - mv.visitMethodInsn(INVOKEVIRTUAL, indexKeyBuilder.getInternalName(), - "nul", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + indexKeyBuilder.getInternalName(), + "nul", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); } void pushBuilder() {
diff --git a/src/main/java/com/google/gwtorm/nosql/IndexKeyBuilder.java b/src/main/java/com/google/gwtorm/nosql/IndexKeyBuilder.java index 2bed6ce..6df8866 100644 --- a/src/main/java/com/google/gwtorm/nosql/IndexKeyBuilder.java +++ b/src/main/java/com/google/gwtorm/nosql/IndexKeyBuilder.java
@@ -14,46 +14,41 @@ package com.google.gwtorm.nosql; - import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; /** * Encoder support for {@link IndexFunction} computed strings. - * <p> - * This class provides a string that may contain multiple values, using - * delimiters between fields and big-endian encoded numerics. Sorting the - * resulting strings using unsigned byte orderings produces a stable sorting. - * <p> - * The encoding used by this class relies on having 258 tokens. To get the extra - * 2 tokens within a 256 byte range, escapes are used according to the following - * simple table: + * + * <p>This class provides a string that may contain multiple values, using delimiters between fields + * and big-endian encoded numerics. Sorting the resulting strings using unsigned byte orderings + * produces a stable sorting. + * + * <p>The encoding used by this class relies on having 258 tokens. To get the extra 2 tokens within + * a 256 byte range, escapes are used according to the following simple table: + * * <ul> - * <li>delimiter = \x00\x01 - * <li>byte \x00 = \x00\xff - * <li>byte \xff = \xff\x00 - * <li>infinity = \xff\xff + * <li>delimiter = \x00\x01 + * <li>byte \x00 = \x00\xff + * <li>byte \xff = \xff\x00 + * <li>infinity = \xff\xff * </ul> - * <p> - * Integers are encoded as variable length big-endian values, skipping leading - * zero bytes, prefixed by the number of bytes used to encode them. Therefore 0 - * is encoded as "\x00", and 256 is encoded as "\x02\x01\x00". Negative values - * are encoded in their twos complement encoding and therefore sort after the - * maximum positive value. - * <p> - * Strings and byte arrays supplied by the caller have their \x00 and \xff - * values escaped according to the table above, but are otherwise written as-is - * without a length prefix. - * <p> - * Callers are responsible for inserting {@link #delimiter()} markers at the - * appropriate positions in the sequence. + * + * <p>Integers are encoded as variable length big-endian values, skipping leading zero bytes, + * prefixed by the number of bytes used to encode them. Therefore 0 is encoded as "\x00", and 256 is + * encoded as "\x02\x01\x00". Negative values are encoded in their twos complement encoding and + * therefore sort after the maximum positive value. + * + * <p>Strings and byte arrays supplied by the caller have their \x00 and \xff values escaped + * according to the table above, but are otherwise written as-is without a length prefix. + * + * <p>Callers are responsible for inserting {@link #delimiter()} markers at the appropriate + * positions in the sequence. */ public class IndexKeyBuilder { private final ByteArrayOutputStream buf = new ByteArrayOutputStream(); - /** - * Add a delimiter marker to the string. - */ + /** Add a delimiter marker to the string. */ public void delimiter() { buf.write(0x00); buf.write(0x01); @@ -61,8 +56,8 @@ /** * Add the special infinity symbol to the string. - * <p> - * The infinity symbol sorts after all other values in the same position. + * + * <p>The infinity symbol sorts after all other values in the same position. */ public void infinity() { buf.write(0xff); @@ -71,9 +66,8 @@ /** * Add \0 to the string. - * <p> - * \0 can be used during searches to enforce greater then or less then clauses - * in a query. + * + * <p>\0 can be used during searches to enforce greater then or less then clauses in a query. */ public void nul() { buf.write(0x00); @@ -81,9 +75,9 @@ /** * Add a raw sequence of bytes. - * <p> - * The bytes 0x00 and 0xff are escaped by this method according to the - * encoding table described in the class documentation. + * + * <p>The bytes 0x00 and 0xff are escaped by this method according to the encoding table described + * in the class documentation. * * @param bin array to copy from. * @param pos first index to copy. @@ -125,9 +119,9 @@ /** * Add a raw sequence of bytes. - * <p> - * The bytes 0x00 and 0xff are escaped by this method according to the - * encoding table described in the class documentation. + * + * <p>The bytes 0x00 and 0xff are escaped by this method according to the encoding table described + * in the class documentation. * * @param bin the complete array to copy. */ @@ -204,9 +198,9 @@ /** * Add a byte array as-is, without escaping. - * <p> - * This should only be used the byte array came from a prior index key and the - * caller is trying to create a new key with this key embedded at the end. + * + * <p>This should only be used the byte array came from a prior index key and the caller is trying + * to create a new key with this key embedded at the end. * * @param bin the binary to append as-is, without further escaping. */
diff --git a/src/main/java/com/google/gwtorm/nosql/IndexRow.java b/src/main/java/com/google/gwtorm/nosql/IndexRow.java index 4986e3a..b4fa059 100644 --- a/src/main/java/com/google/gwtorm/nosql/IndexRow.java +++ b/src/main/java/com/google/gwtorm/nosql/IndexRow.java
@@ -20,20 +20,17 @@ /** * Data value stored in a NoSQL secondary index row. - * <p> - * Instances of this object can be used inside of the data portion of a - * secondary index row, and may either contain the key of the primary data row, - * or a copy of the primary object data. - * <p> - * The {@link #timestamp} field can be used to fossil collect secondary index - * rows that no longer match the primary data row and which are older than the - * longest expected transaction. These fossil rows may have occurred due to an - * aborted, but partially applied transaction. + * + * <p>Instances of this object can be used inside of the data portion of a secondary index row, and + * may either contain the key of the primary data row, or a copy of the primary object data. + * + * <p>The {@link #timestamp} field can be used to fossil collect secondary index rows that no longer + * match the primary data row and which are older than the longest expected transaction. These + * fossil rows may have occurred due to an aborted, but partially applied transaction. */ public class IndexRow { /** Standard encoder/decoder for this class. */ - public static final ProtobufCodec<IndexRow> CODEC = - CodecFactory.encoder(IndexRow.class); + public static final ProtobufCodec<IndexRow> CODEC = CodecFactory.encoder(IndexRow.class); /** * Create an index row to reference the primary data row by key. @@ -51,9 +48,9 @@ /** * Clock of the last time this index row was touched. - * <p> - * Invalid rows older than a certain time interval may be subject to automatic - * background pruning during data retrieval operations. + * + * <p>Invalid rows older than a certain time interval may be subject to automatic background + * pruning during data retrieval operations. */ @Column(id = 1) protected long timestamp;
diff --git a/src/main/java/com/google/gwtorm/nosql/NoSqlAccess.java b/src/main/java/com/google/gwtorm/nosql/NoSqlAccess.java index 9ca1423..c43deaf 100644 --- a/src/main/java/com/google/gwtorm/nosql/NoSqlAccess.java +++ b/src/main/java/com/google/gwtorm/nosql/NoSqlAccess.java
@@ -22,53 +22,51 @@ import com.google.gwtorm.server.ResultSet; /** Internal base class for implementations of {@link Access}. */ -public abstract class NoSqlAccess<T, K extends Key<?>> extends - AbstractAccess<T, K> { - protected NoSqlAccess(final NoSqlSchema s) { - } +public abstract class NoSqlAccess<T, K extends Key<?>> extends AbstractAccess<T, K> { + protected NoSqlAccess(final NoSqlSchema s) {} /** * Scan a range of keys from the data rows and return any matching objects. - * <p> - * All NoSQL implementations must provide their own variant of this method. - * <p> - * To fetch a single record with a scan, set {@code toKey} to the same array - * as {@code fromKey}, but append a trailing NUL byte (0x00). The caller - * should validate that the returned ResultSet contains no more than 1 row. + * + * <p>All NoSQL implementations must provide their own variant of this method. + * + * <p>To fetch a single record with a scan, set {@code toKey} to the same array as {@code + * fromKey}, but append a trailing NUL byte (0x00). The caller should validate that the returned + * ResultSet contains no more than 1 row. * * @param fromKey key to start the scan on. This is inclusive. * @param toKey key to stop the scan on. This is exclusive. * @param limit maximum number of results to return, 0 for unlimited. - * @param order if true the order will be preserved, false if the result order - * order can be arbitrary. - * @return result set for the requested range. The result set may be lazily - * filled, or filled completely. + * @param order if true the order will be preserved, false if the result order order can be + * arbitrary. + * @return result set for the requested range. The result set may be lazily filled, or filled + * completely. * @throws OrmException an error occurred preventing the scan from completing. */ - protected abstract ResultSet<T> scanPrimaryKey(byte[] fromKey, byte[] toKey, - int limit, boolean order) throws OrmException; + protected abstract ResultSet<T> scanPrimaryKey( + byte[] fromKey, byte[] toKey, int limit, boolean order) throws OrmException; /** * Scan a range of keys and return any matching objects. - * <p> - * All NoSQL implementations must provide their own variant of this method. - * <p> - * To fetch a single record with a scan, set {@code toKey} to the same array - * as {@code fromKey}, but append a trailing NUL byte (0x00). The caller - * should validate that the returned ResultSet contains no more than 1 row. + * + * <p>All NoSQL implementations must provide their own variant of this method. + * + * <p>To fetch a single record with a scan, set {@code toKey} to the same array as {@code + * fromKey}, but append a trailing NUL byte (0x00). The caller should validate that the returned + * ResultSet contains no more than 1 row. * * @param index definition of the index the scan occurs over. * @param fromKey key to start the scan on. This is inclusive. * @param toKey key to stop the scan on. This is exclusive. * @param limit maximum number of results to return, 0 for unlimited. - * @param order if true the order will be preserved, false if the result order - * order can be arbitrary. - * @return result set for the requested range. The result set may be lazily - * filled, or filled completely. + * @param order if true the order will be preserved, false if the result order order can be + * arbitrary. + * @return result set for the requested range. The result set may be lazily filled, or filled + * completely. * @throws OrmException an error occurred preventing the scan from completing. */ - protected abstract ResultSet<T> scanIndex(IndexFunction<T> index, - byte[] fromKey, byte[] toKey, int limit, boolean order) + protected abstract ResultSet<T> scanIndex( + IndexFunction<T> index, byte[] fromKey, byte[] toKey, int limit, boolean order) throws OrmException; // -- These are all provided by AccessGen when it builds a subclass -- @@ -78,10 +76,9 @@ /** * Get the indexes that support query functions. - * <p> - * This array may be a subset of the total query functions. This can occur - * when two or more queries can be efficiently answered by performing a range - * scan over the same index. + * + * <p>This array may be a subset of the total query functions. This can occur when two or more + * queries can be efficiently answered by performing a range scan over the same index. * * @return indexes needed to support queries. */
diff --git a/src/main/java/com/google/gwtorm/nosql/NoSqlDatabase.java b/src/main/java/com/google/gwtorm/nosql/NoSqlDatabase.java index 927df32..414e297 100644 --- a/src/main/java/com/google/gwtorm/nosql/NoSqlDatabase.java +++ b/src/main/java/com/google/gwtorm/nosql/NoSqlDatabase.java
@@ -28,20 +28,19 @@ /** * Base class for NoSQL typed databases. - * <p> - * Applications should use the database class to create instances of their - * Schema extension interface, and thus open and connect to the data store. - * <p> - * Creating a new database instance is expensive, due to the type analysis and - * code generation performed to implement the Schema and Access interfaces. - * Applications should create and cache their database instance for the life of - * the application. - * <p> - * Database instances are thread-safe, but returned Schema instances are not. - * <p> - * This class must be further extended by the NoSQL implementation to configure - * the connectivity with the data store and supply the correct subclass of - * {@link NoSqlSchema} that knows how to interact with the data store. + * + * <p>Applications should use the database class to create instances of their Schema extension + * interface, and thus open and connect to the data store. + * + * <p>Creating a new database instance is expensive, due to the type analysis and code generation + * performed to implement the Schema and Access interfaces. Applications should create and cache + * their database instance for the life of the application. + * + * <p>Database instances are thread-safe, but returned Schema instances are not. + * + * <p>This class must be further extended by the NoSQL implementation to configure the connectivity + * with the data store and supply the correct subclass of {@link NoSqlSchema} that knows how to + * interact with the data store. * * @param <T> type of the application's Schema. * @param <S> type of the implementation's base for Schema implementations. @@ -60,18 +59,17 @@ /** * Initialize a new database and generate the implementation. * - * @param schemaBaseType class that the generated Schema implementation should - * extend in order to provide data store connectivity. - * @param accessBaseType class that the generated Access implementations - * should extend in order to provide single-relation access for each - * schema instance. - * @param appSchema the application schema interface that must be implemented - * and constructed on demand. - * @throws OrmException the schema cannot be created because of an annotation - * error in the interface definitions. + * @param schemaBaseType class that the generated Schema implementation should extend in order to + * provide data store connectivity. + * @param accessBaseType class that the generated Access implementations should extend in order to + * provide single-relation access for each schema instance. + * @param appSchema the application schema interface that must be implemented and constructed on + * demand. + * @throws OrmException the schema cannot be created because of an annotation error in the + * interface definitions. */ - protected NoSqlDatabase(final Class<S> schemaBaseType, - final Class<A> accessBaseType, final Class<T> appSchema) + protected NoSqlDatabase( + final Class<S> schemaBaseType, final Class<A> accessBaseType, final Class<T> appSchema) throws OrmException { schemaModel = new JavaSchemaModel(appSchema); final GeneratedClassLoader loader = newLoader(appSchema); @@ -90,18 +88,24 @@ } @SuppressWarnings("unchecked") - private Class<T> generate(final Class<S> schemaBaseType, - final Class<A> accessBaseType, final GeneratedClassLoader loader) + private Class<T> generate( + final Class<S> schemaBaseType, + final Class<A> accessBaseType, + final GeneratedClassLoader loader) throws OrmException { - return new SchemaGen(loader, schemaModel, getClass(), schemaBaseType, - new SchemaGen.AccessGenerator() { - @Override - public Class<?> create(GeneratedClassLoader loader, RelationModel rm) - throws OrmException { - return new AccessGen(loader, rm, schemaBaseType, accessBaseType) - .create(); - } - }).create(); + return new SchemaGen( + loader, + schemaModel, + getClass(), + schemaBaseType, + new SchemaGen.AccessGenerator() { + @Override + public Class<?> create(GeneratedClassLoader loader, RelationModel rm) + throws OrmException { + return new AccessGen(loader, rm, schemaBaseType, accessBaseType).create(); + } + }) + .create(); } private static <T> GeneratedClassLoader newLoader(final Class<T> schema) {
diff --git a/src/main/java/com/google/gwtorm/nosql/NoSqlSchema.java b/src/main/java/com/google/gwtorm/nosql/NoSqlSchema.java index 349f5b5..f6203d1 100644 --- a/src/main/java/com/google/gwtorm/nosql/NoSqlSchema.java +++ b/src/main/java/com/google/gwtorm/nosql/NoSqlSchema.java
@@ -21,8 +21,7 @@ /** Internal base class for implementations of {@link Schema}. */ public abstract class NoSqlSchema extends AbstractSchema { - protected NoSqlSchema(final NoSqlDatabase<?, ?, ?> d) { - } + protected NoSqlSchema(final NoSqlDatabase<?, ?, ?> d) {} @Override public void pruneSchema(StatementExecutor e) throws OrmException {
diff --git a/src/main/java/com/google/gwtorm/nosql/RelationCodec.java b/src/main/java/com/google/gwtorm/nosql/RelationCodec.java index 84add28..d2585a6 100644 --- a/src/main/java/com/google/gwtorm/nosql/RelationCodec.java +++ b/src/main/java/com/google/gwtorm/nosql/RelationCodec.java
@@ -19,7 +19,6 @@ import com.google.protobuf.CodedOutputStream; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.WireFormat; - import java.io.EOFException; import java.io.IOException; @@ -28,10 +27,9 @@ /** * Pop the field number from the stream and return it. * - * @param in the stream to pop the field number from. The caller is - * responsible for making sure the underlying stream had a mark set for - * at least 8 bytes so the tag can be examined, reset, and later read - * again during mergeFrom or decode. + * @param in the stream to pop the field number from. The caller is responsible for making sure + * the underlying stream had a mark set for at least 8 bytes so the tag can be examined, + * reset, and later read again during mergeFrom or decode. * @return the field number of the relation. * @throws IOException the stream cannot be read. */ @@ -71,7 +69,7 @@ @Override public void mergeFrom(CodedInputStream in, T obj) throws IOException { boolean found = false; - for (;;) { + for (; ; ) { int tag = in.readTag(); if (tag == 0) { if (found) { @@ -91,8 +89,8 @@ in.popLimit(oldLimit); found = true; } else { - throw new InvalidProtocolBufferException("Field " + fieldId - + " should be length delimited (wire type 2)"); + throw new InvalidProtocolBufferException( + "Field " + fieldId + " should be length delimited (wire type 2)"); } } else { in.skipField(tag);
diff --git a/src/main/java/com/google/gwtorm/nosql/generic/GenericAccess.java b/src/main/java/com/google/gwtorm/nosql/generic/GenericAccess.java index ecfef33..fe2b3bd 100644 --- a/src/main/java/com/google/gwtorm/nosql/generic/GenericAccess.java +++ b/src/main/java/com/google/gwtorm/nosql/generic/GenericAccess.java
@@ -28,7 +28,6 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.ResultSet; import com.google.protobuf.ByteString; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -38,8 +37,7 @@ import java.util.Map.Entry; /** Base implementation for {@link Access} in a {@link GenericDatabase}. */ -public abstract class GenericAccess<T, K extends Key<?>> extends - NoSqlAccess<T, K> { +public abstract class GenericAccess<T, K extends Key<?>> extends NoSqlAccess<T, K> { /** Maximum number of results to cache to improve updates on upsert. */ private static final int MAX_SZ = 64; @@ -54,12 +52,13 @@ @SuppressWarnings("serial") protected LinkedHashMap<K, byte[]> cache() { if (cache == null) { - cache = new LinkedHashMap<K, byte[]>(8) { - @Override - protected boolean removeEldestEntry(Entry<K, byte[]> entry) { - return MAX_SZ <= size(); - } - }; + cache = + new LinkedHashMap<K, byte[]>(8) { + @Override + protected boolean removeEldestEntry(Entry<K, byte[]> entry) { + return MAX_SZ <= size(); + } + }; } return cache; } @@ -70,8 +69,7 @@ * @param key the primary key instance; must not be null. * @return the entity; null if no entity has this key. * @throws OrmException the data lookup failed. - * @throws OrmDuplicateKeyException more than one row was identified in the - * key scan. + * @throws OrmDuplicateKeyException more than one row was identified in the key scan. */ @Override public T get(K key) throws OrmException, OrmDuplicateKeyException { @@ -87,29 +85,31 @@ @Override public ResultSet<T> get(final Iterable<K> keys) throws OrmException { - final ResultSet<Row> rs = db.fetchRows(new Iterable<byte[]>() { - @Override - public Iterator<byte[]> iterator() { - return new Iterator<byte[]>() { - private final Iterator<K> i = keys.iterator(); + final ResultSet<Row> rs = + db.fetchRows( + new Iterable<byte[]>() { + @Override + public Iterator<byte[]> iterator() { + return new Iterator<byte[]>() { + private final Iterator<K> i = keys.iterator(); - @Override - public boolean hasNext() { - return i.hasNext(); - } + @Override + public boolean hasNext() { + return i.hasNext(); + } - @Override - public byte[] next() { - return dataRowKey(i.next()); - } + @Override + public byte[] next() { + return dataRowKey(i.next()); + } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - }); + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }); final Iterator<Row> i = rs.iterator(); return new AbstractResultSet<T>() { @@ -139,15 +139,15 @@ * @param fromKey key to start the scan on. This is inclusive. * @param toKey key to stop the scan on. This is exclusive. * @param limit maximum number of results to return. - * @param order if true the order will be preserved, false if the result order - * order can be arbitrary. - * @return result set for the requested range. The result set may be lazily - * filled, or filled completely. + * @param order if true the order will be preserved, false if the result order order can be + * arbitrary. + * @return result set for the requested range. The result set may be lazily filled, or filled + * completely. * @throws OrmException an error occurred preventing the scan from completing. */ @Override - protected ResultSet<T> scanPrimaryKey(byte[] fromKey, byte[] toKey, - int limit, boolean order) throws OrmException { + protected ResultSet<T> scanPrimaryKey(byte[] fromKey, byte[] toKey, int limit, boolean order) + throws OrmException { IndexKeyBuilder b; b = new IndexKeyBuilder(); @@ -193,15 +193,16 @@ * @param fromKey key to start the scan on. This is inclusive. * @param toKey key to stop the scan on. This is exclusive. * @param limit maximum number of results to return. - * @param order if true the order will be preserved, false if the result order - * order can be arbitrary. - * @return result set for the requested range. The result set may be lazily - * filled, or filled completely. + * @param order if true the order will be preserved, false if the result order order can be + * arbitrary. + * @return result set for the requested range. The result set may be lazily filled, or filled + * completely. * @throws OrmException an error occurred preventing the scan from completing. */ @Override - protected ResultSet<T> scanIndex(IndexFunction<T> idx, byte[] fromKey, - byte[] toKey, int limit, boolean order) throws OrmException { + protected ResultSet<T> scanIndex( + IndexFunction<T> idx, byte[] fromKey, byte[] toKey, int limit, boolean order) + throws OrmException { final long now = System.currentTimeMillis(); IndexKeyBuilder b; @@ -224,7 +225,8 @@ final ArrayList<T> res = new ArrayList<>(); byte[] lastKey = fromKey; - SCAN: for (;;) { + SCAN: + for (; ; ) { List<CandidateRow> scanned; if (0 < limit) { scanned = new ArrayList<>(limit); @@ -275,7 +277,9 @@ // drop the row out of the index. // if (!idxRow.hasData()) { - db.maybeFossilCollectIndexRow(now, idxRow.getIndexKey(), // + db.maybeFossilCollectIndexRow( + now, + idxRow.getIndexKey(), // idxRow.getIndexRow()); continue; } @@ -293,7 +297,9 @@ break SCAN; } } else { - db.maybeFossilCollectIndexRow(now, idxRow.getIndexKey(), // + db.maybeFossilCollectIndexRow( + now, + idxRow.getIndexKey(), // idxRow.getIndexRow()); } } @@ -387,15 +393,14 @@ /** * Insert secondary index rows for an object about to be written. - * <p> - * Insert or update operations should invoke this method before the main data - * row is written, allowing the secondary index rows to be put into the data - * store before the main data row arrives. Compatible scan implementations - * (such as {@link #scanIndex(IndexFunction, byte[], byte[], int, boolean)} - * above) will ignore these rows for a short time period. * - * @param oldObj an old copy of the object; if non-null this may be used to - * avoid writing unnecessary secondary index rows that already exist. + * <p>Insert or update operations should invoke this method before the main data row is written, + * allowing the secondary index rows to be put into the data store before the main data row + * arrives. Compatible scan implementations (such as {@link #scanIndex(IndexFunction, byte[], + * byte[], int, boolean)} above) will ignore these rows for a short time period. + * + * @param oldObj an old copy of the object; if non-null this may be used to avoid writing + * unnecessary secondary index rows that already exist. * @param newObj the new (or updated) object being stored. Must not be null. * @throws OrmException the data store is unable to update an index row. */ @@ -414,11 +419,10 @@ /** * Remove old secondary index rows that are no longer valid for an object. * - * @param oldObj an old copy of the object, prior to the current update taking - * place. If null the method does nothing and simply returns. - * @param newObj the new copy of the object. Index rows that are still valid - * for {@code #newObj} are left alone. If null, all index rows for - * {@code oldObj} are removed. + * @param oldObj an old copy of the object, prior to the current update taking place. If null the + * method does nothing and simply returns. + * @param newObj the new copy of the object. Index rows that are still valid for {@code #newObj} + * are left alone. If null, all index rows for {@code oldObj} are removed. * @throws OrmException the data store is unable to remove an index row. */ protected void pruneOldIndexes(final T oldObj, T newObj) throws OrmException { @@ -445,8 +449,7 @@ } @Override - public T atomicUpdate(K key, final AtomicUpdate<T> update) - throws OrmException { + public T atomicUpdate(K key, final AtomicUpdate<T> update) throws OrmException { final IndexKeyBuilder b = new IndexKeyBuilder(); b.add(getRelationName()); b.delimiter(); @@ -455,28 +458,30 @@ try { @SuppressWarnings("unchecked") final T[] res = (T[]) new Object[3]; - db.atomicUpdate(b.toByteArray(), new AtomicUpdate<byte[]>() { - @Override - public byte[] update(byte[] data) { - if (data != null) { - final T oldObj = getObjectCodec().decode(data); - final T newObj = getObjectCodec().decode(data); - res[0] = update.update(newObj); - res[1] = oldObj; - res[2] = newObj; - try { - writeNewIndexes(oldObj, newObj); - } catch (OrmException err) { - throw new IndexException(err); - } - return getObjectCodec().encodeToByteString(newObj).toByteArray(); + db.atomicUpdate( + b.toByteArray(), + new AtomicUpdate<byte[]>() { + @Override + public byte[] update(byte[] data) { + if (data != null) { + final T oldObj = getObjectCodec().decode(data); + final T newObj = getObjectCodec().decode(data); + res[0] = update.update(newObj); + res[1] = oldObj; + res[2] = newObj; + try { + writeNewIndexes(oldObj, newObj); + } catch (OrmException err) { + throw new IndexException(err); + } + return getObjectCodec().encodeToByteString(newObj).toByteArray(); - } else { - res[0] = null; - return null; - } - } - }); + } else { + res[0] = null; + return null; + } + } + }); if (res[0] != null) { pruneOldIndexes(res[1], res[2]); } @@ -488,10 +493,10 @@ /** * Determine if an object still matches the index row. - * <p> - * This method checks that the object's fields still match the criteria - * necessary for it to be part of the index defined by {@code f}. It also - * formats the index key and validates it is still identical to {@code exp}. + * + * <p>This method checks that the object's fields still match the criteria necessary for it to be + * part of the index defined by {@code f}. It also formats the index key and validates it is still + * identical to {@code exp}. * * @param f the function that defines the index. * @param obj the object instance being tested; must not be null. @@ -504,9 +509,9 @@ /** * Generate the row key for the object's primary data row. - * <p> - * The default implementation uses the relation name, a delimiter, and then - * the encoded primary key. + * + * <p>The default implementation uses the relation name, a delimiter, and then the encoded primary + * key. * * @param key key of the object. * @return the object's data row key. @@ -521,14 +526,13 @@ /** * Generate the row key for an object's secondary index row. - * <p> - * The default implementation uses the relation name, '.', the index name, a - * delimiter, the indexed fields encoded, a delimiter, and then the encoded - * primary key (without the relation name prefix). - * <p> - * The object's primary key is always appended onto the end of the secondary - * index row key to ensure that objects with the same field values still get - * distinct rows in the secondary index. + * + * <p>The default implementation uses the relation name, '.', the index name, a delimiter, the + * indexed fields encoded, a delimiter, and then the encoded primary key (without the relation + * name prefix). + * + * <p>The object's primary key is always appended onto the end of the secondary index row key to + * ensure that objects with the same field values still get distinct rows in the secondary index. * * @param idx function that describes the index. * @param obj the object the index record should reference. @@ -548,9 +552,9 @@ /** * Generate the data to store in a secondary index row for an object. - * <p> - * The default implementation of this method stores the encoded primary key, - * and the current system timestamp. + * + * <p>The default implementation of this method stores the encoded primary key, and the current + * system timestamp. * * @param obj the object the index record should reference. * @return the encoded secondary index row data.
diff --git a/src/main/java/com/google/gwtorm/nosql/generic/GenericDatabase.java b/src/main/java/com/google/gwtorm/nosql/generic/GenericDatabase.java index 7b946e2..42b6a23 100644 --- a/src/main/java/com/google/gwtorm/nosql/generic/GenericDatabase.java +++ b/src/main/java/com/google/gwtorm/nosql/generic/GenericDatabase.java
@@ -18,68 +18,65 @@ import com.google.gwtorm.nosql.NoSqlSchema; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.Schema; - import java.util.concurrent.TimeUnit; /** * Base class for generic NoSQL typed databases. - * <p> - * The generic types provide basic NoSQL implementation assuming a handful of - * primitive operations are available inside of the implementation's extension - * of {@link GenericSchema}. All relations are stored within the same key space, - * using the relation name as a prefix for the row's primary or secondary key. - * <p> - * Applications should use the database class to create instances of their - * Schema extension interface, and thus open and connect to the data store. - * <p> - * Creating a new database instance is expensive, due to the type analysis and - * code generation performed to implement the Schema and Access interfaces. - * Applications should create and cache their database instance for the life of - * the application. - * <p> - * Database instances are thread-safe, but returned Schema instances are not. - * <p> - * This class must be further extended by the NoSQL implementation to configure - * the connectivity with the data store and supply the correct subclass of - * {@link NoSqlSchema} that knows how to interact with the data store. + * + * <p>The generic types provide basic NoSQL implementation assuming a handful of primitive + * operations are available inside of the implementation's extension of {@link GenericSchema}. All + * relations are stored within the same key space, using the relation name as a prefix for the row's + * primary or secondary key. + * + * <p>Applications should use the database class to create instances of their Schema extension + * interface, and thus open and connect to the data store. + * + * <p>Creating a new database instance is expensive, due to the type analysis and code generation + * performed to implement the Schema and Access interfaces. Applications should create and cache + * their database instance for the life of the application. + * + * <p>Database instances are thread-safe, but returned Schema instances are not. + * + * <p>This class must be further extended by the NoSQL implementation to configure the connectivity + * with the data store and supply the correct subclass of {@link NoSqlSchema} that knows how to + * interact with the data store. * * @param <T> type of the application's Schema. * @param <S> type of the implementation's base for Schema implementations. * @param <A> type of the implementation's base for Access implementations. */ @SuppressWarnings("rawtypes") -public abstract class GenericDatabase<T extends Schema, S extends GenericSchema, A extends GenericAccess> +public abstract class GenericDatabase< + T extends Schema, S extends GenericSchema, A extends GenericAccess> extends NoSqlDatabase<T, S, A> { - private static final long DEFAULT_FOSSIL_AGE = - TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES); + private static final long DEFAULT_FOSSIL_AGE = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES); /** * Initialize a new database and generate the implementation. * - * @param schemaBaseType class that the generated Schema implementation should - * extend in order to provide data store connectivity. - * @param accessBaseType class that the generated Access implementations - * should extend in order to provide single-relation access for each - * schema instance. - * @param appSchema the application schema interface that must be implemented - * and constructed on demand. - * @throws OrmException the schema cannot be created because of an annotation - * error in the interface definitions. + * @param schemaBaseType class that the generated Schema implementation should extend in order to + * provide data store connectivity. + * @param accessBaseType class that the generated Access implementations should extend in order to + * provide single-relation access for each schema instance. + * @param appSchema the application schema interface that must be implemented and constructed on + * demand. + * @throws OrmException the schema cannot be created because of an annotation error in the + * interface definitions. */ - protected GenericDatabase(final Class<S> schemaBaseType, - final Class<A> accessBaseType, final Class<T> appSchema) + protected GenericDatabase( + final Class<S> schemaBaseType, final Class<A> accessBaseType, final Class<T> appSchema) throws OrmException { super(schemaBaseType, accessBaseType, appSchema); } /** * Default number of milliseconds a transaction can appear to be open. - * <p> - * Secondary index rows that don't match their primary data object and that - * are older than this age are removed from the system during a scan. * - * @return milliseconds before considering a fossil index record is garbage - * and should be pruned. By default, 5 minutes. + * <p>Secondary index rows that don't match their primary data object and that are older than this + * age are removed from the system during a scan. + * + * @return milliseconds before considering a fossil index record is garbage and should be pruned. + * By default, 5 minutes. */ public long getMaxFossilAge() { return DEFAULT_FOSSIL_AGE;
diff --git a/src/main/java/com/google/gwtorm/nosql/generic/GenericSchema.java b/src/main/java/com/google/gwtorm/nosql/generic/GenericSchema.java index 1493c1c..f983d3e 100644 --- a/src/main/java/com/google/gwtorm/nosql/generic/GenericSchema.java +++ b/src/main/java/com/google/gwtorm/nosql/generic/GenericSchema.java
@@ -25,18 +25,16 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.ResultSet; import com.google.gwtorm.server.Schema; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Base implementation for {@link Schema} in a {@link GenericDatabase}. - * <p> - * NoSQL implementors must extend this class and provide implementations for the - * abstract methods declared here. Each schema instance will wrap one thread's - * connection to the data store. Therefore, unlike database, this class does not - * need to be thread-safe. + * + * <p>NoSQL implementors must extend this class and provide implementations for the abstract methods + * declared here. Each schema instance will wrap one thread's connection to the data store. + * Therefore, unlike database, this class does not need to be thread-safe. */ public abstract class GenericSchema extends NoSqlSchema { private final GenericDatabase<?, ?, ?> db; @@ -46,8 +44,7 @@ db = d; } - public void flush() { - } + public void flush() {} /** @return the database that created this schema instance. */ public GenericDatabase<?, ?, ?> getDatabase() { @@ -56,18 +53,17 @@ /** * Allocate a new unique value from a pool of values. - * <p> - * This method is only required to return a unique value per invocation. - * Implementors may override the method to provide an implementation that - * returns values out of order. - * <p> - * The default implementation of this method stores a {@link CounterShard} - * under the row key {@code ".sequence." + poolName}, and updates it through - * the atomic semantics of {@link #atomicUpdate(byte[], AtomicUpdate)}. If the - * row does not yet exist, it is initialized and the value 1 is returned. * - * @param poolName name of the value pool to allocate from. This is typically - * the name of a sequence in the schema. + * <p>This method is only required to return a unique value per invocation. Implementors may + * override the method to provide an implementation that returns values out of order. + * + * <p>The default implementation of this method stores a {@link CounterShard} under the row key + * {@code ".sequence." + poolName}, and updates it through the atomic semantics of {@link + * #atomicUpdate(byte[], AtomicUpdate)}. If the row does not yet exist, it is initialized and the + * value 1 is returned. + * + * @param poolName name of the value pool to allocate from. This is typically the name of a + * sequence in the schema. * @return a new unique value. * @throws OrmException a unique value cannot be obtained. */ @@ -78,35 +74,36 @@ b.delimiter(); try { final long[] res = new long[1]; - atomicUpdate(b.toByteArray(), new AtomicUpdate<byte[]>() { - @Override - public byte[] update(byte[] val) { - CounterShard ctr; - if (val != null) { - ctr = CounterShard.CODEC.decode(val); - } else { - long start = 1; - for (SequenceModel s : getDatabase().getSchemaModel() - .getSequences()) { - if (poolName.equals(s.getSequenceName())) { - start = s.getSequence().startWith(); - if (start == 0) { - start = 1; + atomicUpdate( + b.toByteArray(), + new AtomicUpdate<byte[]>() { + @Override + public byte[] update(byte[] val) { + CounterShard ctr; + if (val != null) { + ctr = CounterShard.CODEC.decode(val); + } else { + long start = 1; + for (SequenceModel s : getDatabase().getSchemaModel().getSequences()) { + if (poolName.equals(s.getSequenceName())) { + start = s.getSequence().startWith(); + if (start == 0) { + start = 1; + } + break; + } } - break; + ctr = new CounterShard(start, Long.MAX_VALUE); } + + if (ctr.isEmpty()) { + throw new NoMoreValues(); + } + + res[0] = ctr.next(); + return CounterShard.CODEC.encodeToByteString(ctr).toByteArray(); } - ctr = new CounterShard(start, Long.MAX_VALUE); - } - - if (ctr.isEmpty()) { - throw new NoMoreValues(); - } - - res[0] = ctr.next(); - return CounterShard.CODEC.encodeToByteString(ctr).toByteArray(); - } - }); + }); return res[0]; } catch (NoMoreValues err) { throw new OrmException("Counter '" + poolName + "' out of values"); @@ -115,21 +112,18 @@ /** * Fetch one row's data. - * <p> - * The default implementation of this method creates a pair of keys and passes - * them to {@link #scan(byte[], byte[], int, boolean)}. The {@code fromKey} is - * the supplied {@code key}, while the {@code toKey} has '\0' appended onto - * {@code key}. If more than one row matches in that range, the method throws - * an exception. + * + * <p>The default implementation of this method creates a pair of keys and passes them to {@link + * #scan(byte[], byte[], int, boolean)}. The {@code fromKey} is the supplied {@code key}, while + * the {@code toKey} has '\0' appended onto {@code key}. If more than one row matches in that + * range, the method throws an exception. * * @param key key of the row to fetch and return. * @return the data stored under {@code key}; null if no row exists. - * @throws OrmDuplicateKeyException more than one row was identified in the - * key scan. + * @throws OrmDuplicateKeyException more than one row was identified in the key scan. * @throws OrmException the data store cannot process the request. */ - public byte[] fetchRow(byte[] key) throws OrmDuplicateKeyException, - OrmException { + public byte[] fetchRow(byte[] key) throws OrmDuplicateKeyException, OrmException { final byte[] fromKey = key; final byte[] toKey = new byte[key.length + 1]; System.arraycopy(key, 0, toKey, 0, key.length); @@ -153,9 +147,9 @@ /** * Fetch multiple rows at once. - * <p> - * The default implementation of this method is a simple iteration over each - * key and executes a sequential fetch with {@link #fetchRow(byte[])}. + * + * <p>The default implementation of this method is a simple iteration over each key and executes a + * sequential fetch with {@link #fetchRow(byte[])}. * * @param keys keys to fetch and return. * @return iteration over the rows that exist and appear in {@code keys}. @@ -174,54 +168,55 @@ /** * Scan a range of keys and return any matching objects. - * <p> - * To fetch a single record with a scan, set {@code toKey} to the same array - * as {@code fromKey}, but append a trailing NUL byte (0x00). The caller - * should validate that the returned ResultSet contains no more than 1 row. - * <p> - * The resulting iteration does not support remove. - * <p> - * Each iteration element is a map entry, describing the row key and the row - * value. The map entry's value cannot be changed. + * + * <p>To fetch a single record with a scan, set {@code toKey} to the same array as {@code + * fromKey}, but append a trailing NUL byte (0x00). The caller should validate that the returned + * ResultSet contains no more than 1 row. + * + * <p>The resulting iteration does not support remove. + * + * <p>Each iteration element is a map entry, describing the row key and the row value. The map + * entry's value cannot be changed. * * @param fromKey key to start the scan on. This is inclusive. * @param toKey key to stop the scan on. This is exclusive. * @param limit maximum number of results to return. - * @param order if true the order will be preserved, false if the result order - * order can be arbitrary. - * @return result iteration for the requested range. The result set may be - * lazily filled, or filled completely. + * @param order if true the order will be preserved, false if the result order order can be + * arbitrary. + * @return result iteration for the requested range. The result set may be lazily filled, or + * filled completely. * @throws OrmException an error occurred preventing the scan from completing. */ - public abstract ResultSet<Row> scan(byte[] fromKey, byte[] toKey, int limit, - boolean order) throws OrmException; + public abstract ResultSet<Row> scan(byte[] fromKey, byte[] toKey, int limit, boolean order) + throws OrmException; /** * Atomically insert one row, failing if the row already exists. - * <p> - * The default implementation of this method relies upon the atomic nature of - * the {@link #atomicUpdate(byte[], AtomicUpdate)} primitive to test for the - * row's existence, and create the row only if it is not found. + * + * <p>The default implementation of this method relies upon the atomic nature of the {@link + * #atomicUpdate(byte[], AtomicUpdate)} primitive to test for the row's existence, and create the + * row only if it is not found. * * @param key key of the new row to insert. * @param newData data of the new row. - * @throws OrmDuplicateKeyException another row already exists with the - * specified key. - * @throws OrmException the data store cannot process the request right now, - * for example due to a network connectivity problem. + * @throws OrmDuplicateKeyException another row already exists with the specified key. + * @throws OrmException the data store cannot process the request right now, for example due to a + * network connectivity problem. */ public void insert(byte[] key, final byte[] newData) throws OrmDuplicateKeyException, OrmException { try { - atomicUpdate(key, new AtomicUpdate<byte[]>() { - @Override - public byte[] update(byte[] oldData) { - if (oldData != null) { - throw new KeyExists(); - } - return newData; - } - }); + atomicUpdate( + key, + new AtomicUpdate<byte[]>() { + @Override + public byte[] update(byte[] oldData) { + if (oldData != null) { + throw new KeyExists(); + } + return newData; + } + }); } catch (KeyExists err) { throw new OrmDuplicateKeyException("Duplicate key"); } @@ -229,22 +224,22 @@ /** * Update a single row, inserting it if it does not exist. - * <p> - * Unlike insert, this method always succeeds. + * + * <p>Unlike insert, this method always succeeds. * * @param key key of the row to update, or insert if missing. * @param data data to store at this row. - * @throws OrmException the data store cannot process the request, for example - * due to a network connectivity problem. + * @throws OrmException the data store cannot process the request, for example due to a network + * connectivity problem. */ public abstract void upsert(byte[] key, byte[] data) throws OrmException; /** * Delete the row stored under the given key. - * <p> - * If the row does not exist, this method must complete successfully anyway. - * The intent of the caller is to ensure the row does not exist when the - * method completes, and a row that did not exist satisfies that intent. + * + * <p>If the row does not exist, this method must complete successfully anyway. The intent of the + * caller is to ensure the row does not exist when the method completes, and a row that did not + * exist satisfies that intent. * * @param key the key to delete. * @throws OrmException the data store cannot perform the removal. @@ -253,10 +248,10 @@ /** * Atomically read and update a single row. - * <p> - * Unlike schema's atomicUpdate() method, this method must handle missing - * rows. Implementations must be logically equivalent to the following, but - * performed atomically within the scope of the single row key: + * + * <p>Unlike schema's atomicUpdate() method, this method must handle missing rows. Implementations + * must be logically equivalent to the following, but performed atomically within the scope of the + * single row key: * * <pre> * byte[] oldData = get(key); @@ -268,32 +263,29 @@ * } * return data; * </pre> - * <p> - * Secondary index row updates are assumed to never be part of the atomic - * update transaction. This is an intentional design decision to fit with many - * NoSQL product's limitations to support only single-row atomic updates. - * <p> - * The {@code update} method may be invoked multiple times before the - * operation is considered successful. This permits an implementation to - * perform an opportunistic update attempt, and retry the update if the same - * row was modified by another concurrent worker. + * + * <p>Secondary index row updates are assumed to never be part of the atomic update transaction. + * This is an intentional design decision to fit with many NoSQL product's limitations to support + * only single-row atomic updates. + * + * <p>The {@code update} method may be invoked multiple times before the operation is considered + * successful. This permits an implementation to perform an opportunistic update attempt, and + * retry the update if the same row was modified by another concurrent worker. * * @param key the row key to read, update and return. - * @param update action to perform on the row's data element. The action may - * be passed null if the row doesn't exist. + * @param update action to perform on the row's data element. The action may be passed null if the + * row doesn't exist. * @throws OrmException the database cannot perform the update. */ - public abstract void atomicUpdate(byte[] key, AtomicUpdate<byte[]> update) - throws OrmException; + public abstract void atomicUpdate(byte[] key, AtomicUpdate<byte[]> update) throws OrmException; /** * Check (and delete) an index row if its a fossil. - * <p> - * As index rows are written ahead of the main data row being written out, - * scans sometimes see an index row that does not match the data row. These - * are ignored for a short period ({@link GenericDatabase#getMaxFossilAge()}) - * to allow the primary data row to eventually get written out. If however the - * writer never finished the update, these index rows are stale and need to be + * + * <p>As index rows are written ahead of the main data row being written out, scans sometimes see + * an index row that does not match the data row. These are ignored for a short period ({@link + * GenericDatabase#getMaxFossilAge()}) to allow the primary data row to eventually get written + * out. If however the writer never finished the update, these index rows are stale and need to be * pruned. Any index row older than the fossil age is removed by this method. * * @param now timestamp when the current scan started. @@ -308,13 +300,12 @@ /** * Delete the given fossil index row. - * <p> - * This method is logically the same as {@link #delete(byte[])}, but its - * separated out to permit asynchronous delivery of the delete events since - * these are arriving during an index scan and are less time-critical than - * other delete operations. - * <p> - * The default implementation of this method calls {@link #delete(byte[])}. + * + * <p>This method is logically the same as {@link #delete(byte[])}, but its separated out to + * permit asynchronous delivery of the delete events since these are arriving during an index scan + * and are less time-critical than other delete operations. + * + * <p>The default implementation of this method calls {@link #delete(byte[])}. * * @param key index key to remove. * @param row the index row data. @@ -328,10 +319,8 @@ } @SuppressWarnings("serial") - private static class KeyExists extends RuntimeException { - } + private static class KeyExists extends RuntimeException {} @SuppressWarnings("serial") - private static class NoMoreValues extends RuntimeException { - } + private static class NoMoreValues extends RuntimeException {} }
diff --git a/src/main/java/com/google/gwtorm/nosql/heap/FileDatabase.java b/src/main/java/com/google/gwtorm/nosql/heap/FileDatabase.java index 1799865..66a96cf 100644 --- a/src/main/java/com/google/gwtorm/nosql/heap/FileDatabase.java +++ b/src/main/java/com/google/gwtorm/nosql/heap/FileDatabase.java
@@ -16,7 +16,6 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.Schema; - import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; @@ -32,19 +31,18 @@ /** * Tiny NoSQL database stored on the local filesystem. - * <p> - * This is a simple NoSQL implementation intended only for development/debugging - * purposes. It is not capable of supporting any production traffic. Large data - * sets will cause the implementation to fall over, as all records are stored in - * memory. - * <p> - * Although some effort is made to persist data to disk during updates, and - * reload it during construction, durability of stored data is not guaranteed. + * + * <p>This is a simple NoSQL implementation intended only for development/debugging purposes. It is + * not capable of supporting any production traffic. Large data sets will cause the implementation + * to fall over, as all records are stored in memory. + * + * <p>Although some effort is made to persist data to disk during updates, and reload it during + * construction, durability of stored data is not guaranteed. * * @param <T> type of the application schema. */ -public class FileDatabase<T extends Schema> extends - TreeMapDatabase<T, FileDatabase.LoggingSchema, FileDatabase.LoggingAccess> { +public class FileDatabase<T extends Schema> + extends TreeMapDatabase<T, FileDatabase.LoggingSchema, FileDatabase.LoggingAccess> { private static final int MAX_LOG_SIZE = 50000; private final File heapFile; @@ -56,14 +54,13 @@ /** * Create the database and implement the application's schema interface. * - * @param path path prefix for the data files. File suffixes will be added to - * this name to name the database's various files. + * @param path path prefix for the data files. File suffixes will be added to this name to name + * the database's various files. * @param schema the application schema this database will open. - * @throws OrmException the schema cannot be queried, or the existing database - * files are not readable. + * @throws OrmException the schema cannot be queried, or the existing database files are not + * readable. */ - public FileDatabase(final File path, final Class<T> schema) - throws OrmException { + public FileDatabase(final File path, final Class<T> schema) throws OrmException { super(LoggingSchema.class, LoggingAccess.class, schema); heapFile = new File(path.getAbsolutePath() + ".nosql_db"); @@ -105,9 +102,10 @@ final DataInputStream in; try { - in = new DataInputStream( // - new BufferedInputStream( // - new FileInputStream(heapFile))); + in = + new DataInputStream( // + new BufferedInputStream( // + new FileInputStream(heapFile))); } catch (FileNotFoundException e) { return; } @@ -136,36 +134,39 @@ final DataInputStream in; try { - in = new DataInputStream( // - new BufferedInputStream( // - new FileInputStream(logFile))); + in = + new DataInputStream( // + new BufferedInputStream( // + new FileInputStream(logFile))); } catch (FileNotFoundException e) { return; } try { - for (;; logRecords++) { + for (; ; logRecords++) { final int op = in.read(); if (op < 0) { break; } switch (op) { - case 0: { - final byte[] key = new byte[in.readInt()]; - in.readFully(key); - table.remove(key); - break; - } + case 0: + { + final byte[] key = new byte[in.readInt()]; + in.readFully(key); + table.remove(key); + break; + } - case 1: { - final byte[] key = new byte[in.readInt()]; - final byte[] val = new byte[in.readInt()]; - in.readFully(key); - in.readFully(val); - table.put(key, val); - break; - } + case 1: + { + final byte[] key = new byte[in.readInt()]; + final byte[] val = new byte[in.readInt()]; + in.readFully(key); + in.readFully(val); + table.put(key, val); + break; + } default: throw new OrmException("Unknown log command " + op); @@ -220,9 +221,10 @@ final File tmp = newTempFile(); boolean ok = false; try { - DataOutputStream out = new DataOutputStream( // - new BufferedOutputStream( // - new FileOutputStream(tmp))); + DataOutputStream out = + new DataOutputStream( // + new BufferedOutputStream( // + new FileOutputStream(tmp))); try { out.writeInt(table.size()); for (Map.Entry<byte[], byte[]> ent : table.entrySet()) { @@ -270,7 +272,7 @@ return File.createTempFile("heap_", "_db", heapFile.getParentFile()); } - public static abstract class LoggingSchema extends TreeMapSchema { + public abstract static class LoggingSchema extends TreeMapSchema { private final FileDatabase<?> db; protected LoggingSchema(FileDatabase<?> db) { @@ -302,7 +304,7 @@ } @SuppressWarnings("rawtypes") - public static abstract class LoggingAccess extends TreeMapAccess { + public abstract static class LoggingAccess extends TreeMapAccess { protected LoggingAccess(LoggingSchema s) { super(s); }
diff --git a/src/main/java/com/google/gwtorm/nosql/heap/HeapKeyComparator.java b/src/main/java/com/google/gwtorm/nosql/heap/HeapKeyComparator.java index 33aded6..4ef4533 100644 --- a/src/main/java/com/google/gwtorm/nosql/heap/HeapKeyComparator.java +++ b/src/main/java/com/google/gwtorm/nosql/heap/HeapKeyComparator.java
@@ -19,8 +19,7 @@ class HeapKeyComparator implements Comparator<byte[]> { static final HeapKeyComparator INSTANCE = new HeapKeyComparator(); - private HeapKeyComparator() { - } + private HeapKeyComparator() {} @Override public int compare(byte[] a, byte[] b) {
diff --git a/src/main/java/com/google/gwtorm/nosql/heap/MemoryDatabase.java b/src/main/java/com/google/gwtorm/nosql/heap/MemoryDatabase.java index 5c8aaab..47e5bdc 100644 --- a/src/main/java/com/google/gwtorm/nosql/heap/MemoryDatabase.java +++ b/src/main/java/com/google/gwtorm/nosql/heap/MemoryDatabase.java
@@ -19,18 +19,17 @@ /** * Toy in-memory implementation of a NoSQL database. - * <p> - * Implements a simple NoSQL database with a standard {@link java.util.TreeMap} - * held inside of this JVM process. All operations occur on the TreeMap, with no - * durability across database restarts. Therefore this implementation is only - * suitable for simple tests. + * + * <p>Implements a simple NoSQL database with a standard {@link java.util.TreeMap} held inside of + * this JVM process. All operations occur on the TreeMap, with no durability across database + * restarts. Therefore this implementation is only suitable for simple tests. * * @param <T> type of the application schema. * @see FileDatabase */ @SuppressWarnings("rawtypes") -public class MemoryDatabase<T extends Schema> extends - TreeMapDatabase<T, TreeMapSchema, TreeMapAccess> { +public class MemoryDatabase<T extends Schema> + extends TreeMapDatabase<T, TreeMapSchema, TreeMapAccess> { /** * Create the database and implement the application's schema interface.
diff --git a/src/main/java/com/google/gwtorm/nosql/heap/TreeMapAccess.java b/src/main/java/com/google/gwtorm/nosql/heap/TreeMapAccess.java index aa58c1e..6f82d12 100644 --- a/src/main/java/com/google/gwtorm/nosql/heap/TreeMapAccess.java +++ b/src/main/java/com/google/gwtorm/nosql/heap/TreeMapAccess.java
@@ -19,8 +19,7 @@ import com.google.gwtorm.server.Access; /** Base implementation for {@link Access} in a {@link TreeMapDatabase}. */ -public abstract class TreeMapAccess<T, K extends Key<?>> extends - GenericAccess<T, K> { +public abstract class TreeMapAccess<T, K extends Key<?>> extends GenericAccess<T, K> { protected TreeMapAccess(final TreeMapSchema s) { super(s); }
diff --git a/src/main/java/com/google/gwtorm/nosql/heap/TreeMapDatabase.java b/src/main/java/com/google/gwtorm/nosql/heap/TreeMapDatabase.java index fca8470..e36da61 100644 --- a/src/main/java/com/google/gwtorm/nosql/heap/TreeMapDatabase.java +++ b/src/main/java/com/google/gwtorm/nosql/heap/TreeMapDatabase.java
@@ -19,7 +19,6 @@ import com.google.gwtorm.server.Schema; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.UnknownFieldSet; - import java.io.PrintWriter; import java.util.Map; import java.util.SortedMap; @@ -29,11 +28,10 @@ /** * Toy in-memory implementation of a NoSQL database. - * <p> - * Implements a simple NoSQL database with a standard {@link java.util.TreeMap} - * held inside of this JVM process. All operations occur on the TreeMap, with no - * durability across database restarts. Therefore this implementation is only - * suitable for simple tests. + * + * <p>Implements a simple NoSQL database with a standard {@link java.util.TreeMap} held inside of + * this JVM process. All operations occur on the TreeMap, with no durability across database + * restarts. Therefore this implementation is only suitable for simple tests. * * @param <T> type of the application schema. */ @@ -50,18 +48,17 @@ /** * Initialize a new database and generate the implementation. * - * @param schemaBaseType class that the generated Schema implementation should - * extend in order to provide data store connectivity. - * @param accessBaseType class that the generated Access implementations - * should extend in order to provide single-relation access for each - * schema instance. - * @param appSchema the application schema interface that must be implemented - * and constructed on demand. - * @throws OrmException the schema cannot be created because of an annotation - * error in the interface definitions. + * @param schemaBaseType class that the generated Schema implementation should extend in order to + * provide data store connectivity. + * @param accessBaseType class that the generated Access implementations should extend in order to + * provide single-relation access for each schema instance. + * @param appSchema the application schema interface that must be implemented and constructed on + * demand. + * @throws OrmException the schema cannot be created because of an annotation error in the + * interface definitions. */ - protected TreeMapDatabase(final Class<S> schemaBaseType, - final Class<A> accessBaseType, final Class<T> appSchema) + protected TreeMapDatabase( + final Class<S> schemaBaseType, final Class<A> accessBaseType, final Class<T> appSchema) throws OrmException { super(schemaBaseType, accessBaseType, appSchema);
diff --git a/src/main/java/com/google/gwtorm/nosql/heap/TreeMapSchema.java b/src/main/java/com/google/gwtorm/nosql/heap/TreeMapSchema.java index ed73f2d..4d47d75 100644 --- a/src/main/java/com/google/gwtorm/nosql/heap/TreeMapSchema.java +++ b/src/main/java/com/google/gwtorm/nosql/heap/TreeMapSchema.java
@@ -21,12 +21,11 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.ResultSet; import com.google.gwtorm.server.Schema; - import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.Map.Entry; +import java.util.Set; /** Base implementation for {@link Schema} in a {@link TreeMapDatabase}. */ public abstract class TreeMapSchema extends GenericSchema { @@ -48,8 +47,7 @@ } @Override - public ResultSet<Row> scan(byte[] fromKey, byte[] toKey, int limit, - boolean order) { + public ResultSet<Row> scan(byte[] fromKey, byte[] toKey, int limit, boolean order) { db.lock.lock(); try { final List<Row> res = new ArrayList<>(); @@ -91,8 +89,7 @@ } @Override - public void atomicUpdate(byte[] key, AtomicUpdate<byte[]> update) - throws OrmException { + public void atomicUpdate(byte[] key, AtomicUpdate<byte[]> update) throws OrmException { db.lock.lock(); try { final byte[] oldData = fetchRow(key);
diff --git a/src/main/java/com/google/gwtorm/protobuf/CodecFactory.java b/src/main/java/com/google/gwtorm/protobuf/CodecFactory.java index 070ce78..cedfc65 100644 --- a/src/main/java/com/google/gwtorm/protobuf/CodecFactory.java +++ b/src/main/java/com/google/gwtorm/protobuf/CodecFactory.java
@@ -17,7 +17,6 @@ import com.google.gwtorm.client.Column; import com.google.gwtorm.server.GeneratedClassLoader; import com.google.gwtorm.server.OrmException; - import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; @@ -29,18 +28,17 @@ /** * Create an implementation to encode/decode an arbitrary object. - * <p> - * The object must use the {@link Column} annotations to denote the fields - * that should be encoded or decoded. + * + * <p>The object must use the {@link Column} annotations to denote the fields that should be + * encoded or decoded. * * @param <T> type of the object to be supported. * @param type the object type. * @return an encoder for this object type. - * @throws IllegalArgumentException the object's fields aren't declared - * properly. This is a programming error that cannot be recovered. + * @throws IllegalArgumentException the object's fields aren't declared properly. This is a + * programming error that cannot be recovered. */ - public static <T> ProtobufCodec<T> encoder(Class<T> type) - throws IllegalStateException { + public static <T> ProtobufCodec<T> encoder(Class<T> type) throws IllegalStateException { final GeneratedClassLoader loader = newLoader(type); ProtobufCodec<T> encoder = null; String cacheName = encoders.get(type); @@ -52,8 +50,8 @@ try { encoder = gen.create(); } catch (OrmException e) { - throw new IllegalArgumentException("Class " + type.getName() - + " cannot be supported on protobuf", e); + throw new IllegalArgumentException( + "Class " + type.getName() + " cannot be supported on protobuf", e); } encoders.put(type, encoder.getClass().getName()); } @@ -77,6 +75,5 @@ } } - private CodecFactory() { - } + private CodecFactory() {} }
diff --git a/src/main/java/com/google/gwtorm/protobuf/CodecGen.java b/src/main/java/com/google/gwtorm/protobuf/CodecGen.java index 1eb6fde..a726ad6 100644 --- a/src/main/java/com/google/gwtorm/protobuf/CodecGen.java +++ b/src/main/java/com/google/gwtorm/protobuf/CodecGen.java
@@ -25,13 +25,6 @@ import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import com.google.protobuf.WireFormat; - -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; @@ -42,22 +35,23 @@ import java.util.HashSet; import java.util.Map; import java.util.TreeSet; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; /** Generates {@link ProtobufCodec} implementations. */ class CodecGen<T> implements Opcodes { - private static final Type illegalStateException = - Type.getType(IllegalStateException.class); - private static final Type collection = - Type.getType(java.util.Collection.class); + private static final Type illegalStateException = Type.getType(IllegalStateException.class); + private static final Type collection = Type.getType(java.util.Collection.class); private static final Type iterator = Type.getType(java.util.Iterator.class); private static final Type string = Type.getType(String.class); private static final Type enumType = Type.getType(Enum.class); private static final Type byteString = Type.getType(ByteString.class); private static final Type object = Type.getType(Object.class); - private static final Type codedOutputStream = - Type.getType(CodedOutputStream.class); - private static final Type codedInputStream = - Type.getType(CodedInputStream.class); + private static final Type codedOutputStream = Type.getType(CodedOutputStream.class); + private static final Type codedInputStream = Type.getType(CodedInputStream.class); private final GeneratedClassLoader classLoader; private final Class<T> pojo; private final Type pojoType; @@ -122,21 +116,21 @@ in = in.getSuperclass(); } if (col.isEmpty()) { - throw new OrmException( - "Cannot create new encoder, no @Column fields found"); + throw new OrmException("Cannot create new encoder, no @Column fields found"); } return sort(col); } - private static JavaColumnModel[] sort( - final Collection<? extends ColumnModel> col) { + private static JavaColumnModel[] sort(final Collection<? extends ColumnModel> col) { JavaColumnModel[] out = col.toArray(new JavaColumnModel[col.size()]); - Arrays.sort(out, new Comparator<JavaColumnModel>() { - @Override - public int compare(JavaColumnModel o1, JavaColumnModel o2) { - return o1.getColumnID() - o2.getColumnID(); - } - }); + Arrays.sort( + out, + new Comparator<JavaColumnModel>() { + @Override + public int compare(JavaColumnModel o1, JavaColumnModel o2) { + return o1.getColumnID() - o2.getColumnID(); + } + }); return out; } @@ -151,30 +145,46 @@ implTypeName = implClassName.replace('.', '/'); cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - cw.visit(V1_3, ACC_PUBLIC | ACC_FINAL | ACC_SUPER, implTypeName, null, - superTypeName, new String[] {}); + cw.visit( + V1_3, + ACC_PUBLIC | ACC_FINAL | ACC_SUPER, + implTypeName, + null, + superTypeName, + new String[] {}); } private void implementCodecFields() { for (NestedCodec other : nestedCodecs.values()) { - cw.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, other.field, - other.codecType.getDescriptor(), null, null).visitEnd(); + cw.visitField( + ACC_PRIVATE | ACC_STATIC | ACC_FINAL, + other.field, + other.codecType.getDescriptor(), + null, + null) + .visitEnd(); } } private void implementStaticInit() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {}), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_STATIC, + "<clinit>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}), + null, + null); mv.visitCode(); for (NestedCodec other : nestedCodecs.values()) { mv.visitTypeInsn(NEW, other.codecType.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, other.codecType.getInternalName(), - "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); - mv.visitFieldInsn(PUTSTATIC, implTypeName, other.field, other.codecType - .getDescriptor()); + mv.visitMethodInsn( + INVOKESPECIAL, + other.codecType.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitFieldInsn(PUTSTATIC, implTypeName, other.field, other.codecType.getDescriptor()); } mv.visitInsn(RETURN); @@ -184,10 +194,8 @@ private void implementConstructor() { final String consName = "<init>"; - final String consDesc = - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}); - final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); + final String consDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}); + final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); @@ -200,13 +208,20 @@ private void implementNewInstanceObject() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "newInstance", Type.getMethodDescriptor( - object, new Type[] {}), null, new String[] {}); + cw.visitMethod( + ACC_PUBLIC, + "newInstance", + Type.getMethodDescriptor(object, new Type[] {}), + null, + new String[] {}); mv.visitCode(); mv.visitTypeInsn(NEW, pojoType.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, pojoType.getInternalName(), "<init>", + mv.visitMethodInsn( + INVOKESPECIAL, + pojoType.getInternalName(), + "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); mv.visitInsn(ARETURN); @@ -216,13 +231,20 @@ private void implementNewInstanceSelf() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "newInstance", Type.getMethodDescriptor( - pojoType, new Type[] {}), null, new String[] {}); + cw.visitMethod( + ACC_PUBLIC, + "newInstance", + Type.getMethodDescriptor(pojoType, new Type[] {}), + null, + new String[] {}); mv.visitCode(); mv.visitTypeInsn(NEW, pojoType.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, pojoType.getInternalName(), "<init>", + mv.visitMethodInsn( + INVOKESPECIAL, + pojoType.getInternalName(), + "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); mv.visitInsn(ARETURN); @@ -232,8 +254,12 @@ private void implementSizeofObject() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "sizeof", Type.getMethodDescriptor( - Type.INT_TYPE, new Type[] {object}), null, new String[] {}); + cw.visitMethod( + ACC_PUBLIC, + "sizeof", + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {object}), + null, + new String[] {}); mv.visitCode(); final SizeofCGS cgs = new SizeofCGS(mv); cgs.sizeVar = cgs.newLocal(); @@ -242,8 +268,11 @@ mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, pojoType.getInternalName()); - mv.visitMethodInsn(INVOKEVIRTUAL, implTypeName, "sizeof", Type - .getMethodDescriptor(Type.INT_TYPE, new Type[] {pojoType})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + implTypeName, + "sizeof", + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {pojoType})); mv.visitInsn(IRETURN); mv.visitMaxs(-1, -1); @@ -252,8 +281,12 @@ private void implementSizeofSelf() throws OrmException { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "sizeof", Type.getMethodDescriptor( - Type.INT_TYPE, new Type[] {pojoType}), null, new String[] {}); + cw.visitMethod( + ACC_PUBLIC, + "sizeof", + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {pojoType}), + null, + new String[] {}); mv.visitCode(); final SizeofCGS cgs = new SizeofCGS(mv); cgs.sizeVar = cgs.newLocal(); @@ -269,8 +302,9 @@ mv.visitEnd(); } - private void sizeofMessage(final JavaColumnModel[] myFields, - final MethodVisitor mv, final SizeofCGS cgs) throws OrmException { + private void sizeofMessage( + final JavaColumnModel[] myFields, final MethodVisitor mv, final SizeofCGS cgs) + throws OrmException { for (final JavaColumnModel f : myFields) { if (f.isNested()) { final NestedCodec n = nestedFor(f); @@ -280,12 +314,13 @@ mv.visitJumpInsn(IFNULL, end); final int msgSizeVar = cgs.newLocal(); - mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType - .getDescriptor()); + mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType.getDescriptor()); cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, n.codecType.getInternalName(), - "sizeof", Type.getMethodDescriptor(Type.INT_TYPE, - new Type[] {n.pojoType})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + n.codecType.getInternalName(), + "sizeof", + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {n.pojoType})); mv.visitVarInsn(ISTORE, msgSizeVar); cgs.preinc(); @@ -336,41 +371,42 @@ return n; } - private void sizeofCollection(final JavaColumnModel f, - final MethodVisitor mv, final SizeofCGS cgs) throws OrmException { + private void sizeofCollection( + final JavaColumnModel f, final MethodVisitor mv, final SizeofCGS cgs) throws OrmException { final int itr = cgs.newLocal(); final int val = cgs.newLocal(); final Class<?> valClazz = (Class<?>) f.getArgumentTypes()[0]; final Type valType = Type.getType(valClazz); final JavaColumnModel col = collectionColumn(f, valClazz); - final SizeofCGS ng = new SizeofCGS(mv) { - { - sizeVar = cgs.sizeVar; - setEntityType(valType); - } + final SizeofCGS ng = + new SizeofCGS(mv) { + { + sizeVar = cgs.sizeVar; + setEntityType(valType); + } - @Override - public void pushEntity() { - mv.visitVarInsn(ALOAD, val); - } + @Override + public void pushEntity() { + mv.visitVarInsn(ALOAD, val); + } - @Override - protected void appendGetField(final ColumnModel c) { - if (c != col) { - super.appendGetField(c); - } - } + @Override + protected void appendGetField(final ColumnModel c) { + if (c != col) { + super.appendGetField(c); + } + } - @Override - public int newLocal() { - return cgs.newLocal(); - } + @Override + public int newLocal() { + return cgs.newLocal(); + } - @Override - public void freeLocal(int index) { - cgs.freeLocal(index); - } - }; + @Override + public void freeLocal(int index) { + cgs.freeLocal(index); + } + }; final Label end = new Label(); cgs.setFieldReference(f); @@ -379,19 +415,28 @@ cgs.setFieldReference(f); cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEINTERFACE, collection.getInternalName(), - "iterator", Type.getMethodDescriptor(iterator, new Type[] {})); + mv.visitMethodInsn( + INVOKEINTERFACE, + collection.getInternalName(), + "iterator", + Type.getMethodDescriptor(iterator, new Type[] {})); mv.visitVarInsn(ASTORE, itr); final Label doloop = new Label(); mv.visitLabel(doloop); mv.visitVarInsn(ALOAD, itr); - mv.visitMethodInsn(INVOKEINTERFACE, iterator.getInternalName(), "hasNext", + mv.visitMethodInsn( + INVOKEINTERFACE, + iterator.getInternalName(), + "hasNext", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {})); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ALOAD, itr); - mv.visitMethodInsn(INVOKEINTERFACE, iterator.getInternalName(), "next", + mv.visitMethodInsn( + INVOKEINTERFACE, + iterator.getInternalName(), + "next", Type.getMethodDescriptor(object, new Type[] {})); mv.visitTypeInsn(CHECKCAST, valType.getInternalName()); mv.visitVarInsn(ASTORE, val); @@ -404,8 +449,8 @@ cgs.freeLocal(val); } - private JavaColumnModel collectionColumn(final JavaColumnModel f, - final Class<?> valClazz) throws OrmException { + private JavaColumnModel collectionColumn(final JavaColumnModel f, final Class<?> valClazz) + throws OrmException { return new JavaColumnModel( // f.getField(), // f.getPathToFieldName(), // @@ -413,8 +458,8 @@ valClazz); } - private void sizeofScalar(final MethodVisitor mv, final SizeofCGS cgs, - final JavaColumnModel f) throws OrmException { + private void sizeofScalar(final MethodVisitor mv, final SizeofCGS cgs, final JavaColumnModel f) + throws OrmException { cgs.setFieldReference(f); switch (Type.getType(f.getPrimitiveType()).getSort()) { @@ -463,70 +508,82 @@ break; case Type.ARRAY: - case Type.OBJECT: { - final Label end = new Label(); - cgs.pushFieldValue(); - mv.visitJumpInsn(IFNULL, end); - - if (f.getPrimitiveType() == byte[].class) { - cgs.preinc(); - cgs.push(f.getColumnID()); - cgs.doinc("computeTagSize", Type.INT_TYPE); - - cgs.preinc(); + case Type.OBJECT: + { + final Label end = new Label(); cgs.pushFieldValue(); - mv.visitInsn(ARRAYLENGTH); - cgs.doinc("computeRawVarint32Size", Type.INT_TYPE); + mv.visitJumpInsn(IFNULL, end); - cgs.preinc(); - cgs.pushFieldValue(); - mv.visitInsn(ARRAYLENGTH); - cgs.doinc(); + if (f.getPrimitiveType() == byte[].class) { + cgs.preinc(); + cgs.push(f.getColumnID()); + cgs.doinc("computeTagSize", Type.INT_TYPE); - } else if (f.getPrimitiveType() == String.class) { - cgs.preinc(); - cgs.push(f.getColumnID()); - cgs.pushFieldValue(); - cgs.doinc("computeStringSize", Type.INT_TYPE, string); + cgs.preinc(); + cgs.pushFieldValue(); + mv.visitInsn(ARRAYLENGTH); + cgs.doinc("computeRawVarint32Size", Type.INT_TYPE); - } else if (f.getPrimitiveType() == java.sql.Timestamp.class - || f.getPrimitiveType() == java.util.Date.class - || f.getPrimitiveType() == java.sql.Date.class) { - cgs.preinc(); - cgs.push(f.getColumnID()); - cgs.pushFieldValue(); - String tsType = Type.getType(f.getPrimitiveType()).getInternalName(); - mv.visitMethodInsn(INVOKEVIRTUAL, tsType, "getTime", Type - .getMethodDescriptor(Type.LONG_TYPE, new Type[] {})); - cgs.doinc("computeFixed64Size", Type.INT_TYPE, Type.LONG_TYPE); + cgs.preinc(); + cgs.pushFieldValue(); + mv.visitInsn(ARRAYLENGTH); + cgs.doinc(); - } else if (f.getPrimitiveType().isEnum()) { - cgs.preinc(); - cgs.push(f.getColumnID()); - cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, enumType.getInternalName(), - "ordinal", // - Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {})); - cgs.doinc("computeEnumSize", Type.INT_TYPE, Type.INT_TYPE); + } else if (f.getPrimitiveType() == String.class) { + cgs.preinc(); + cgs.push(f.getColumnID()); + cgs.pushFieldValue(); + cgs.doinc("computeStringSize", Type.INT_TYPE, string); - } else { - throw new OrmException("Type " + f.getPrimitiveType() - + " not supported for field " + f.getPathToFieldName()); + } else if (f.getPrimitiveType() == java.sql.Timestamp.class + || f.getPrimitiveType() == java.util.Date.class + || f.getPrimitiveType() == java.sql.Date.class) { + cgs.preinc(); + cgs.push(f.getColumnID()); + cgs.pushFieldValue(); + String tsType = Type.getType(f.getPrimitiveType()).getInternalName(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + tsType, + "getTime", + Type.getMethodDescriptor(Type.LONG_TYPE, new Type[] {})); + cgs.doinc("computeFixed64Size", Type.INT_TYPE, Type.LONG_TYPE); + + } else if (f.getPrimitiveType().isEnum()) { + cgs.preinc(); + cgs.push(f.getColumnID()); + cgs.pushFieldValue(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + enumType.getInternalName(), + "ordinal", // + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {})); + cgs.doinc("computeEnumSize", Type.INT_TYPE, Type.INT_TYPE); + + } else { + throw new OrmException( + "Type " + + f.getPrimitiveType() + + " not supported for field " + + f.getPathToFieldName()); + } + mv.visitLabel(end); + break; } - mv.visitLabel(end); - break; - } default: - throw new OrmException("Type " + f.getPrimitiveType() - + " not supported for field " + f.getPathToFieldName()); + throw new OrmException( + "Type " + f.getPrimitiveType() + " not supported for field " + f.getPathToFieldName()); } } private void implementEncodeObject() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "encode", Type.getMethodDescriptor( - Type.VOID_TYPE, new Type[] {object, codedOutputStream}), null, + cw.visitMethod( + ACC_PUBLIC, + "encode", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {object, codedOutputStream}), + null, new String[] {}); mv.visitCode(); final EncodeCGS cgs = new EncodeCGS(mv); @@ -536,9 +593,11 @@ mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, pojoType.getInternalName()); mv.visitVarInsn(ALOAD, 2); - mv.visitMethodInsn(INVOKEVIRTUAL, implTypeName, "encode", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {pojoType, - codedOutputStream})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + implTypeName, + "encode", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {pojoType, codedOutputStream})); mv.visitInsn(RETURN); mv.visitMaxs(-1, -1); @@ -547,8 +606,11 @@ private void implementEncodeSelf() throws OrmException { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "encode", Type.getMethodDescriptor( - Type.VOID_TYPE, new Type[] {pojoType, codedOutputStream}), null, + cw.visitMethod( + ACC_PUBLIC, + "encode", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {pojoType, codedOutputStream}), + null, new String[] {}); mv.visitCode(); final EncodeCGS cgs = new EncodeCGS(mv); @@ -561,8 +623,9 @@ mv.visitEnd(); } - private void encodeMessage(final JavaColumnModel[] myFields, - final MethodVisitor mv, final EncodeCGS cgs) throws OrmException { + private void encodeMessage( + final JavaColumnModel[] myFields, final MethodVisitor mv, final EncodeCGS cgs) + throws OrmException { for (final JavaColumnModel f : myFields) { if (f.isNested()) { final NestedCodec n = nestedFor(f); @@ -573,34 +636,40 @@ mv.visitJumpInsn(IFNULL, end); final int msgSizeVar = cgs.newLocal(); - mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType - .getDescriptor()); + mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType.getDescriptor()); cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, n.codecType.getInternalName(), - "sizeof", Type.getMethodDescriptor(Type.INT_TYPE, - new Type[] {n.pojoType})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + n.codecType.getInternalName(), + "sizeof", + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {n.pojoType})); mv.visitVarInsn(ISTORE, msgSizeVar); cgs.pushCodedOutputStream(); cgs.push(f.getColumnID()); cgs.push(WireFormat.FieldType.MESSAGE.getWireType()); - mv.visitMethodInsn(INVOKEVIRTUAL, codedOutputStream.getInternalName(), - "writeTag", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { - Type.INT_TYPE, Type.INT_TYPE})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedOutputStream.getInternalName(), + "writeTag", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE, Type.INT_TYPE})); cgs.pushCodedOutputStream(); mv.visitVarInsn(ILOAD, msgSizeVar); - mv.visitMethodInsn(INVOKEVIRTUAL, codedOutputStream.getInternalName(), - "writeRawVarint32", Type.getMethodDescriptor(Type.VOID_TYPE, - new Type[] {Type.INT_TYPE})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedOutputStream.getInternalName(), + "writeRawVarint32", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE})); - mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType - .getDescriptor()); + mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType.getDescriptor()); cgs.pushFieldValue(); cgs.pushCodedOutputStream(); - mv.visitMethodInsn(INVOKEVIRTUAL, n.codecType.getInternalName(), - "encode", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { - n.pojoType, codedOutputStream})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + n.codecType.getInternalName(), + "encode", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {n.pojoType, codedOutputStream})); cgs.freeLocal(msgSizeVar); mv.visitLabel(end); @@ -614,41 +683,42 @@ } } - private void encodeCollection(final JavaColumnModel f, - final MethodVisitor mv, final EncodeCGS cgs) throws OrmException { + private void encodeCollection( + final JavaColumnModel f, final MethodVisitor mv, final EncodeCGS cgs) throws OrmException { final int itr = cgs.newLocal(); final int val = cgs.newLocal(); final Class<?> valClazz = (Class<?>) f.getArgumentTypes()[0]; final Type valType = Type.getType(valClazz); final JavaColumnModel col = collectionColumn(f, valClazz); - final EncodeCGS ng = new EncodeCGS(mv) { - { - sizeVar = cgs.sizeVar; - setEntityType(valType); - } + final EncodeCGS ng = + new EncodeCGS(mv) { + { + sizeVar = cgs.sizeVar; + setEntityType(valType); + } - @Override - public void pushEntity() { - mv.visitVarInsn(ALOAD, val); - } + @Override + public void pushEntity() { + mv.visitVarInsn(ALOAD, val); + } - @Override - protected void appendGetField(final ColumnModel c) { - if (c != col) { - super.appendGetField(c); - } - } + @Override + protected void appendGetField(final ColumnModel c) { + if (c != col) { + super.appendGetField(c); + } + } - @Override - public int newLocal() { - return cgs.newLocal(); - } + @Override + public int newLocal() { + return cgs.newLocal(); + } - @Override - public void freeLocal(int index) { - cgs.freeLocal(index); - } - }; + @Override + public void freeLocal(int index) { + cgs.freeLocal(index); + } + }; final Label end = new Label(); cgs.setFieldReference(f); @@ -657,19 +727,28 @@ cgs.setFieldReference(f); cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEINTERFACE, collection.getInternalName(), - "iterator", Type.getMethodDescriptor(iterator, new Type[] {})); + mv.visitMethodInsn( + INVOKEINTERFACE, + collection.getInternalName(), + "iterator", + Type.getMethodDescriptor(iterator, new Type[] {})); mv.visitVarInsn(ASTORE, itr); final Label doloop = new Label(); mv.visitLabel(doloop); mv.visitVarInsn(ALOAD, itr); - mv.visitMethodInsn(INVOKEINTERFACE, iterator.getInternalName(), "hasNext", + mv.visitMethodInsn( + INVOKEINTERFACE, + iterator.getInternalName(), + "hasNext", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {})); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ALOAD, itr); - mv.visitMethodInsn(INVOKEINTERFACE, iterator.getInternalName(), "next", + mv.visitMethodInsn( + INVOKEINTERFACE, + iterator.getInternalName(), + "next", Type.getMethodDescriptor(object, new Type[] {})); mv.visitTypeInsn(CHECKCAST, valType.getInternalName()); mv.visitVarInsn(ASTORE, val); @@ -682,8 +761,8 @@ cgs.freeLocal(val); } - private void encodeScalar(final MethodVisitor mv, final EncodeCGS cgs, - final JavaColumnModel f) throws OrmException { + private void encodeScalar(final MethodVisitor mv, final EncodeCGS cgs, final JavaColumnModel f) + throws OrmException { cgs.setFieldReference(f); switch (Type.getType(f.getPrimitiveType()).getSort()) { @@ -732,77 +811,92 @@ break; case Type.ARRAY: - case Type.OBJECT: { - final Label end = new Label(); - cgs.pushFieldValue(); - mv.visitJumpInsn(IFNULL, end); - - if (f.getPrimitiveType() == byte[].class) { - cgs.pushCodedOutputStream(); - cgs.push(f.getColumnID()); - cgs.push(WireFormat.FieldType.BYTES.getWireType()); - mv.visitMethodInsn(INVOKEVIRTUAL, - codedOutputStream.getInternalName(), "writeTag", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] { - Type.INT_TYPE, Type.INT_TYPE})); - - cgs.pushCodedOutputStream(); + case Type.OBJECT: + { + final Label end = new Label(); cgs.pushFieldValue(); - mv.visitInsn(ARRAYLENGTH); - mv.visitMethodInsn(INVOKEVIRTUAL, - codedOutputStream.getInternalName(), "writeRawVarint32", Type - .getMethodDescriptor(Type.VOID_TYPE, - new Type[] {Type.INT_TYPE})); + mv.visitJumpInsn(IFNULL, end); - cgs.pushCodedOutputStream(); - cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, - codedOutputStream.getInternalName(), "writeRawBytes", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type - .getType(byte[].class)})); + if (f.getPrimitiveType() == byte[].class) { + cgs.pushCodedOutputStream(); + cgs.push(f.getColumnID()); + cgs.push(WireFormat.FieldType.BYTES.getWireType()); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedOutputStream.getInternalName(), + "writeTag", + Type.getMethodDescriptor( + Type.VOID_TYPE, new Type[] {Type.INT_TYPE, Type.INT_TYPE})); - } else { - cgs.pushCodedOutputStream(); - cgs.push(f.getColumnID()); - cgs.pushFieldValue(); + cgs.pushCodedOutputStream(); + cgs.pushFieldValue(); + mv.visitInsn(ARRAYLENGTH); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedOutputStream.getInternalName(), + "writeRawVarint32", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE})); - if (f.getPrimitiveType() == String.class) { - cgs.write("writeString", string); - - } else if (f.getPrimitiveType() == java.sql.Timestamp.class - || f.getPrimitiveType() == java.util.Date.class - || f.getPrimitiveType() == java.sql.Date.class) { - String tsType = - Type.getType(f.getPrimitiveType()).getInternalName(); - mv.visitMethodInsn(INVOKEVIRTUAL, tsType, "getTime", Type - .getMethodDescriptor(Type.LONG_TYPE, new Type[] {})); - cgs.write("writeFixed64", Type.LONG_TYPE); - - } else if (f.getPrimitiveType().isEnum()) { - mv.visitMethodInsn(INVOKEVIRTUAL, enumType.getInternalName(), - "ordinal", // - Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {})); - cgs.write("writeEnum", Type.INT_TYPE); + cgs.pushCodedOutputStream(); + cgs.pushFieldValue(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedOutputStream.getInternalName(), + "writeRawBytes", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.getType(byte[].class)})); } else { - throw new OrmException("Type " + f.getPrimitiveType() - + " not supported for field " + f.getPathToFieldName()); + cgs.pushCodedOutputStream(); + cgs.push(f.getColumnID()); + cgs.pushFieldValue(); + + if (f.getPrimitiveType() == String.class) { + cgs.write("writeString", string); + + } else if (f.getPrimitiveType() == java.sql.Timestamp.class + || f.getPrimitiveType() == java.util.Date.class + || f.getPrimitiveType() == java.sql.Date.class) { + String tsType = Type.getType(f.getPrimitiveType()).getInternalName(); + mv.visitMethodInsn( + INVOKEVIRTUAL, + tsType, + "getTime", + Type.getMethodDescriptor(Type.LONG_TYPE, new Type[] {})); + cgs.write("writeFixed64", Type.LONG_TYPE); + + } else if (f.getPrimitiveType().isEnum()) { + mv.visitMethodInsn( + INVOKEVIRTUAL, + enumType.getInternalName(), + "ordinal", // + Type.getMethodDescriptor(Type.INT_TYPE, new Type[] {})); + cgs.write("writeEnum", Type.INT_TYPE); + + } else { + throw new OrmException( + "Type " + + f.getPrimitiveType() + + " not supported for field " + + f.getPathToFieldName()); + } } + mv.visitLabel(end); + break; } - mv.visitLabel(end); - break; - } default: - throw new OrmException("Type " + f.getPrimitiveType() - + " not supported for field " + f.getPathToFieldName()); + throw new OrmException( + "Type " + f.getPrimitiveType() + " not supported for field " + f.getPathToFieldName()); } } private void implementMergeFromObject() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "mergeFrom", Type.getMethodDescriptor( - Type.VOID_TYPE, new Type[] {codedInputStream, object}), null, + cw.visitMethod( + ACC_PUBLIC, + "mergeFrom", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {codedInputStream, object}), + null, new String[] {}); mv.visitCode(); @@ -810,9 +904,11 @@ mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitTypeInsn(CHECKCAST, pojoType.getInternalName()); - mv.visitMethodInsn(INVOKEVIRTUAL, implTypeName, "mergeFrom", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {codedInputStream, - pojoType})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + implTypeName, + "mergeFrom", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {codedInputStream, pojoType})); mv.visitInsn(RETURN); mv.visitMaxs(-1, -1); @@ -821,8 +917,11 @@ private void implementMergeFromSelf() throws OrmException { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, "mergeFrom", Type.getMethodDescriptor( - Type.VOID_TYPE, new Type[] {codedInputStream, pojoType}), null, + cw.visitMethod( + ACC_PUBLIC, + "mergeFrom", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {codedInputStream, pojoType}), + null, new String[] {}); mv.visitCode(); final DecodeCGS cgs = new DecodeCGS(mv); @@ -837,8 +936,9 @@ mv.visitEnd(); } - private void decodeMessage(final JavaColumnModel[] myFields, - final MethodVisitor mv, final DecodeCGS cgs) throws OrmException { + private void decodeMessage( + final JavaColumnModel[] myFields, final MethodVisitor mv, final DecodeCGS cgs) + throws OrmException { final Label nextField = new Label(); final Label end = new Label(); mv.visitLabel(nextField); @@ -902,8 +1002,8 @@ cgs.ncallInt("checkLastTagWas", Type.VOID_TYPE); } - private void decodeField(final MethodVisitor mv, final DecodeCGS cgs, - final JavaColumnModel f) throws OrmException { + private void decodeField(final MethodVisitor mv, final DecodeCGS cgs, final JavaColumnModel f) + throws OrmException { if (f.isNested()) { final NestedCodec n = nestedFor(f); final Label load = new Label(); @@ -914,13 +1014,14 @@ // Since the field isn't initialized, construct it // cgs.fieldSetBegin(); - mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType - .getDescriptor()); - mv.visitMethodInsn(INVOKEVIRTUAL, n.codecType.getInternalName(), - "newInstance", Type.getMethodDescriptor(n.pojoType, new Type[] {})); + mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType.getDescriptor()); + mv.visitMethodInsn( + INVOKEVIRTUAL, + n.codecType.getInternalName(), + "newInstance", + Type.getMethodDescriptor(n.pojoType, new Type[] {})); if (object.equals(n.pojoType)) { - mv.visitTypeInsn(CHECKCAST, Type.getType(f.getNestedClass()) - .getInternalName()); + mv.visitTypeInsn(CHECKCAST, Type.getType(f.getNestedClass()).getInternalName()); } cgs.fieldSetEnd(); @@ -934,13 +1035,14 @@ cgs.ncallInt("pushLimit", Type.INT_TYPE); mv.visitVarInsn(ISTORE, limitVar); - mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType - .getDescriptor()); + mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType.getDescriptor()); cgs.pushCodedInputStream(); cgs.pushFieldValue(); - mv.visitMethodInsn(INVOKEVIRTUAL, n.codecType.getInternalName(), - "mergeFrom", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { - codedInputStream, n.pojoType})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + n.codecType.getInternalName(), + "mergeFrom", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {codedInputStream, n.pojoType})); cgs.pushCodedInputStream(); mv.visitVarInsn(ILOAD, limitVar); @@ -955,55 +1057,58 @@ } } - private void decodeCollection(final MethodVisitor mv, final DecodeCGS cgs, - final JavaColumnModel f) throws OrmException { + private void decodeCollection( + final MethodVisitor mv, final DecodeCGS cgs, final JavaColumnModel f) throws OrmException { final Class<?> valClazz = (Class<?>) f.getArgumentTypes()[0]; final Type valType = Type.getType(valClazz); final JavaColumnModel col = collectionColumn(f, valClazz); - final DecodeCGS ng = new DecodeCGS(mv) { - { - tagVar = cgs.tagVar; - setEntityType(valType); - } + final DecodeCGS ng = + new DecodeCGS(mv) { + { + tagVar = cgs.tagVar; + setEntityType(valType); + } - @Override - public int newLocal() { - return cgs.newLocal(); - } + @Override + public int newLocal() { + return cgs.newLocal(); + } - @Override - public void freeLocal(int index) { - cgs.freeLocal(index); - } + @Override + public void freeLocal(int index) { + cgs.freeLocal(index); + } - @Override - protected void appendGetField(final ColumnModel c) { - if (c != col) { - super.appendGetField(c); - } - } + @Override + protected void appendGetField(final ColumnModel c) { + if (c != col) { + super.appendGetField(c); + } + } - @Override - public void fieldSetBegin() { - if (col.isNested()) { - super.fieldSetBegin(); - } else { - cgs.pushFieldValue(); - } - } + @Override + public void fieldSetBegin() { + if (col.isNested()) { + super.fieldSetBegin(); + } else { + cgs.pushFieldValue(); + } + } - @Override - public void fieldSetEnd() { - if (col.isNested()) { - super.fieldSetEnd(); - } else { - mv.visitMethodInsn(INVOKEINTERFACE, collection.getInternalName(), - "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, - new Type[] {object})); - mv.visitInsn(POP); - } - } - }; + @Override + public void fieldSetEnd() { + if (col.isNested()) { + super.fieldSetEnd(); + } else { + mv.visitMethodInsn( + INVOKEINTERFACE, + collection.getInternalName(), + "add", + Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {object})); + mv.visitInsn(POP); + } + } + }; final Label notnull = new Label(); cgs.setFieldReference(f); @@ -1031,9 +1136,11 @@ mv.visitTypeInsn(NEW, illegalStateException.getInternalName()); mv.visitInsn(DUP); mv.visitLdcInsn("Field " + f.getPathToFieldName() + " not initialized"); - mv.visitMethodInsn(INVOKESPECIAL, - illegalStateException.getInternalName(), "<init>", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {string})); + mv.visitMethodInsn( + INVOKESPECIAL, + illegalStateException.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {string})); mv.visitInsn(ATHROW); concreteType = null; } @@ -1041,8 +1148,11 @@ cgs.fieldSetBegin(); mv.visitTypeInsn(NEW, concreteType.getInternalName()); mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, concreteType.getInternalName(), - "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKESPECIAL, + concreteType.getInternalName(), + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); cgs.fieldSetEnd(); } mv.visitLabel(notnull); @@ -1052,10 +1162,12 @@ // final NestedCodec n = nestedFor(col); ng.objVar = cgs.newLocal(); - mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType - .getDescriptor()); - mv.visitMethodInsn(INVOKEVIRTUAL, n.codecType.getInternalName(), - "newInstance", Type.getMethodDescriptor(n.pojoType, new Type[] {})); + mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType.getDescriptor()); + mv.visitMethodInsn( + INVOKEVIRTUAL, + n.codecType.getInternalName(), + "newInstance", + Type.getMethodDescriptor(n.pojoType, new Type[] {})); mv.visitVarInsn(ASTORE, ng.objVar); // read the length, set a new limit, decode the message, validate @@ -1067,13 +1179,14 @@ cgs.ncallInt("pushLimit", Type.INT_TYPE); mv.visitVarInsn(ISTORE, limitVar); - mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType - .getDescriptor()); + mv.visitFieldInsn(GETSTATIC, implTypeName, n.field, n.codecType.getDescriptor()); cgs.pushCodedInputStream(); mv.visitVarInsn(ALOAD, ng.objVar); - mv.visitMethodInsn(INVOKEVIRTUAL, n.codecType.getInternalName(), - "mergeFrom", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { - codedInputStream, n.pojoType})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + n.codecType.getInternalName(), + "mergeFrom", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {codedInputStream, n.pojoType})); cgs.pushCodedInputStream(); mv.visitVarInsn(ILOAD, limitVar); @@ -1082,22 +1195,25 @@ cgs.pushFieldValue(); mv.visitVarInsn(ALOAD, ng.objVar); - mv.visitMethodInsn(INVOKEINTERFACE, collection.getInternalName(), "add", + mv.visitMethodInsn( + INVOKEINTERFACE, + collection.getInternalName(), + "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {object})); mv.visitInsn(POP); cgs.freeLocal(ng.objVar); } else if (col.isCollection()) { - throw new OrmException("Cannot nest collection as member of another" - + " collection: " + f.getPathToFieldName()); + throw new OrmException( + "Cannot nest collection as member of another" + " collection: " + f.getPathToFieldName()); } else { decodeScalar(mv, ng, col); } } - private static void decodeScalar(final MethodVisitor mv, final DecodeCGS cgs, - final JavaColumnModel f) throws OrmException { + private static void decodeScalar( + final MethodVisitor mv, final DecodeCGS cgs, final JavaColumnModel f) throws OrmException { cgs.setFieldReference(f); cgs.fieldSetBegin(); switch (Type.getType(f.getPrimitiveType()).getSort()) { @@ -1130,9 +1246,11 @@ default: if (f.getPrimitiveType() == byte[].class) { cgs.call("readBytes", byteString); - mv.visitMethodInsn(INVOKEVIRTUAL, byteString.getInternalName(), - "toByteArray", Type.getMethodDescriptor(Type - .getType(byte[].class), new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + byteString.getInternalName(), + "toByteArray", + Type.getMethodDescriptor(Type.getType(byte[].class), new Type[] {})); } else if (f.getPrimitiveType() == String.class) { cgs.call("readString", string); @@ -1144,21 +1262,28 @@ mv.visitTypeInsn(NEW, tsType); mv.visitInsn(DUP); cgs.call("readFixed64", Type.LONG_TYPE); - mv.visitMethodInsn(INVOKESPECIAL, tsType, "<init>", // - Type.getMethodDescriptor(Type.VOID_TYPE, - new Type[] {Type.LONG_TYPE})); + mv.visitMethodInsn( + INVOKESPECIAL, + tsType, + "<init>", // + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.LONG_TYPE})); } else if (f.getPrimitiveType().isEnum()) { Type et = Type.getType(f.getPrimitiveType()); - mv.visitMethodInsn(INVOKESTATIC, et.getInternalName(), "values", Type - .getMethodDescriptor(Type.getType("[" + et.getDescriptor()), - new Type[] {})); + mv.visitMethodInsn( + INVOKESTATIC, + et.getInternalName(), + "values", + Type.getMethodDescriptor(Type.getType("[" + et.getDescriptor()), new Type[] {})); cgs.call("readEnum", Type.INT_TYPE); mv.visitInsn(AALOAD); } else { - throw new OrmException("Type " + f.getPrimitiveType() - + " not supported for field " + f.getPathToFieldName()); + throw new OrmException( + "Type " + + f.getPrimitiveType() + + " not supported for field " + + f.getPathToFieldName()); } break; } @@ -1173,8 +1298,11 @@ } void doinc(String name, Type... args) { - mv.visitMethodInsn(INVOKESTATIC, codedOutputStream.getInternalName(), - name, Type.getMethodDescriptor(Type.INT_TYPE, args)); + mv.visitMethodInsn( + INVOKESTATIC, + codedOutputStream.getInternalName(), + name, + Type.getMethodDescriptor(Type.INT_TYPE, args)); doinc(); } @@ -1203,9 +1331,11 @@ } void write(String name, Type arg) { - mv.visitMethodInsn(INVOKEVIRTUAL, codedOutputStream.getInternalName(), - name, Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { - Type.INT_TYPE, arg})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedOutputStream.getInternalName(), + name, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE, arg})); } } @@ -1224,13 +1354,19 @@ void call(String name, Type ret) { pushCodedInputStream(); - mv.visitMethodInsn(INVOKEVIRTUAL, codedInputStream.getInternalName(), - name, Type.getMethodDescriptor(ret, new Type[] {})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedInputStream.getInternalName(), + name, + Type.getMethodDescriptor(ret, new Type[] {})); } void ncallInt(String name, Type ret) { - mv.visitMethodInsn(INVOKEVIRTUAL, codedInputStream.getInternalName(), - name, Type.getMethodDescriptor(ret, new Type[] {Type.INT_TYPE})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + codedInputStream.getInternalName(), + name, + Type.getMethodDescriptor(ret, new Type[] {Type.INT_TYPE})); } @Override
diff --git a/src/main/java/com/google/gwtorm/protobuf/CustomCodec.java b/src/main/java/com/google/gwtorm/protobuf/CustomCodec.java index 3462a3c..8a25690 100644 --- a/src/main/java/com/google/gwtorm/protobuf/CustomCodec.java +++ b/src/main/java/com/google/gwtorm/protobuf/CustomCodec.java
@@ -21,11 +21,10 @@ /** * Identity of a custom {@link ProtobufCodec} for a {@code Column}. - * <p> - * Additional annotation tagged onto a {@code Column} field that carries the - * name of a custom {@link ProtobufCodec} that should be used to handle that - * field. The field data will be treated as an opaque binary sequence, so its - * {@link ProtobufCodec#sizeof(Object)} method must be accurate. + * + * <p>Additional annotation tagged onto a {@code Column} field that carries the name of a custom + * {@link ProtobufCodec} that should be used to handle that field. The field data will be treated as + * an opaque binary sequence, so its {@link ProtobufCodec#sizeof(Object)} method must be accurate. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD)
diff --git a/src/main/java/com/google/gwtorm/protobuf/ProtobufCodec.java b/src/main/java/com/google/gwtorm/protobuf/ProtobufCodec.java index 43202b1..aa5d5d1 100644 --- a/src/main/java/com/google/gwtorm/protobuf/ProtobufCodec.java +++ b/src/main/java/com/google/gwtorm/protobuf/ProtobufCodec.java
@@ -19,7 +19,6 @@ import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import com.google.protobuf.InvalidProtocolBufferException; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -27,9 +26,9 @@ /** * Encode and decode an arbitrary Java object as a Protobuf message. - * <p> - * The object must use the {@link Column} annotations to denote the fields that - * should be encoded or decoded. + * + * <p>The object must use the {@link Column} annotations to denote the fields that should be encoded + * or decoded. */ public abstract class ProtobufCodec<T> { /** Encode the object into an immutable byte string. */ @@ -71,10 +70,11 @@ /** Encode the object into a ByteBuffer. */ public void encode(T obj, ByteBuffer buf) { if (buf.hasArray()) { - CodedOutputStream out = CodedOutputStream.newInstance( // - buf.array(), // - buf.position(), // - buf.remaining()); + CodedOutputStream out = + CodedOutputStream.newInstance( // + buf.array(), // + buf.position(), // + buf.remaining()); try { encode(obj, out); out.flush(); @@ -96,8 +96,8 @@ /** * Encodes the object, prefixed by its encoded length. - * <p> - * The length is encoded as a raw varint with no tag. + * + * <p>The length is encoded as a raw varint with no tag. * * @param obj the object to encode. * @param out stream that will receive the object's data. @@ -116,10 +116,10 @@ /** * Encode the object to the supplied output stream. - * <p> - * The stream {@code out} is not flushed by this method. Callers that need the - * entire byte representation after invoking encode must flush the stream to - * ensure its intermediate buffers have been written to the backing store. + * + * <p>The stream {@code out} is not flushed by this method. Callers that need the entire byte + * representation after invoking encode must flush the stream to ensure its intermediate buffers + * have been written to the backing store. * * @param obj the object to encode. * @param out the stream to encode the object onto. @@ -205,10 +205,11 @@ /** Decode a byte buffer into an existing object instance. */ public void mergeFrom(ByteBuffer buf, T obj) { if (buf.hasArray()) { - CodedInputStream in = CodedInputStream.newInstance( // - buf.array(), // - buf.position(), // - buf.remaining()); + CodedInputStream in = + CodedInputStream.newInstance( // + buf.array(), // + buf.position(), // + buf.remaining()); try { mergeFrom(in, obj); } catch (IOException err) {
diff --git a/src/main/java/com/google/gwtorm/schema/ColumnModel.java b/src/main/java/com/google/gwtorm/schema/ColumnModel.java index 066b363..c9a88d2 100644 --- a/src/main/java/com/google/gwtorm/schema/ColumnModel.java +++ b/src/main/java/com/google/gwtorm/schema/ColumnModel.java
@@ -16,7 +16,6 @@ import com.google.gwtorm.client.Column; import com.google.gwtorm.server.OrmException; - import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; @@ -36,14 +35,13 @@ protected boolean notNull; protected ColumnModel() { - nestedColumns = Collections.<ColumnModel> emptyList(); + nestedColumns = Collections.<ColumnModel>emptyList(); } - protected void initName(final String fieldName, final Column col) - throws OrmException { + protected void initName(final String fieldName, final Column col) throws OrmException { if (col == null) { - throw new OrmException("Field " + fieldName + " is missing " - + Column.class.getName() + " annotation"); + throw new OrmException( + "Field " + fieldName + " is missing " + Column.class.getName() + " annotation"); } column = col; origName = Util.any(column.name(), Util.makeSqlFriendly(fieldName)); @@ -71,8 +69,8 @@ Set<Integer> ids = new HashSet<>(); for (final ColumnModel c : nestedColumns) { if (!ids.add(c.columnId)) { - throw new OrmException("Duplicate @Column id " + c.columnId + " in " - + c.getPathToFieldName()); + throw new OrmException( + "Duplicate @Column id " + c.columnId + " in " + c.getPathToFieldName()); } } }
diff --git a/src/main/java/com/google/gwtorm/schema/QueryModel.java b/src/main/java/com/google/gwtorm/schema/QueryModel.java index 149e3d7..f8141ee 100644 --- a/src/main/java/com/google/gwtorm/schema/QueryModel.java +++ b/src/main/java/com/google/gwtorm/schema/QueryModel.java
@@ -19,36 +19,33 @@ import com.google.gwtorm.schema.sql.SqlDialect; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.Query; - -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.Tree; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.antlr.runtime.CommonToken; +import org.antlr.runtime.tree.CommonTree; +import org.antlr.runtime.tree.Tree; public class QueryModel { private final RelationModel model; private final String name; private final Tree parsedQuery; - public QueryModel(final RelationModel rel, final String queryName, - final Query q) throws OrmException { + public QueryModel(final RelationModel rel, final String queryName, final Query q) + throws OrmException { this(rel, queryName, queryTextOf(queryName, q)); } - private static String queryTextOf(String queryName, Query q) - throws OrmException { + private static String queryTextOf(String queryName, Query q) throws OrmException { if (q == null) { - throw new OrmException("Query " + queryName + " is missing " - + Query.class.getName() + " annotation"); + throw new OrmException( + "Query " + queryName + " is missing " + Query.class.getName() + " annotation"); } return q.value(); } - public QueryModel(final RelationModel rel, final String queryName, - final String queryText) throws OrmException { + public QueryModel(final RelationModel rel, final String queryName, final String queryText) + throws OrmException { model = rel; name = queryName; @@ -107,9 +104,9 @@ for (int i = 0; i < node.getChildCount(); i++) { Tree sortOrder = node.getChild(i); Tree id = sortOrder.getChild(0); - r.add(new OrderBy( - ((QueryParser.Column) id).getField(), - sortOrder.getType() == QueryParser.DESC)); + r.add( + new OrderBy( + ((QueryParser.Column) id).getField(), sortOrder.getType() == QueryParser.DESC)); } } } @@ -164,8 +161,7 @@ public boolean hasLimitParameter() { final Tree limit = findLimit(parsedQuery); - return limit != null - && limit.getChild(0).getType() == QueryParser.PLACEHOLDER; + return limit != null && limit.getChild(0).getType() == QueryParser.PLACEHOLDER; } public int getStaticLimit() { @@ -273,29 +269,30 @@ format(fmt, node.getChild(1)); break; - case QueryParser.ID: { - final ColumnModel col = ((QueryParser.Column) node).getField(); - if (!col.isSqlPrimitive()) { - throw new IllegalStateException("Unexpanded nested field"); + case QueryParser.ID: + { + final ColumnModel col = ((QueryParser.Column) node).getField(); + if (!col.isSqlPrimitive()) { + throw new IllegalStateException("Unexpanded nested field"); + } + fmt.buf.append(fmt.tableAlias); + fmt.buf.append('.'); + fmt.buf.append(col.getColumnName()); + break; } - fmt.buf.append(fmt.tableAlias); - fmt.buf.append('.'); - fmt.buf.append(col.getColumnName()); - break; - } case QueryParser.PLACEHOLDER: fmt.buf.append(fmt.dialect.getParameterPlaceHolder(fmt.nthParam++)); break; case QueryParser.TRUE: - fmt.buf.append(((SqlBooleanTypeInfo) fmt.dialect - .getSqlTypeInfo(Boolean.TYPE)).getTrueLiteralValue()); + fmt.buf.append( + ((SqlBooleanTypeInfo) fmt.dialect.getSqlTypeInfo(Boolean.TYPE)).getTrueLiteralValue()); break; case QueryParser.FALSE: - fmt.buf.append(((SqlBooleanTypeInfo) fmt.dialect - .getSqlTypeInfo(Boolean.TYPE)).getFalseLiteralValue()); + fmt.buf.append( + ((SqlBooleanTypeInfo) fmt.dialect.getSqlTypeInfo(Boolean.TYPE)).getFalseLiteralValue()); break; case QueryParser.CONSTANT_INTEGER: @@ -313,8 +310,9 @@ } final ColumnModel col = ((QueryParser.Column) id).getField(); if (col.isNested()) { - for (final Iterator<ColumnModel> cItr = - col.getAllLeafColumns().iterator(); cItr.hasNext();) { + for (final Iterator<ColumnModel> cItr = col.getAllLeafColumns().iterator(); + cItr.hasNext(); + ) { fmt.buf.append(fmt.tableAlias); fmt.buf.append('.'); fmt.buf.append(cItr.next().getColumnName()); @@ -363,24 +361,25 @@ case QueryParser.LE: case QueryParser.GT: case QueryParser.GE: - case QueryParser.EQ: { - final Column qpc = (QueryParser.Column) node.getChild(0); - final ColumnModel f = qpc.getField(); - if (f.isNested()) { - final CommonTree join; + case QueryParser.EQ: + { + final Column qpc = (QueryParser.Column) node.getChild(0); + final ColumnModel f = qpc.getField(); + if (f.isNested()) { + final CommonTree join; - join = new CommonTree(new CommonToken(QueryParser.AND)); - for (final ColumnModel c : f.getAllLeafColumns()) { - final Tree op; + join = new CommonTree(new CommonToken(QueryParser.AND)); + for (final ColumnModel c : f.getAllLeafColumns()) { + final Tree op; - op = node.dupNode(); - op.addChild(new QueryParser.Column(qpc, c)); - op.addChild(node.getChild(1).dupNode()); - join.addChild(op); + op = node.dupNode(); + op.addChild(new QueryParser.Column(qpc, c)); + op.addChild(node.getChild(1).dupNode()); + join.addChild(op); + } + return join; } - return join; } - } } final Tree r = node.dupNode();
diff --git a/src/main/java/com/google/gwtorm/schema/RelationModel.java b/src/main/java/com/google/gwtorm/schema/RelationModel.java index ebfb050..8f1f555 100644 --- a/src/main/java/com/google/gwtorm/schema/RelationModel.java +++ b/src/main/java/com/google/gwtorm/schema/RelationModel.java
@@ -20,7 +20,6 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.PrimaryKey; import com.google.gwtorm.server.Relation; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -46,11 +45,10 @@ queries = Lists.newArrayList(); } - protected void initName(final String method, final Relation rel) - throws OrmException { + protected void initName(final String method, final Relation rel) throws OrmException { if (rel == null) { - throw new OrmException("Method " + method + " is missing " - + Relation.class.getName() + " annotation"); + throw new OrmException( + "Method " + method + " is missing " + Relation.class.getName() + " annotation"); } relation = rel; methodName = method; @@ -64,8 +62,8 @@ throw new OrmException("Duplicate fields " + field.getFieldName()); } if (columnsById.put(field.getColumnID(), field) != null) { - throw new OrmException("Duplicate @Column id " + field.getColumnID() - + " in " + field.getPathToFieldName()); + throw new OrmException( + "Duplicate @Column id " + field.getColumnID() + " in " + field.getPathToFieldName()); } if (field.isNested()) { @@ -81,9 +79,16 @@ private void registerColumn(final ColumnModel nc) throws OrmException { final ColumnModel name = columnsByColumnName.put(nc.getColumnName(), nc); if (name != null) { - throw new OrmException("Duplicate columns " + nc.getColumnName() + " in " - + getMethodName() + ":\n" + "prior " + name.getPathToFieldName() - + "\n next " + nc.getPathToFieldName()); + throw new OrmException( + "Duplicate columns " + + nc.getColumnName() + + " in " + + getMethodName() + + ":\n" + + "prior " + + name.getPathToFieldName() + + "\n next " + + nc.getPathToFieldName()); } } @@ -95,8 +100,7 @@ final ColumnModel field = getField(annotation.value()); if (field == null) { - throw new OrmException("Field " + annotation.value() + " not in " - + getEntityTypeClassName()); + throw new OrmException("Field " + annotation.value() + " not in " + getEntityTypeClassName()); } primaryKey = new KeyModel(name, field); @@ -108,14 +112,16 @@ protected void addQuery(final QueryModel q) throws OrmException { for (QueryModel e : queries) { if (e.getName().equals(q.getName())) { - throw new OrmException("Duplicate query " + q.getName() // - + " in " + getAccessInterfaceName()); + throw new OrmException( + "Duplicate query " + + q.getName() // + + " in " + + getAccessInterfaceName()); } } queries.add(q); } - public String getMethodName() { return methodName; } @@ -176,7 +182,7 @@ if (getPrimaryKey() != null) { return getPrimaryKey().getAllLeafColumns(); } - return Collections.<ColumnModel> emptyList(); + return Collections.<ColumnModel>emptyList(); } public Collection<QueryModel> getQueries() { @@ -211,14 +217,13 @@ r.append(relationName); r.append(" (\n"); - for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext();) { + for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext(); ) { final ColumnModel col = i.next(); r.append(col.getColumnName()); r.append(" "); r.append(dialect.getSqlTypeInfo(col).getSqlType(col, dialect)); - String check = - dialect.getSqlTypeInfo(col).getCheckConstraint(col, dialect); + String check = dialect.getSqlTypeInfo(col).getCheckConstraint(col, dialect); if (check != null) { r.append(' '); r.append(check); @@ -231,8 +236,7 @@ if (!getPrimaryKeyColumns().isEmpty()) { r.append(",PRIMARY KEY("); - for (final Iterator<ColumnModel> i = getPrimaryKeyColumns().iterator(); i - .hasNext();) { + for (final Iterator<ColumnModel> i = getPrimaryKeyColumns().iterator(); i.hasNext(); ) { final ColumnModel col = i.next(); r.append(col.getColumnName()); if (i.hasNext()) { @@ -250,7 +254,7 @@ public String getSelectSql(final SqlDialect dialect, final String tableAlias) { final StringBuilder r = new StringBuilder(); r.append("SELECT "); - for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext();) { + for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext(); ) { final ColumnModel col = i.next(); r.append(tableAlias); r.append('.'); @@ -271,7 +275,7 @@ r.append("INSERT INTO "); r.append(relationName); r.append("("); - for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext();) { + for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext(); ) { final ColumnModel col = i.next(); r.append(col.getColumnName()); if (i.hasNext()) { @@ -280,7 +284,7 @@ } r.append(")VALUES("); int nth = 1; - for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext();) { + for (final Iterator<ColumnModel> i = getColumns().iterator(); i.hasNext(); ) { i.next(); r.append(dialect.getParameterPlaceHolder(nth++)); if (i.hasNext()) { @@ -302,7 +306,7 @@ cols = new ArrayList<>(); cols.addAll(getDependentColumns()); cols.addAll(getRowVersionColumns()); - for (final Iterator<ColumnModel> i = cols.iterator(); i.hasNext();) { + for (final Iterator<ColumnModel> i = cols.iterator(); i.hasNext(); ) { final ColumnModel col = i.next(); r.append(col.getColumnName()); r.append("="); @@ -316,7 +320,7 @@ cols = new ArrayList<>(); cols.addAll(getPrimaryKeyColumns()); cols.addAll(getRowVersionColumns()); - for (final Iterator<ColumnModel> i = cols.iterator(); i.hasNext();) { + for (final Iterator<ColumnModel> i = cols.iterator(); i.hasNext(); ) { final ColumnModel col = i.next(); r.append(col.getColumnName()); r.append("="); @@ -337,7 +341,7 @@ final List<ColumnModel> cols = new ArrayList<>(); cols.addAll(getPrimaryKeyColumns()); cols.addAll(getRowVersionColumns()); - for (final Iterator<ColumnModel> i = cols.iterator(); i.hasNext();) { + for (final Iterator<ColumnModel> i = cols.iterator(); i.hasNext(); ) { final ColumnModel col = i.next(); r.append(col.getColumnName()); r.append("=");
diff --git a/src/main/java/com/google/gwtorm/schema/SchemaModel.java b/src/main/java/com/google/gwtorm/schema/SchemaModel.java index b8ed338..3f188c1 100644 --- a/src/main/java/com/google/gwtorm/schema/SchemaModel.java +++ b/src/main/java/com/google/gwtorm/schema/SchemaModel.java
@@ -16,7 +16,6 @@ import com.google.gwtorm.schema.sql.SqlDialect; import com.google.gwtorm.server.OrmException; - import java.util.Collection; import java.util.HashSet; import java.util.Map;
diff --git a/src/main/java/com/google/gwtorm/schema/SequenceModel.java b/src/main/java/com/google/gwtorm/schema/SequenceModel.java index e8a128e..0b56f85 100644 --- a/src/main/java/com/google/gwtorm/schema/SequenceModel.java +++ b/src/main/java/com/google/gwtorm/schema/SequenceModel.java
@@ -24,15 +24,14 @@ protected Sequence sequence; protected Class<?> returnType; - public SequenceModel(final String method, final Sequence seq, - final Class<?> type) throws OrmException { + public SequenceModel(final String method, final Sequence seq, final Class<?> type) + throws OrmException { if (seq == null) { - throw new OrmException("Method " + method + " is missing " - + Sequence.class.getName() + " annotation"); + throw new OrmException( + "Method " + method + " is missing " + Sequence.class.getName() + " annotation"); } if (type != Integer.TYPE && type != Long.TYPE) { - throw new OrmException("Sequence method " + method - + " must return int or long"); + throw new OrmException("Sequence method " + method + " must return int or long"); } sequence = seq;
diff --git a/src/main/java/com/google/gwtorm/schema/Util.java b/src/main/java/com/google/gwtorm/schema/Util.java index 6a55c72..287e573 100644 --- a/src/main/java/com/google/gwtorm/schema/Util.java +++ b/src/main/java/com/google/gwtorm/schema/Util.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.schema; - public class Util { private static int nameCounter; @@ -43,14 +42,13 @@ } String friendlyName = r.toString(); if (friendlyName.length() > 30) { - throw new IllegalArgumentException(String.format( - "Identifier '%s' for name '%s' is greater than 30 characters", - friendlyName, name)); + throw new IllegalArgumentException( + String.format( + "Identifier '%s' for name '%s' is greater than 30 characters", friendlyName, name)); } return friendlyName; } - public static String any(final String a, final String b) { if (a != null && a.length() > 0) { return a; @@ -92,6 +90,5 @@ return false; } - private Util() { - } + private Util() {} }
diff --git a/src/main/java/com/google/gwtorm/schema/java/JavaColumnModel.java b/src/main/java/com/google/gwtorm/schema/java/JavaColumnModel.java index 9e2b30c..f3d9102 100644 --- a/src/main/java/com/google/gwtorm/schema/java/JavaColumnModel.java +++ b/src/main/java/com/google/gwtorm/schema/java/JavaColumnModel.java
@@ -20,7 +20,6 @@ import com.google.gwtorm.schema.ColumnModel; import com.google.gwtorm.schema.Util; import com.google.gwtorm.server.OrmException; - import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; @@ -29,7 +28,6 @@ import java.util.Arrays; import java.util.List; - public class JavaColumnModel extends ColumnModel { public static List<Field> getDeclaredFields(Class<?> in) { return sort(Arrays.asList(in.getDeclaredFields())); @@ -69,25 +67,38 @@ initName(fieldName, field.getAnnotation(Column.class)); if (Modifier.isPrivate(field.getModifiers())) { - throw new OrmException("Field " + field.getName() + " of " - + field.getDeclaringClass().getName() + " must not be private"); + throw new OrmException( + "Field " + + field.getName() + + " of " + + field.getDeclaringClass().getName() + + " must not be private"); } if (Modifier.isFinal(field.getModifiers())) { - throw new OrmException("Field " + field.getName() + " of " - + field.getDeclaringClass().getName() + " must not be final"); + throw new OrmException( + "Field " + + field.getName() + + " of " + + field.getDeclaringClass().getName() + + " must not be final"); } rowVersion = field.getAnnotation(RowVersion.class) != null; if (rowVersion && field.getType() != Integer.TYPE) { - throw new OrmException("Field " + field.getName() + " of " - + field.getDeclaringClass().getName() + " must have type 'int'"); + throw new OrmException( + "Field " + + field.getName() + + " of " + + field.getDeclaringClass().getName() + + " must have type 'int'"); } initNested(); } - public JavaColumnModel(Field f, final String fieldPath, final int columnId, - final Class<?> columnType) throws OrmException { + public JavaColumnModel( + Field f, final String fieldPath, final int columnId, final Class<?> columnType) + throws OrmException { this.field = f; this.fieldName = fieldPath; this.columnName = fieldPath;
diff --git a/src/main/java/com/google/gwtorm/schema/java/JavaRelationModel.java b/src/main/java/com/google/gwtorm/schema/java/JavaRelationModel.java index 3a06407..b2b8f16 100644 --- a/src/main/java/com/google/gwtorm/schema/java/JavaRelationModel.java +++ b/src/main/java/com/google/gwtorm/schema/java/JavaRelationModel.java
@@ -23,7 +23,6 @@ import com.google.gwtorm.server.Query; import com.google.gwtorm.server.Relation; import com.google.gwtorm.server.ResultSet; - import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; @@ -41,21 +40,23 @@ initName(method.getName(), m.getAnnotation(Relation.class)); accessType = method.getReturnType(); - if (accessType.getInterfaces().length != 1 - || accessType.getInterfaces()[0] != Access.class) { - throw new OrmException("Method " + method.getName() + " in " - + method.getDeclaringClass().getName() - + " must return a direct extension of " + Access.class); + if (accessType.getInterfaces().length != 1 || accessType.getInterfaces()[0] != Access.class) { + throw new OrmException( + "Method " + + method.getName() + + " in " + + method.getDeclaringClass().getName() + + " must return a direct extension of " + + Access.class); } final Type gt = accessType.getGenericInterfaces()[0]; if (!(gt instanceof ParameterizedType)) { - throw new OrmException(accessType.getName() - + " must specify entity type parameter for " + Access.class); + throw new OrmException( + accessType.getName() + " must specify entity type parameter for " + Access.class); } - entityType = - (Class<?>) ((ParameterizedType) gt).getActualTypeArguments()[0]; + entityType = (Class<?>) ((ParameterizedType) gt).getActualTypeArguments()[0]; initColumns(); initQueriesAndKeys(); @@ -82,18 +83,18 @@ continue; } if (m.getReturnType() != entityType) { - throw new OrmException("PrimaryKey " + m.getName() + " must return " - + entityType.getName()); + throw new OrmException( + "PrimaryKey " + m.getName() + " must return " + entityType.getName()); } initPrimaryKey(m.getName(), m.getAnnotation(PrimaryKey.class)); } else if (m.getAnnotation(Query.class) != null) { if (!ResultSet.class.isAssignableFrom(m.getReturnType()) || !(m.getGenericReturnType() instanceof ParameterizedType) - || ((ParameterizedType) m.getGenericReturnType()) - .getActualTypeArguments()[0] != entityType) { - throw new OrmException("Query " + m.getName() + " must return" - + " ResultSet<" + entityType.getName() + ">"); + || ((ParameterizedType) m.getGenericReturnType()).getActualTypeArguments()[0] + != entityType) { + throw new OrmException( + "Query " + m.getName() + " must return" + " ResultSet<" + entityType.getName() + ">"); } addQuery(new QueryModel(this, m.getName(), m.getAnnotation(Query.class))); }
diff --git a/src/main/java/com/google/gwtorm/schema/java/JavaSchemaModel.java b/src/main/java/com/google/gwtorm/schema/java/JavaSchemaModel.java index cbec78b..a3a2c0b 100644 --- a/src/main/java/com/google/gwtorm/schema/java/JavaSchemaModel.java +++ b/src/main/java/com/google/gwtorm/schema/java/JavaSchemaModel.java
@@ -21,11 +21,9 @@ import com.google.gwtorm.server.Relation; import com.google.gwtorm.server.Schema; import com.google.gwtorm.server.Sequence; - import java.io.PrintWriter; import java.lang.reflect.Method; - public class JavaSchemaModel extends SchemaModel { private final Class<?> schema; @@ -33,14 +31,12 @@ schema = schemaInterface; if (!schema.isInterface()) { - throw new OrmException("Schema " + schema.getName() - + " must be an interface"); + throw new OrmException("Schema " + schema.getName() + " must be an interface"); } - if (schema.getInterfaces().length != 1 - || schema.getInterfaces()[0] != Schema.class) { - throw new OrmException("Schema " + schema.getName() - + " must only extend " + Schema.class.getName()); + if (schema.getInterfaces().length != 1 || schema.getInterfaces()[0] != Schema.class) { + throw new OrmException( + "Schema " + schema.getName() + " must only extend " + Schema.class.getName()); } for (final Method m : schema.getDeclaredMethods()) {
diff --git a/src/main/java/com/google/gwtorm/schema/java/ProtoFileGenerator.java b/src/main/java/com/google/gwtorm/schema/java/ProtoFileGenerator.java index 900ce02..986d72e 100644 --- a/src/main/java/com/google/gwtorm/schema/java/ProtoFileGenerator.java +++ b/src/main/java/com/google/gwtorm/schema/java/ProtoFileGenerator.java
@@ -18,9 +18,6 @@ import com.google.gwtorm.schema.ColumnModel; import com.google.gwtorm.schema.RelationModel; import com.google.gwtorm.schema.Util; - -import org.objectweb.asm.Type; - import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; @@ -28,6 +25,7 @@ import java.util.Comparator; import java.util.HashSet; import java.util.List; +import org.objectweb.asm.Type; class ProtoFileGenerator { private static final Comparator<ColumnModel> COLUMN_COMPARATOR = @@ -86,18 +84,28 @@ out.print("message Any" + schemaName + "PrimaryKey {\n"); for (RelationModel r : sortRelations(rels)) { ColumnModel pk = r.getPrimaryKey().getField(); - out.print("\toptional " + getType(pk) + " " - + r.getRelationName().toLowerCase() + " = " + r.getRelationID() - + ";\n"); + out.print( + "\toptional " + + getType(pk) + + " " + + r.getRelationName().toLowerCase() + + " = " + + r.getRelationID() + + ";\n"); } out.print("}\n"); out.print("\n"); out.print("message Any" + schemaName + " {\n"); for (RelationModel r : sortRelations(rels)) { - out.print("\toptional " + getMessageName(r) + " " - + r.getRelationName().toLowerCase() + " = " + r.getRelationID() - + ";\n"); + out.print( + "\toptional " + + getMessageName(r) + + " " + + r.getRelationName().toLowerCase() + + " = " + + r.getRelationID() + + ";\n"); } out.print("}\n"); } @@ -121,8 +129,7 @@ out.print("}\n\n"); } - private void generateMessage(ColumnModel parent, PrintWriter out, - boolean required) { + private void generateMessage(ColumnModel parent, PrintWriter out, boolean required) { // Handle base cases if (!parent.isNested()) { return; @@ -186,8 +193,7 @@ return list; } - private static List<RelationModel> sortRelations( - Collection<RelationModel> rels) { + private static List<RelationModel> sortRelations(Collection<RelationModel> rels) { ArrayList<RelationModel> list = new ArrayList<>(rels); Collections.sort(list, RELATION_COMPARATOR); return list; @@ -210,22 +216,21 @@ case Type.LONG: return "int64"; case Type.ARRAY: - case Type.OBJECT: { - if (clazz == byte[].class) { - return "bytes"; - } else if (clazz == String.class) { - return "string"; - } else if (clazz == java.sql.Timestamp.class) { - return "fixed64"; - } else { - throw new RuntimeException("Type " + clazz - + " not supported on protobuf!"); + case Type.OBJECT: + { + if (clazz == byte[].class) { + return "bytes"; + } else if (clazz == String.class) { + return "string"; + } else if (clazz == java.sql.Timestamp.class) { + return "fixed64"; + } else { + throw new RuntimeException("Type " + clazz + " not supported on protobuf!"); + } } - } default: - throw new RuntimeException("Type " + clazz - + " not supported on protobuf!"); + throw new RuntimeException("Type " + clazz + " not supported on protobuf!"); } } }
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectDB2.java b/src/main/java/com/google/gwtorm/schema/sql/DialectDB2.java index b45da82..5b26cd6 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectDB2.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectDB2.java
@@ -18,7 +18,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -41,8 +40,7 @@ } @Override - public OrmException convertError(String op, String entity, - SQLException err) { + public OrmException convertError(String op, String entity, SQLException err) { switch (getSQLStateInt(err)) { case 23505: // DUPLICATE_KEY_1 return new OrmDuplicateKeyException(entity, err); @@ -62,9 +60,8 @@ Statement s = db.createStatement(); try { ResultSet rs = - s.executeQuery("SELECT SEQNAME" - + " FROM SYSCAT.SEQUENCES" - + " WHERE SEQSCHEMA = CURRENT_SCHEMA"); + s.executeQuery( + "SELECT SEQNAME" + " FROM SYSCAT.SEQUENCES" + " WHERE SEQSCHEMA = CURRENT_SCHEMA"); try { HashSet<String> sequences = new HashSet<>(); while (rs.next()) { @@ -83,9 +80,9 @@ public Set<String> listTables(Connection db) throws SQLException { Statement s = db.createStatement(); try { - ResultSet rs = s.executeQuery("SELECT TABNAME" - + " FROM SYSCAT.TABLES" - + " WHERE TABSCHEMA = CURRENT_SCHEMA"); + ResultSet rs = + s.executeQuery( + "SELECT TABNAME" + " FROM SYSCAT.TABLES" + " WHERE TABSCHEMA = CURRENT_SCHEMA"); try { Set<String> tables = new HashSet<>(); while (rs.next()) { @@ -101,10 +98,11 @@ } @Override - public Set<String> listIndexes(final Connection db, String tableName) - throws SQLException { - PreparedStatement s = db.prepareStatement("SELECT distinct INDNAME" - + " FROM syscat.indexes WHERE TABNAME = ? AND TABSCHEMA = CURRENT_SCHEMA"); + public Set<String> listIndexes(final Connection db, String tableName) throws SQLException { + PreparedStatement s = + db.prepareStatement( + "SELECT distinct INDNAME" + + " FROM syscat.indexes WHERE TABNAME = ? AND TABSCHEMA = CURRENT_SCHEMA"); try { s.setString(1, tableName.toUpperCase()); ResultSet rs = s.executeQuery(); @@ -123,8 +121,7 @@ } @Override - public void renameTable(StatementExecutor e, String from, String to) - throws OrmException { + public void renameTable(StatementExecutor e, String from, String to) throws OrmException { StringBuilder r = new StringBuilder(); r.append("RENAME TABLE "); r.append(from); @@ -134,8 +131,9 @@ } @Override - public void renameColumn(StatementExecutor stmt, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor stmt, String tableName, String fromColumn, ColumnModel col) + throws OrmException { StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(tableName);
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectDerby.java b/src/main/java/com/google/gwtorm/schema/sql/DialectDerby.java index 690ed94..e8cd2ce 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectDerby.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectDerby.java
@@ -18,7 +18,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -70,8 +69,9 @@ } @Override - public void renameColumn(StatementExecutor e, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor e, String tableName, String fromColumn, ColumnModel col) + throws OrmException { StringBuffer sb = new StringBuffer(); sb.append("RENAME COLUMN "); sb.append(tableName); @@ -83,8 +83,7 @@ } @Override - public void renameTable(StatementExecutor e, String from, String to) - throws OrmException { + public void renameTable(StatementExecutor e, String from, String to) throws OrmException { final StringBuilder r = new StringBuilder(); r.append("RENAME TABLE "); r.append(from);
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectH2.java b/src/main/java/com/google/gwtorm/schema/sql/DialectH2.java index c676715..4af606c 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectH2.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectH2.java
@@ -18,7 +18,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -34,8 +33,7 @@ } @Override - public OrmException convertError(final String op, final String entity, - final SQLException err) { + public OrmException convertError(final String op, final String entity, final SQLException err) { switch (getSQLStateInt(err)) { case 23001: // UNIQUE CONSTRAINT VIOLATION case 23505: // DUPLICATE_KEY_1 @@ -56,9 +54,10 @@ Statement s = db.createStatement(); try { ResultSet rs = - s.executeQuery("SELECT SEQUENCE_NAME" - + " FROM INFORMATION_SCHEMA.SEQUENCES" - + " WHERE SEQUENCE_SCHEMA = 'PUBLIC'"); + s.executeQuery( + "SELECT SEQUENCE_NAME" + + " FROM INFORMATION_SCHEMA.SEQUENCES" + + " WHERE SEQUENCE_SCHEMA = 'PUBLIC'"); try { HashSet<String> sequences = new HashSet<>(); while (rs.next()) { @@ -74,8 +73,8 @@ } @Override - public void addColumn(StatementExecutor stmt, String tableName, - ColumnModel col) throws OrmException { + public void addColumn(StatementExecutor stmt, String tableName, ColumnModel col) + throws OrmException { final StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(tableName); @@ -99,8 +98,9 @@ } @Override - public void renameColumn(StatementExecutor stmt, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor stmt, String tableName, String fromColumn, ColumnModel col) + throws OrmException { final StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(tableName);
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectHANA.java b/src/main/java/com/google/gwtorm/schema/sql/DialectHANA.java index c67fca7..db2fbf7 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectHANA.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectHANA.java
@@ -19,7 +19,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -33,40 +32,44 @@ public class DialectHANA extends SqlDialect { public DialectHANA() { - types.put(String.class, new SqlStringTypeInfo() { - @Override - public String getSqlType(ColumnModel col, SqlDialect dialect) { - Column column = col.getColumnAnnotation(); - StringBuilder r = new StringBuilder(); + types.put( + String.class, + new SqlStringTypeInfo() { + @Override + public String getSqlType(ColumnModel col, SqlDialect dialect) { + Column column = col.getColumnAnnotation(); + StringBuilder r = new StringBuilder(); - if (column.length() <= 0) { - r.append("NVARCHAR(255)"); - if (col.isNotNull()) { - r.append(" DEFAULT ''"); + if (column.length() <= 0) { + r.append("NVARCHAR(255)"); + if (col.isNotNull()) { + r.append(" DEFAULT ''"); + } + } else if (column.length() <= 5000) { + r.append("NVARCHAR(" + column.length() + ")"); + if (col.isNotNull()) { + r.append(" DEFAULT ''"); + } + } else { + r.append("NCLOB"); + } + + if (col.isNotNull()) { + r.append(" NOT NULL"); + } + + return r.toString(); } - } else if (column.length() <= 5000) { - r.append("NVARCHAR(" + column.length() + ")"); - if (col.isNotNull()) { - r.append(" DEFAULT ''"); + }); + types.put( + Boolean.TYPE, + new SqlBooleanTypeInfo() { + @Override + public String getCheckConstraint(ColumnModel column, SqlDialect dialect) { + // check constraints are not supported by HANA + return null; } - } else { - r.append("NCLOB"); - } - - if (col.isNotNull()) { - r.append(" NOT NULL"); - } - - return r.toString(); - } - }); - types.put(Boolean.TYPE, new SqlBooleanTypeInfo() { - @Override - public String getCheckConstraint(ColumnModel column, SqlDialect dialect) { - // check constraints are not supported by HANA - return null; - } - }); + }); typeNames.put(Types.INTEGER, "INTEGER"); } @@ -85,8 +88,7 @@ } @Override - public void dropColumn(StatementExecutor e, String tableName, String column) - throws OrmException { + public void dropColumn(StatementExecutor e, String tableName, String column) throws OrmException { StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(tableName); @@ -112,14 +114,12 @@ } @Override - public Set<String> listIndexes(Connection db, String tableName) - throws SQLException { + public Set<String> listIndexes(Connection db, String tableName) throws SQLException { return listNamesFromSystemTable(db, "INDEX_NAME", "INDEXES"); } @Override - public Set<String> listColumns(Connection db, String tableName) - throws SQLException { + public Set<String> listColumns(Connection db, String tableName) throws SQLException { String sql = "SELECT COLUMN_NAME FROM TABLE_COLUMNS" + " WHERE SCHEMA_NAME = CURRENT_SCHEMA AND TABLE_NAME = ?"; @@ -144,8 +144,8 @@ return names; } - private static Set<String> listNamesFromSystemTable(Connection db, - String columnName, String tableName) throws SQLException { + private static Set<String> listNamesFromSystemTable( + Connection db, String columnName, String tableName) throws SQLException { StringBuilder r = new StringBuilder(); r.append("SELECT "); r.append(columnName); @@ -159,8 +159,7 @@ } @Override - public void renameTable(StatementExecutor e, String from, String to) - throws OrmException { + public void renameTable(StatementExecutor e, String from, String to) throws OrmException { StringBuilder r = new StringBuilder(); r.append("RENAME TABLE "); r.append(from); @@ -188,8 +187,9 @@ } @Override - public void renameColumn(StatementExecutor e, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor e, String tableName, String fromColumn, ColumnModel col) + throws OrmException { StringBuilder s = new StringBuilder(); s.append("RENAME COLUMN "); s.append(tableName).append(".").append(fromColumn);
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectMaxDB.java b/src/main/java/com/google/gwtorm/schema/sql/DialectMaxDB.java index df3ac31..1234a48 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectMaxDB.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectMaxDB.java
@@ -18,7 +18,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -56,8 +55,7 @@ final Statement s = conn.createStatement(); try { // lists sequences from schema associated with the current connection only - final ResultSet rs = - s.executeQuery("SELECT sequence_name FROM sequences"); + final ResultSet rs = s.executeQuery("SELECT sequence_name FROM sequences"); try { HashSet<String> sequences = new HashSet<>(); while (rs.next()) { @@ -73,8 +71,9 @@ } @Override - public void renameColumn(StatementExecutor e, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor e, String tableName, String fromColumn, ColumnModel col) + throws OrmException { final StringBuilder s = new StringBuilder(); s.append("RENAME COLUMN "); s.append(tableName).append(".").append(fromColumn); @@ -106,8 +105,7 @@ } @Override - public void renameTable(StatementExecutor e, String from, String to) - throws OrmException { + public void renameTable(StatementExecutor e, String from, String to) throws OrmException { final StringBuilder r = new StringBuilder(); r.append("RENAME TABLE "); r.append(from); @@ -115,5 +113,4 @@ r.append(to); e.execute(r.toString()); } - }
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectMySQL.java b/src/main/java/com/google/gwtorm/schema/sql/DialectMySQL.java index 521a88f..a233dce 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectMySQL.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectMySQL.java
@@ -20,7 +20,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -34,46 +33,50 @@ /** Dialect for <a href="http://www.mysql.com/">MySQL</a> */ public class DialectMySQL extends SqlDialect { public DialectMySQL() { - types.put(String.class, new SqlStringTypeInfo() { - @Override - public String getSqlType(final ColumnModel col, final SqlDialect dialect) { - final Column column = col.getColumnAnnotation(); - final StringBuilder r = new StringBuilder(); + types.put( + String.class, + new SqlStringTypeInfo() { + @Override + public String getSqlType(final ColumnModel col, final SqlDialect dialect) { + final Column column = col.getColumnAnnotation(); + final StringBuilder r = new StringBuilder(); - if (column.length() <= 0) { - r.append("VARCHAR(255) BINARY"); - if (col.isNotNull()) { - r.append(" DEFAULT ''"); + if (column.length() <= 0) { + r.append("VARCHAR(255) BINARY"); + if (col.isNotNull()) { + r.append(" DEFAULT ''"); + } + } else if (column.length() <= 255) { + r.append("VARCHAR(" + column.length() + ") BINARY"); + if (col.isNotNull()) { + r.append(" DEFAULT ''"); + } + } else { + r.append(dialect.getSqlTypeName(Types.LONGVARCHAR)); + } + + if (col.isNotNull()) { + r.append(" NOT NULL"); + } + + return r.toString(); } - } else if (column.length() <= 255) { - r.append("VARCHAR(" + column.length() + ") BINARY"); - if (col.isNotNull()) { - r.append(" DEFAULT ''"); + }); + types.put( + Timestamp.class, + new SqlTimestampTypeInfo() { + @Override + public String getSqlType(ColumnModel col, SqlDialect dialect) { + final StringBuilder r = new StringBuilder(); + r.append(dialect.getSqlTypeName(getSqlTypeConstant())); + if (col.isNotNull()) { + r.append(" NOT NULL"); + } else { + r.append(" NULL DEFAULT NULL"); + } + return r.toString(); } - } else { - r.append(dialect.getSqlTypeName(Types.LONGVARCHAR)); - } - - if (col.isNotNull()) { - r.append(" NOT NULL"); - } - - return r.toString(); - } - }); - types.put(Timestamp.class, new SqlTimestampTypeInfo() { - @Override - public String getSqlType(ColumnModel col, SqlDialect dialect) { - final StringBuilder r = new StringBuilder(); - r.append(dialect.getSqlTypeName(getSqlTypeConstant())); - if (col.isNotNull()) { - r.append(" NOT NULL"); - } else { - r.append(" NULL DEFAULT NULL"); - } - return r.toString(); - } - }); + }); } @Override @@ -106,13 +109,11 @@ } @Override - public long nextLong(final Connection conn, final String seqname) - throws OrmException { + public long nextLong(final Connection conn, final String seqname) throws OrmException { try { final Statement st = conn.createStatement(); try { - st.execute("INSERT INTO " + seqname + "(s)VALUES(NULL)", - Statement.RETURN_GENERATED_KEYS); + st.execute("INSERT INTO " + seqname + "(s)VALUES(NULL)", Statement.RETURN_GENERATED_KEYS); final long r; final ResultSet rs = st.getGeneratedKeys(); try { @@ -168,8 +169,7 @@ } } - private boolean isSequence(Connection db, String tableName) - throws SQLException { + private boolean isSequence(Connection db, String tableName) throws SQLException { final DatabaseMetaData meta = db.getMetaData(); if (meta.storesUpperCaseIdentifiers()) { tableName = tableName.toUpperCase(); @@ -195,8 +195,7 @@ } @Override - public void renameTable(StatementExecutor e, String from, - String to) throws OrmException { + public void renameTable(StatementExecutor e, String from, String to) throws OrmException { final StringBuilder r = new StringBuilder(); r.append("RENAME TABLE "); r.append(from); @@ -207,8 +206,9 @@ } @Override - public void renameColumn(StatementExecutor stmt, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor stmt, String tableName, String fromColumn, ColumnModel col) + throws OrmException { StringBuffer r = new StringBuffer(); r.append("ALTER TABLE "); r.append(tableName);
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectOracle.java b/src/main/java/com/google/gwtorm/schema/sql/DialectOracle.java index b96081a..bb44604 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectOracle.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectOracle.java
@@ -18,7 +18,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -44,6 +43,7 @@ public boolean canDetermineIndividualBatchUpdateCounts() { return false; } + @Override public boolean canDetermineTotalBatchUpdateCount() { return false; @@ -69,10 +69,10 @@ } @Override - public Set<String> listIndexes(final Connection db, String tableName) - throws SQLException { - PreparedStatement s = db.prepareStatement("SELECT distinct index_name" - + " FROM user_indexes WHERE table_name = ?"); + public Set<String> listIndexes(final Connection db, String tableName) throws SQLException { + PreparedStatement s = + db.prepareStatement( + "SELECT distinct index_name" + " FROM user_indexes WHERE table_name = ?"); try { s.setString(1, tableName.toUpperCase()); ResultSet rs = s.executeQuery(); @@ -110,8 +110,8 @@ } @Override - public void addColumn(StatementExecutor stmt, String tableName, - ColumnModel col) throws OrmException { + public void addColumn(StatementExecutor stmt, String tableName, ColumnModel col) + throws OrmException { final StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(tableName); @@ -123,8 +123,9 @@ } @Override - public void renameColumn(StatementExecutor e, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor e, String tableName, String fromColumn, ColumnModel col) + throws OrmException { StringBuffer sb = new StringBuffer(); sb.append("ALTER TABLE "); sb.append(tableName);
diff --git a/src/main/java/com/google/gwtorm/schema/sql/DialectPostgreSQL.java b/src/main/java/com/google/gwtorm/schema/sql/DialectPostgreSQL.java index fb8a75e..b04ba19 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/DialectPostgreSQL.java +++ b/src/main/java/com/google/gwtorm/schema/sql/DialectPostgreSQL.java
@@ -19,7 +19,6 @@ import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -51,8 +50,7 @@ } @Override - public OrmException convertError(final String op, final String entity, - final SQLException err) { + public OrmException convertError(final String op, final String entity, final SQLException err) { switch (getSQLStateInt(err)) { case 23505: // UNIQUE CONSTRAINT VIOLATION return new OrmDuplicateKeyException(entity, err); @@ -72,14 +70,15 @@ } @Override - public void appendCreateTableStorage(final StringBuilder sqlBuffer, - final RelationModel relationModel) { + public void appendCreateTableStorage( + final StringBuilder sqlBuffer, final RelationModel relationModel) { sqlBuffer.append("WITH (OIDS = FALSE)"); } @Override - public void renameColumn(StatementExecutor stmt, String tableName, - String fromColumn, ColumnModel col) throws OrmException { + public void renameColumn( + StatementExecutor stmt, String tableName, String fromColumn, ColumnModel col) + throws OrmException { final StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(tableName); @@ -94,8 +93,7 @@ public Set<String> listSequences(Connection db) throws SQLException { Statement s = db.createStatement(); try { - ResultSet rs = - s.executeQuery("SELECT relname FROM pg_class WHERE relkind = 'S'"); + ResultSet rs = s.executeQuery("SELECT relname FROM pg_class WHERE relkind = 'S'"); try { HashSet<String> sequences = new HashSet<>(); while (rs.next()) { @@ -112,8 +110,8 @@ private static class Pre82 extends DialectPostgreSQL { @Override - public void appendCreateTableStorage(final StringBuilder sqlBuffer, - final RelationModel relationModel) { + public void appendCreateTableStorage( + final StringBuilder sqlBuffer, final RelationModel relationModel) { sqlBuffer.append("WITHOUT OIDS"); } }
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlBooleanTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlBooleanTypeInfo.java index cf6e54f..437a2b9 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlBooleanTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlBooleanTypeInfo.java
@@ -16,13 +16,11 @@ import com.google.gwtorm.schema.ColumnModel; import com.google.gwtorm.server.CodeGenSupport; - +import java.sql.Types; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import java.sql.Types; - public class SqlBooleanTypeInfo extends SqlTypeInfo { @Override public String getSqlType(final ColumnModel column, final SqlDialect dialect) { @@ -37,8 +35,7 @@ } @Override - public String getCheckConstraint(final ColumnModel column, - final SqlDialect dialect) { + public String getCheckConstraint(final ColumnModel column, final SqlDialect dialect) { final String name = column.getColumnName(); final String t = getTrueLiteralValue(); final String f = getFalseLiteralValue(); @@ -95,9 +92,11 @@ cgs.pushSqlHandle(); cgs.pushColumnIndex(); cgs.invokeResultSetGet(getJavaSqlTypeAlias()); - cgs.mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type - .getInternalName(String.class), "equals", Type.getMethodDescriptor( - Type.BOOLEAN_TYPE, new Type[] {Type.getType(Object.class)})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + Type.getInternalName(String.class), + "equals", + Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] {Type.getType(Object.class)})); cgs.fieldSetEnd(); } }
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlByteArrayTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlByteArrayTypeInfo.java index eb0f840..b99094e 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlByteArrayTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlByteArrayTypeInfo.java
@@ -16,10 +16,6 @@ import com.google.gwtorm.schema.ColumnModel; import com.google.gwtorm.server.CodeGenSupport; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -28,6 +24,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; public class SqlByteArrayTypeInfo extends SqlTypeInfo { @Override @@ -56,11 +54,15 @@ cgs.pushSqlHandle(); cgs.pushColumnIndex(); cgs.pushFieldValue(); - cgs.mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type - .getInternalName(SqlByteArrayTypeInfo.class), "toPreparedStatement", - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { - Type.getType(PreparedStatement.class), Type.INT_TYPE, - Type.getType(byte[].class)})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(SqlByteArrayTypeInfo.class), + "toPreparedStatement", + Type.getMethodDescriptor( + Type.VOID_TYPE, + new Type[] { + Type.getType(PreparedStatement.class), Type.INT_TYPE, Type.getType(byte[].class) + })); } @Override @@ -68,15 +70,16 @@ cgs.fieldSetBegin(); cgs.pushSqlHandle(); cgs.pushColumnIndex(); - cgs.mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type - .getInternalName(SqlByteArrayTypeInfo.class), "fromResultSet", Type - .getMethodDescriptor(Type.getType(byte[].class), new Type[] { - Type.getType(ResultSet.class), Type.INT_TYPE})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(SqlByteArrayTypeInfo.class), + "fromResultSet", + Type.getMethodDescriptor( + Type.getType(byte[].class), new Type[] {Type.getType(ResultSet.class), Type.INT_TYPE})); cgs.fieldSetEnd(); } - public static byte[] fromResultSet(final ResultSet rs, final int col) - throws SQLException { + public static byte[] fromResultSet(final ResultSet rs, final int col) throws SQLException { final InputStream r = rs.getBinaryStream(col); if (r == null) { return null; @@ -98,8 +101,8 @@ } } - public static void toPreparedStatement(final PreparedStatement ps, - final int col, final byte[] raw) throws SQLException { + public static void toPreparedStatement( + final PreparedStatement ps, final int col, final byte[] raw) throws SQLException { if (raw != null) { ps.setBinaryStream(col, new ByteArrayInputStream(raw), raw.length); } else {
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlCharTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlCharTypeInfo.java index 510993a..b82b7dd 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlCharTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlCharTypeInfo.java
@@ -16,12 +16,10 @@ import com.google.gwtorm.schema.ColumnModel; import com.google.gwtorm.server.CodeGenSupport; - +import java.sql.Types; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import java.sql.Types; - public class SqlCharTypeInfo extends SqlTypeInfo { @Override public String getSqlType(final ColumnModel column, final SqlDialect dialect) { @@ -49,10 +47,11 @@ cgs.pushSqlHandle(); cgs.pushColumnIndex(); cgs.pushFieldValue(); - cgs.mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type - .getInternalName(Character.class), "toString", Type - .getMethodDescriptor(Type.getType(String.class), - new Type[] {Type.CHAR_TYPE})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(Character.class), + "toString", + Type.getMethodDescriptor(Type.getType(String.class), new Type[] {Type.CHAR_TYPE})); cgs.invokePreparedStatementSet(getJavaSqlTypeAlias()); } @@ -63,9 +62,11 @@ cgs.pushColumnIndex(); cgs.invokeResultSetGet(getJavaSqlTypeAlias()); cgs.push(0); - cgs.mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type - .getInternalName(String.class), "charAt", Type.getMethodDescriptor( - Type.CHAR_TYPE, new Type[] {Type.INT_TYPE})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + Type.getInternalName(String.class), + "charAt", + Type.getMethodDescriptor(Type.CHAR_TYPE, new Type[] {Type.INT_TYPE})); cgs.fieldSetEnd(); } }
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlDateTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlDateTypeInfo.java index 127befe..52c7bdc 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlDateTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlDateTypeInfo.java
@@ -15,7 +15,6 @@ package com.google.gwtorm.schema.sql; import com.google.gwtorm.schema.ColumnModel; - import java.sql.Types; public class SqlDateTypeInfo extends SqlTypeInfo {
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlDialect.java b/src/main/java/com/google/gwtorm/schema/sql/SqlDialect.java index 17c1e88..be46505 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlDialect.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlDialect.java
@@ -20,7 +20,6 @@ import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.Sequence; import com.google.gwtorm.server.StatementExecutor; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; @@ -36,8 +35,7 @@ import java.util.concurrent.CopyOnWriteArrayList; public abstract class SqlDialect { - private static final List<SqlDialect> DIALECTS = - new CopyOnWriteArrayList<>(); + private static final List<SqlDialect> DIALECTS = new CopyOnWriteArrayList<>(); static { DIALECTS.add(new DialectDB2()); @@ -55,8 +53,7 @@ DIALECTS.add(0, dialect); } - public static SqlDialect getDialectFor(Connection c) - throws SQLException, OrmException { + public static SqlDialect getDialectFor(Connection c) throws SQLException, OrmException { String url = c.getMetaData().getURL(); for (SqlDialect d : DIALECTS) { if (d.handles(url, c)) { @@ -93,13 +90,14 @@ public abstract boolean handles(String url, Connection c) throws SQLException; - /** Select a better dialect definition for this connection. + /** + * Select a better dialect definition for this connection. * * @param c the connection * @return a dialect instance * @throws SQLException */ - public SqlDialect refine(final Connection c) throws SQLException { + public SqlDialect refine(final Connection c) throws SQLException { return this; } @@ -154,16 +152,14 @@ * @param err the driver specific exception. * @return an OrmException the caller can throw. */ - public OrmException convertError(final String op, final String entity, - final SQLException err) { + public OrmException convertError(final String op, final String entity, final SQLException err) { if (err.getCause() == null && err.getNextException() != null) { err.initCause(err.getNextException()); } return new OrmException(op + " failure on " + entity, err); } - public long nextLong(final Connection conn, final String poolName) - throws OrmException { + public long nextLong(final Connection conn, final String poolName) throws OrmException { final String query = getNextSequenceValueSql(poolName); try { final Statement st = conn.createStatement(); @@ -217,13 +213,12 @@ /** * Append driver specific storage parameters to a CREATE TABLE statement. * - * @param sqlBuffer buffer holding the CREATE TABLE, just after the closing - * parenthesis after the column list. + * @param sqlBuffer buffer holding the CREATE TABLE, just after the closing parenthesis after the + * column list. * @param relationModel the model of the table being generated. */ - public void appendCreateTableStorage(final StringBuilder sqlBuffer, - final RelationModel relationModel) { - } + public void appendCreateTableStorage( + final StringBuilder sqlBuffer, final RelationModel relationModel) {} /** * List all tables in the current database schema. @@ -254,8 +249,7 @@ * @param to destination table name * @throws OrmException the table could not be renamed. */ - public void renameTable(StatementExecutor e, String from, - String to) throws OrmException { + public void renameTable(StatementExecutor e, String from, String to) throws OrmException { final StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(from); @@ -273,8 +267,7 @@ * @return set of declared indexes, in lowercase. * @throws SQLException the indexes cannot be listed. */ - public Set<String> listIndexes(final Connection db, String tableName) - throws SQLException { + public Set<String> listIndexes(final Connection db, String tableName) throws SQLException { final DatabaseMetaData meta = db.getMetaData(); if (meta.storesUpperCaseIdentifiers()) { tableName = tableName.toUpperCase(); @@ -301,8 +294,7 @@ * @return set of declared sequences, in lowercase. * @throws SQLException the sequence objects cannot be listed. */ - public abstract Set<String> listSequences(final Connection db) - throws SQLException; + public abstract Set<String> listSequences(final Connection db) throws SQLException; /** * List all columns in the given table name. @@ -312,8 +304,7 @@ * @return set of declared columns, in lowercase. * @throws SQLException the columns cannot be listed from the relation. */ - public Set<String> listColumns(final Connection db, String tableName) - throws SQLException { + public Set<String> listColumns(final Connection db, String tableName) throws SQLException { final DatabaseMetaData meta = db.getMetaData(); if (meta.storesUpperCaseIdentifiers()) { tableName = tableName.toUpperCase(); @@ -366,8 +357,7 @@ * @param column name of the column to drop. * @throws OrmException the column could not be added. */ - public void dropColumn(StatementExecutor e, String tableName, String column) - throws OrmException { + public void dropColumn(StatementExecutor e, String tableName, String column) throws OrmException { final StringBuilder r = new StringBuilder(); r.append("ALTER TABLE "); r.append(tableName); @@ -385,8 +375,9 @@ * @param col destination column definition * @throws OrmException the column could not be renamed. */ - public abstract void renameColumn(StatementExecutor e, String tableName, - String fromColumn, ColumnModel col) throws OrmException; + public abstract void renameColumn( + StatementExecutor e, String tableName, String fromColumn, ColumnModel col) + throws OrmException; /** * Drop one index from a table. @@ -396,8 +387,7 @@ * @param name index name. * @throws OrmException the index could not be renamed. */ - public void dropIndex(StatementExecutor e, String tableName, String name) - throws OrmException { + public void dropIndex(StatementExecutor e, String tableName, String name) throws OrmException { e.execute(getDropIndexSql(tableName, name)); } @@ -408,25 +398,22 @@ protected abstract String getNextSequenceValueSql(String seqname); /** - * Does the array returned by the PreparedStatement.executeBatch method return - * the exact number of rows updated for every row in the batch? + * Does the array returned by the PreparedStatement.executeBatch method return the exact number of + * rows updated for every row in the batch? * - * @return <code>true</code> if the executeBatch method returns the number of - * rows affected for every row in the batch; <code>false</code> if it - * may return Statement.SUCESS_NO_INFO + * @return <code>true</code> if the executeBatch method returns the number of rows affected for + * every row in the batch; <code>false</code> if it may return Statement.SUCESS_NO_INFO */ public boolean canDetermineIndividualBatchUpdateCounts() { return true; - } /** - * Can the total number of rows updated by the PreparedStatement.executeBatch - * be determined exactly by the SQLDialect.executeBatch method? + * Can the total number of rows updated by the PreparedStatement.executeBatch be determined + * exactly by the SQLDialect.executeBatch method? * - * @return <code>true</code> if the SQlDialect.executeBatch method can exactly - * determine the total number of rows updated by a batch; - * <code>false</code> otherwise + * @return <code>true</code> if the SQlDialect.executeBatch method can exactly determine the total + * number of rows updated by a batch; <code>false</code> otherwise * @see #executeBatch(PreparedStatement) */ public boolean canDetermineTotalBatchUpdateCount() { @@ -434,11 +421,11 @@ } /** - * Executes a prepared statement batch and returns the total number of rows - * successfully updated or inserted. This method is intended to be overridden. + * Executes a prepared statement batch and returns the total number of rows successfully updated + * or inserted. This method is intended to be overridden. * - * If the canDetermineTotalBatchUpdateCount returns false for a particular - * SQLDialect, this method should throw an UnsupportedOperationException. + * <p>If the canDetermineTotalBatchUpdateCount returns false for a particular SQLDialect, this + * method should throw an UnsupportedOperationException. * * @param ps the prepared statement with the batch to be executed * @return the total number of rows affected @@ -462,8 +449,7 @@ /** * Some databases don't support delimiters (semicolons) in scripts. * - * @return <code>true</code> statement delimiter is accepted, - * <code>false</code> otherwise + * @return <code>true</code> statement delimiter is accepted, <code>false</code> otherwise */ public boolean isStatementDelimiterSupported() { return true; @@ -471,6 +457,7 @@ /** * Get the SQL LIMIT command segment in the given dialect + * * @param limit the limit to apply to the result set (either a number or ?) * @return the SQL LIMIT command segment in the given dialect */ @@ -479,9 +466,8 @@ } /** - * Get the driver specific 'table type' to be used in a CREATE TABLE - * statement. When creating a CREATE TABLE statement the 'table type' is - * appended after a blank following the CREATE keyword. + * Get the driver specific 'table type' to be used in a CREATE TABLE statement. When creating a + * CREATE TABLE statement the 'table type' is appended after a blank following the CREATE keyword. */ public String getTableTypeSql() { return "TABLE";
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlIntTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlIntTypeInfo.java index 23c89da..eace44d 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlIntTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlIntTypeInfo.java
@@ -15,7 +15,6 @@ package com.google.gwtorm.schema.sql; import com.google.gwtorm.schema.ColumnModel; - import java.sql.Types; public class SqlIntTypeInfo extends SqlTypeInfo {
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlLongTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlLongTypeInfo.java index 940c7fc..0b25b52 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlLongTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlLongTypeInfo.java
@@ -15,7 +15,6 @@ package com.google.gwtorm.schema.sql; import com.google.gwtorm.schema.ColumnModel; - import java.sql.Types; public class SqlLongTypeInfo extends SqlTypeInfo {
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlShortTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlShortTypeInfo.java index c2f895e..6894a47 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlShortTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlShortTypeInfo.java
@@ -15,7 +15,6 @@ package com.google.gwtorm.schema.sql; import com.google.gwtorm.schema.ColumnModel; - import java.sql.Types; public class SqlShortTypeInfo extends SqlTypeInfo {
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlStringTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlStringTypeInfo.java index 2c32f1e..d6cbda0 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlStringTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlStringTypeInfo.java
@@ -17,10 +17,6 @@ import com.google.gwtorm.client.Column; import com.google.gwtorm.schema.ColumnModel; import com.google.gwtorm.server.CodeGenSupport; - -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - import java.io.IOException; import java.io.Reader; import java.io.StringReader; @@ -29,6 +25,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; public class SqlStringTypeInfo extends SqlTypeInfo { @Override @@ -70,11 +68,15 @@ cgs.pushSqlHandle(); cgs.pushColumnIndex(); cgs.pushFieldValue(); - cgs.mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type - .getInternalName(SqlStringTypeInfo.class), "toPreparedStatement", - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { - Type.getType(PreparedStatement.class), Type.INT_TYPE, - Type.getType(String.class)})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(SqlStringTypeInfo.class), + "toPreparedStatement", + Type.getMethodDescriptor( + Type.VOID_TYPE, + new Type[] { + Type.getType(PreparedStatement.class), Type.INT_TYPE, Type.getType(String.class) + })); } } @@ -86,16 +88,18 @@ cgs.fieldSetBegin(); cgs.pushSqlHandle(); cgs.pushColumnIndex(); - cgs.mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type - .getInternalName(SqlStringTypeInfo.class), "fromResultSet", Type - .getMethodDescriptor(Type.getType(String.class), new Type[] { - Type.getType(ResultSet.class), Type.INT_TYPE})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(SqlStringTypeInfo.class), + "fromResultSet", + Type.getMethodDescriptor( + Type.getType(String.class), + new Type[] {Type.getType(ResultSet.class), Type.INT_TYPE})); cgs.fieldSetEnd(); } } - public static String fromResultSet(final ResultSet rs, final int col) - throws SQLException { + public static String fromResultSet(final ResultSet rs, final int col) throws SQLException { final Reader r = rs.getCharacterStream(col); if (r == null) { return null; @@ -117,8 +121,8 @@ } } - public static void toPreparedStatement(final PreparedStatement ps, - final int col, final String txt) throws SQLException { + public static void toPreparedStatement( + final PreparedStatement ps, final int col, final String txt) throws SQLException { if (txt != null) { ps.setCharacterStream(col, new StringReader(txt), txt.length()); } else {
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlTimestampTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlTimestampTypeInfo.java index ef60d29..1fb4bb0 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlTimestampTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlTimestampTypeInfo.java
@@ -15,7 +15,6 @@ package com.google.gwtorm.schema.sql; import com.google.gwtorm.schema.ColumnModel; - import java.sql.Types; public class SqlTimestampTypeInfo extends SqlTypeInfo {
diff --git a/src/main/java/com/google/gwtorm/schema/sql/SqlTypeInfo.java b/src/main/java/com/google/gwtorm/schema/sql/SqlTypeInfo.java index f238541..5832c18 100644 --- a/src/main/java/com/google/gwtorm/schema/sql/SqlTypeInfo.java +++ b/src/main/java/com/google/gwtorm/schema/sql/SqlTypeInfo.java
@@ -16,21 +16,16 @@ import com.google.gwtorm.schema.ColumnModel; import com.google.gwtorm.server.CodeGenSupport; - +import java.sql.PreparedStatement; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import java.sql.PreparedStatement; - - public abstract class SqlTypeInfo { - protected SqlTypeInfo() { - } + protected SqlTypeInfo() {} public abstract String getSqlType(ColumnModel column, SqlDialect dialect); - public String getCheckConstraint(final ColumnModel column, - final SqlDialect dialect) { + public String getCheckConstraint(final ColumnModel column, final SqlDialect dialect) { return null; } @@ -49,10 +44,11 @@ cgs.pushSqlHandle(); cgs.pushColumnIndex(); cgs.push(getSqlTypeConstant()); - cgs.mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type - .getInternalName(PreparedStatement.class), "setNull", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE, - Type.INT_TYPE})); + cgs.mv.visitMethodInsn( + Opcodes.INVOKEINTERFACE, + Type.getInternalName(PreparedStatement.class), + "setNull", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type.INT_TYPE, Type.INT_TYPE})); } public void generateResultSetGet(final CodeGenSupport cgs) {
diff --git a/src/main/java/com/google/gwtorm/server/AbstractAccess.java b/src/main/java/com/google/gwtorm/server/AbstractAccess.java index a814ec8..21988f2 100644 --- a/src/main/java/com/google/gwtorm/server/AbstractAccess.java +++ b/src/main/java/com/google/gwtorm/server/AbstractAccess.java
@@ -17,14 +17,12 @@ import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import com.google.gwtorm.client.Key; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; -public abstract class AbstractAccess<E, K extends Key<?>> - implements Access<E, K> { +public abstract class AbstractAccess<E, K extends Key<?>> implements Access<E, K> { private static final int MAX_TRIES = 10; @Override @@ -69,9 +67,8 @@ } @Override - public E atomicUpdate(final K key, final AtomicUpdate<E> update) - throws OrmException { - for (int attempts = 1;; attempts++) { + public E atomicUpdate(final K key, final AtomicUpdate<E> update) throws OrmException { + for (int attempts = 1; ; attempts++) { try { final E obj = get(key); if (obj == null) {
diff --git a/src/main/java/com/google/gwtorm/server/AbstractResultSet.java b/src/main/java/com/google/gwtorm/server/AbstractResultSet.java index f3cf5ce..a6e5c74 100644 --- a/src/main/java/com/google/gwtorm/server/AbstractResultSet.java +++ b/src/main/java/com/google/gwtorm/server/AbstractResultSet.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - import java.util.ArrayList; import java.util.Iterator; import java.util.List;
diff --git a/src/main/java/com/google/gwtorm/server/AbstractSchema.java b/src/main/java/com/google/gwtorm/server/AbstractSchema.java index 87ced82..83ce259 100644 --- a/src/main/java/com/google/gwtorm/server/AbstractSchema.java +++ b/src/main/java/com/google/gwtorm/server/AbstractSchema.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - /** Base implementation any generated schema must implement. */ public abstract class AbstractSchema implements Schema { @Override @@ -29,16 +28,15 @@ /** * Obtain the next unique value from a pool of available numbers. - * <p> - * Frequently the next number will be just an increment of a global counter, - * but may be spread across multiple counter ranges to increase concurrency. * - * @param poolName unique name of the counter within the schema. The - * underlying storage system should use this to identify the counter - * pool to obtain the next value from. + * <p>Frequently the next number will be just an increment of a global counter, but may be spread + * across multiple counter ranges to increase concurrency. + * + * @param poolName unique name of the counter within the schema. The underlying storage system + * should use this to identify the counter pool to obtain the next value from. * @return a new unique value. - * @throws OrmException a value cannot be reserved for the caller, or the pool - * has been exhausted and no new values are available. + * @throws OrmException a value cannot be reserved for the caller, or the pool has been exhausted + * and no new values are available. */ protected abstract long nextLong(String poolName) throws OrmException; }
diff --git a/src/main/java/com/google/gwtorm/server/Access.java b/src/main/java/com/google/gwtorm/server/Access.java index 019249b..0126054 100644 --- a/src/main/java/com/google/gwtorm/server/Access.java +++ b/src/main/java/com/google/gwtorm/server/Access.java
@@ -17,38 +17,34 @@ import com.google.common.util.concurrent.CheckedFuture; import com.google.gwtorm.client.Column; import com.google.gwtorm.client.Key; - import java.util.Map; /** * Data access interface for an entity type. - * <p> - * Applications should extend this interface for each entity type they need to - * access. At runtime the application extension will be automatically - * implemented with a generated class, providing concrete implementations for - * all methods. - * <p> - * Instances should be acquired through the application's extension interface of - * {@link Schema}. - * <p> - * Applications should implement a query method using the {@link PrimaryKey} - * annotation, for example: + * + * <p>Applications should extend this interface for each entity type they need to access. At runtime + * the application extension will be automatically implemented with a generated class, providing + * concrete implementations for all methods. + * + * <p>Instances should be acquired through the application's extension interface of {@link Schema}. + * + * <p>Applications should implement a query method using the {@link PrimaryKey} annotation, for + * example: * * <pre> * public interface FooAccess extends Access<Foo, Foo.Key> { * @PrimaryKey("key") * Foo byKey(Foo.Key k) throws OrmException; * } - *</pre> - *<p> - * otherwise the primaryKey, get, update and delete operations declared by this - * interface will be unsupported. + * </pre> * - * @param <T> type of the entity. Any object type is suitable, so long as at - * least one field uses a {@link Column} annotation. - * @param <K> type of the primary key of entity. If the primary key is a - * primitive type then use Key directly, otherwise use a Key - * implementation. Entity specific key subclasses are recommended. + * <p>otherwise the primaryKey, get, update and delete operations declared by this interface will be + * unsupported. + * + * @param <T> type of the entity. Any object type is suitable, so long as at least one field uses a + * {@link Column} annotation. + * @param <K> type of the primary key of entity. If the primary key is a primitive type then use Key + * directly, otherwise use a Key implementation. Entity specific key subclasses are recommended. */ public interface Access<T extends Object, K extends Key<?>> { /** @return the name of this relation. */ @@ -68,8 +64,8 @@ * Obtain the primary key of an entity instance. * * @param entity the entity to get the key of; must not be null. - * @return the primary key. Null if this entity has no primary key declared, - * or if the primary key does not implement the Key interface. + * @return the primary key. Null if this entity has no primary key declared, or if the primary key + * does not implement the Key interface. */ K primaryKey(T entity); @@ -83,10 +79,10 @@ /** * Lookup a single entity via its primary key. - * <p> - * This method is only implemented if the entity's primary key is defined to - * be an implementation of the {@link Key} interface. Otherwise the method - * throws {@link UnsupportedOperationException}. + * + * <p>This method is only implemented if the entity's primary key is defined to be an + * implementation of the {@link Key} interface. Otherwise the method throws {@link + * UnsupportedOperationException}. * * @param key the primary key instance; must not be null. * @return the entity; null if no entity has this key. @@ -97,33 +93,31 @@ /** * Lookup a single entity asynchronously via its primary key. - * <p> - * This method is only implemented if the entity's primary key is defined to - * be an implementation of the {@link Key} interface. Otherwise the method - * throws {@link UnsupportedOperationException}. + * + * <p>This method is only implemented if the entity's primary key is defined to be an + * implementation of the {@link Key} interface. Otherwise the method throws {@link + * UnsupportedOperationException}. * * @param key the primary key instance; must not be null. - * @return a {@link CheckedFuture} for the entity; the - * {@link CheckedFuture#get()} will return null if no entity has - * this key. + * @return a {@link CheckedFuture} for the entity; the {@link CheckedFuture#get()} will return + * null if no entity has this key. * @throws UnsupportedOperationException the key type doesn't implement Key. */ CheckedFuture<T, OrmException> getAsync(K key); /** * Lookup multiple entities via their primary key. - * <p> - * This method is only implemented if the entity's primary key is defined to - * be an implementation of the {@link Key} interface. Otherwise the method - * throws {@link UnsupportedOperationException}. - * <p> - * This method is a batch form of {@link #get(Key)} and may be optimized to - * reduce round-trips to the data store. + * + * <p>This method is only implemented if the entity's primary key is defined to be an + * implementation of the {@link Key} interface. Otherwise the method throws {@link + * UnsupportedOperationException}. + * + * <p>This method is a batch form of {@link #get(Key)} and may be optimized to reduce round-trips + * to the data store. * * @param keys collection of zero or more keys to perform lookup with. - * @return collection of all matching entities; this may be a smaller result - * than the keys supplied if one or more of the keys does not match an - * existing entity. + * @return collection of all matching entities; this may be a smaller result than the keys + * supplied if one or more of the keys does not match an existing entity. * @throws OrmException the data lookup failed. * @throws UnsupportedOperationException the key type doesn't implement Key. */ @@ -183,14 +177,13 @@ /** * Atomically update a single entity. - * <p> - * If the entity does not exist, the method returns {@code null} without - * invoking {@code update}. - * <p> - * If the entity exists, the method invokes {@code update} with a current copy - * of the entity. The update function should edit the passed instance - * in-place. The return value will be returned to the caller, but is otherwise - * ignored by this update function. + * + * <p>If the entity does not exist, the method returns {@code null} without invoking {@code + * update}. + * + * <p>If the entity exists, the method invokes {@code update} with a current copy of the entity. + * The update function should edit the passed instance in-place. The return value will be returned + * to the caller, but is otherwise ignored by this update function. * * @param key key which identifies the entity. * @param update the update function.
diff --git a/src/main/java/com/google/gwtorm/server/AtomicUpdate.java b/src/main/java/com/google/gwtorm/server/AtomicUpdate.java index 26bb894..75d107d 100644 --- a/src/main/java/com/google/gwtorm/server/AtomicUpdate.java +++ b/src/main/java/com/google/gwtorm/server/AtomicUpdate.java
@@ -14,20 +14,17 @@ package com.google.gwtorm.server; -/** - * Atomically updates exactly one entity. - */ +/** Atomically updates exactly one entity. */ public interface AtomicUpdate<T> { /** * Update the one object, in place. - * <p> - * This method may be called multiple times, up until the retry limit. * - * @param row a fresh copy of the object. The updater should modify it in - * place and return, the caller will attempt to rewrite it into the - * database. - * @return return value for the application code calling the atomic update; - * should be either {@code instance} or {@code null}. + * <p>This method may be called multiple times, up until the retry limit. + * + * @param row a fresh copy of the object. The updater should modify it in place and return, the + * caller will attempt to rewrite it into the database. + * @return return value for the application code calling the atomic update; should be either + * {@code instance} or {@code null}. */ T update(T row); }
diff --git a/src/main/java/com/google/gwtorm/server/CodeGenSupport.java b/src/main/java/com/google/gwtorm/server/CodeGenSupport.java index df75300..c14cdc7 100644 --- a/src/main/java/com/google/gwtorm/server/CodeGenSupport.java +++ b/src/main/java/com/google/gwtorm/server/CodeGenSupport.java
@@ -15,16 +15,14 @@ package com.google.gwtorm.server; import com.google.gwtorm.schema.ColumnModel; - -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - import java.lang.reflect.Method; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; public class CodeGenSupport implements Opcodes { public final MethodVisitor mv; @@ -128,17 +126,20 @@ final Method m; try { m = - PreparedStatement.class.getMethod("set" + sqlTypeName, Integer.TYPE, - ResultSet.class.getMethod("get" + sqlTypeName, Integer.TYPE) - .getReturnType()); + PreparedStatement.class.getMethod( + "set" + sqlTypeName, + Integer.TYPE, + ResultSet.class.getMethod("get" + sqlTypeName, Integer.TYPE).getReturnType()); } catch (SecurityException e) { throw new RuntimeException("java.sql has no " + sqlTypeName); } catch (NoSuchMethodException e) { throw new RuntimeException("java.sql has no " + sqlTypeName, e); } - mv.visitMethodInsn(INVOKEINTERFACE, Type - .getInternalName(PreparedStatement.class), m.getName(), Type - .getMethodDescriptor(m)); + mv.visitMethodInsn( + INVOKEINTERFACE, + Type.getInternalName(PreparedStatement.class), + m.getName(), + Type.getMethodDescriptor(m)); } public void invokeResultSetGet(final String sqlTypeName) { @@ -150,8 +151,11 @@ } catch (NoSuchMethodException e) { throw new RuntimeException("java.sql has no " + sqlTypeName, e); } - mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(ResultSet.class), - m.getName(), Type.getMethodDescriptor(m)); + mv.visitMethodInsn( + INVOKEINTERFACE, + Type.getInternalName(ResultSet.class), + m.getName(), + Type.getMethodDescriptor(m)); } public void fieldSetBegin() { @@ -167,8 +171,8 @@ mv.visitInsn(DUP); mv.visitVarInsn(ASTORE, dupOnSet); } - mv.visitFieldInsn(PUTFIELD, c.getInternalName(), col.getFieldName(), - toType(col).getDescriptor()); + mv.visitFieldInsn( + PUTFIELD, c.getInternalName(), col.getFieldName(), toType(col).getDescriptor()); } public void setDupOnFieldSetEnd(final int varIdx) { @@ -185,8 +189,7 @@ appendGetField(c.getParent()); } final Type t = containerClass(c); - mv.visitFieldInsn(GETFIELD, t.getInternalName(), c.getFieldName(), - toType(c).getDescriptor()); + mv.visitFieldInsn(GETFIELD, t.getInternalName(), c.getFieldName(), toType(c).getDescriptor()); } private Type containerClass(final ColumnModel c) {
diff --git a/src/main/java/com/google/gwtorm/server/GeneratedClassLoader.java b/src/main/java/com/google/gwtorm/server/GeneratedClassLoader.java index 8d9e774..567b83f 100644 --- a/src/main/java/com/google/gwtorm/server/GeneratedClassLoader.java +++ b/src/main/java/com/google/gwtorm/server/GeneratedClassLoader.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -23,12 +22,11 @@ /** * Hacked ClassLoader to inject generated code into the parent. - * <p> - * This ClassLoader allows our code generators to inject their generated classes - * into the parent ClassLoader, which should be the same ClassLoader that - * defined the application's Schema interface extension. This is necessary to - * ensure the generated classes can access protected and default-access fields - * within the entities. + * + * <p>This ClassLoader allows our code generators to inject their generated classes into the parent + * ClassLoader, which should be the same ClassLoader that defined the application's Schema interface + * extension. This is necessary to ensure the generated classes can access protected and + * default-access fields within the entities. */ public class GeneratedClassLoader extends ClassLoader { private static final boolean debugCodeGen; @@ -41,8 +39,8 @@ Method m; try { m = - ClassLoader.class.getDeclaredMethod("defineClass", String.class, - byte[].class, Integer.TYPE, Integer.TYPE); + ClassLoader.class.getDeclaredMethod( + "defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE); m.setAccessible(true); } catch (SecurityException e) { throw new LinkageError("No defineClass in ClassLoader"); @@ -56,11 +54,9 @@ super(parent); } - public void defineClass(final String name, final byte[] code) - throws OrmException { + public void defineClass(final String name, final byte[] code) throws OrmException { if (debugCodeGen) { - final File outClassFile = - new File("generated_classes/" + name.replace('.', '/') + ".class"); + final File outClassFile = new File("generated_classes/" + name.replace('.', '/') + ".class"); outClassFile.getParentFile().mkdirs(); try { final FileOutputStream out = new FileOutputStream(outClassFile); @@ -75,8 +71,7 @@ } try { - defineClass.invoke(getParent(), name, code, Integer.valueOf(0), Integer - .valueOf(code.length)); + defineClass.invoke(getParent(), name, code, Integer.valueOf(0), Integer.valueOf(code.length)); } catch (IllegalArgumentException e) { throw new OrmException("Unable to inject class " + name, e); } catch (SecurityException e) {
diff --git a/src/main/java/com/google/gwtorm/server/ListResultSet.java b/src/main/java/com/google/gwtorm/server/ListResultSet.java index 019d976..dac3e64 100644 --- a/src/main/java/com/google/gwtorm/server/ListResultSet.java +++ b/src/main/java/com/google/gwtorm/server/ListResultSet.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - import java.util.ArrayList; import java.util.Iterator; import java.util.List;
diff --git a/src/main/java/com/google/gwtorm/server/OrmException.java b/src/main/java/com/google/gwtorm/server/OrmException.java index a5acd32..24325b0 100644 --- a/src/main/java/com/google/gwtorm/server/OrmException.java +++ b/src/main/java/com/google/gwtorm/server/OrmException.java
@@ -14,9 +14,7 @@ package com.google.gwtorm.server; -/** - * Any data store read or write error. - */ +/** Any data store read or write error. */ @SuppressWarnings("serial") public class OrmException extends Exception { public OrmException(final String message) {
diff --git a/src/main/java/com/google/gwtorm/server/OrmRuntimeException.java b/src/main/java/com/google/gwtorm/server/OrmRuntimeException.java index 5220a3b..e3fbc4c 100644 --- a/src/main/java/com/google/gwtorm/server/OrmRuntimeException.java +++ b/src/main/java/com/google/gwtorm/server/OrmRuntimeException.java
@@ -14,9 +14,7 @@ package com.google.gwtorm.server; -/** - * Any data store read or write error. - */ +/** Any data store read or write error. */ @SuppressWarnings("serial") public class OrmRuntimeException extends RuntimeException { public OrmRuntimeException(final String message) {
diff --git a/src/main/java/com/google/gwtorm/server/PrimaryKey.java b/src/main/java/com/google/gwtorm/server/PrimaryKey.java index 73ae5b7..07c2eb6 100644 --- a/src/main/java/com/google/gwtorm/server/PrimaryKey.java +++ b/src/main/java/com/google/gwtorm/server/PrimaryKey.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -28,8 +27,6 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PrimaryKey { - /** - * @return name of the field in the entity which contains the primary key. - */ + /** @return name of the field in the entity which contains the primary key. */ String value(); }
diff --git a/src/main/java/com/google/gwtorm/server/Query.java b/src/main/java/com/google/gwtorm/server/Query.java index d7d0f9b..563c846 100644 --- a/src/main/java/com/google/gwtorm/server/Query.java +++ b/src/main/java/com/google/gwtorm/server/Query.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -22,17 +21,17 @@ /** * Annotation marking a method in an {@link Access} interface as a query. - * <p> - * Query methods must return a parameterized {@link ResultSet}, for example: + * + * <p>Query methods must return a parameterized {@link ResultSet}, for example: * * <pre> * public interface FooAccess extends Access<Foo, Foo.Key> { * @Query("WHERE a=?") * ResultSet<Foo> find(int a) throws OrmException; * } - *</pre> - *<p> - * Query strings must conform to the following grammar: + * </pre> + * + * <p>Query strings must conform to the following grammar: * * <pre> * [WHERE <condition> [AND <condition> ...]] @@ -42,16 +41,13 @@ * <condition> := <property> { < | <= | > | >= | = } <value> * <value> := { ? | true | false | <int> | <string> } * </pre> - * <p> - * Method parameters are bound in order to the placeholders (?) declared in the - * query conditions. The type of the limit placeholder parameter (if used in the - * query) must be <code>int</code>. + * + * <p>Method parameters are bound in order to the placeholders (?) declared in the query conditions. + * The type of the limit placeholder parameter (if used in the query) must be <code>int</code>. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Query { - /** - * @return the query clause. Defaults to "", matching all entities, no order. - */ + /** @return the query clause. Defaults to "", matching all entities, no order. */ String value() default ""; }
diff --git a/src/main/java/com/google/gwtorm/server/Relation.java b/src/main/java/com/google/gwtorm/server/Relation.java index f4141c6..40d652d 100644 --- a/src/main/java/com/google/gwtorm/server/Relation.java +++ b/src/main/java/com/google/gwtorm/server/Relation.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -22,9 +21,8 @@ /** * Annotation marking a method in a {@link Schema} interface as entity access. - * <p> - * Access methods must return an interface extending {@link Access}, for - * example: + * + * <p>Access methods must return an interface extending {@link Access}, for example: * * <pre> * public interface FooAccess extends Access<Foo, Foo.Key> { @@ -35,22 +33,20 @@ * FooAccess foos(); * } * </pre> - * <p> - * The table name within the data store will be derived from the relation - * annotation, or the method name. + * + * <p>The table name within the data store will be derived from the relation annotation, or the + * method name. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Relation { - /** - * @return the name of the data store table. Defaults to the method name. - */ + /** @return the name of the data store table. Defaults to the method name. */ String name() default ""; /** - * @return the unique ID for this relation. Must be unique among all - * relations, and conform to Protobuf message ID rules. The ID must be - * in the range [1,2^29-1] except 19000 through 19999. + * @return the unique ID for this relation. Must be unique among all relations, and conform to + * Protobuf message ID rules. The ID must be in the range [1,2^29-1] except 19000 through + * 19999. */ int id(); }
diff --git a/src/main/java/com/google/gwtorm/server/ResultSet.java b/src/main/java/com/google/gwtorm/server/ResultSet.java index 18f8c75..25ea15e 100644 --- a/src/main/java/com/google/gwtorm/server/ResultSet.java +++ b/src/main/java/com/google/gwtorm/server/ResultSet.java
@@ -25,19 +25,18 @@ public interface ResultSet<T> extends Iterable<T> { /** * Obtain an iterator to loop through the results. - * <p> - * The iterator can be obtained only once. When the iterator completes ( - * <code>hasNext()</code> returns false) {@link #close()} will be - * automatically called. + * + * <p>The iterator can be obtained only once. When the iterator completes ( <code>hasNext()</code> + * returns false) {@link #close()} will be automatically called. */ @Override Iterator<T> iterator(); /** * Materialize all results as a single list. - * <p> - * Prior to returning {@link #close()} is invoked. This method must not be - * combined with {@link #iterator()} on the same instance. + * + * <p>Prior to returning {@link #close()} is invoked. This method must not be combined with {@link + * #iterator()} on the same instance. * * @return mutable list of the complete results. */ @@ -45,9 +44,9 @@ /** * Close the result, discarding any further results. - * <p> - * This method may be invoked more than once. Its main use is to stop - * obtaining results before the iterator has finished. + * + * <p>This method may be invoked more than once. Its main use is to stop obtaining results before + * the iterator has finished. */ void close(); }
diff --git a/src/main/java/com/google/gwtorm/server/Schema.java b/src/main/java/com/google/gwtorm/server/Schema.java index 2357a89..026bb1d 100644 --- a/src/main/java/com/google/gwtorm/server/Schema.java +++ b/src/main/java/com/google/gwtorm/server/Schema.java
@@ -14,32 +14,28 @@ package com.google.gwtorm.server; - /** * Application database definition and top-level schema access. - * <p> - * Applications should extend this interface and declare relation methods for - * each entity/table used. Relation methods must be marked with the - * {@link Relation} annotation and return an interface extending {@link Access}. - * At runtime the application extension of Schema will be automatically - * implemented with a generated class, providing implementations of the Access + * + * <p>Applications should extend this interface and declare relation methods for each entity/table + * used. Relation methods must be marked with the {@link Relation} annotation and return an + * interface extending {@link Access}. At runtime the application extension of Schema will be + * automatically implemented with a generated class, providing implementations of the Access * extensions from each of the declared relation methods. - * <p> - * Instances of a schema should be obtained through the - * {@link com.google.gwtorm.jdbc.Database} class on a pure-JDBC implementation - * and through <code>GWT.create()</code> on the GWT client side. - * <p> - * In the JDBC implementation each Schema instance wraps around a single JDBC - * Connection object. Therefore a Schema instance has a 1:1 relationship with an - * active database handle. - * <p> - * A Schema instance (as well as its returned Access instances) is not thread - * safe. Applications must provide their own synchronization, or ensure that at - * most 1 thread access a Schema instance (or any returned Access instance) at a - * time. The safest mapping is 1 schema instance per thread, never shared. - * <p> - * For example the OurDb schema creates two tables (identical structure) named - * <code>someFoos</code> and <code>otherFoos</code>: + * + * <p>Instances of a schema should be obtained through the {@link com.google.gwtorm.jdbc.Database} + * class on a pure-JDBC implementation and through <code>GWT.create()</code> on the GWT client side. + * + * <p>In the JDBC implementation each Schema instance wraps around a single JDBC Connection object. + * Therefore a Schema instance has a 1:1 relationship with an active database handle. + * + * <p>A Schema instance (as well as its returned Access instances) is not thread safe. Applications + * must provide their own synchronization, or ensure that at most 1 thread access a Schema instance + * (or any returned Access instance) at a time. The safest mapping is 1 schema instance per thread, + * never shared. + * + * <p>For example the OurDb schema creates two tables (identical structure) named <code>someFoos + * </code> and <code>otherFoos</code>: * * <pre> * public interface FooAccess extends Access<Foo, Foo.Key> { @@ -64,10 +60,10 @@ /** * Add any missing columns, create any missing tables or sequences. - * <p> - * This method does not drop any unused columns or tables, leaving them intact - * for applications to continue to query after the update. Any unused columns - * that are NOT NULL are altered to accept NULL. + * + * <p>This method does not drop any unused columns or tables, leaving them intact for applications + * to continue to query after the update. Any unused columns that are NOT NULL are altered to + * accept NULL. * * @param e executor to perform (or log) the statements. * @throws OrmException one or more objects could not be added to the schema. @@ -76,8 +72,8 @@ /** * Drop any unused columns, tables, or sequences. - * <p> - * This method destroys data, as columns may be removed entirely. + * + * <p>This method destroys data, as columns may be removed entirely. * * @param e executor to perform (or log) the statements. * @throws OrmException one or more drops could not be completed.
diff --git a/src/main/java/com/google/gwtorm/server/SchemaConstructorGen.java b/src/main/java/com/google/gwtorm/server/SchemaConstructorGen.java index 95ea82a..175b212 100644 --- a/src/main/java/com/google/gwtorm/server/SchemaConstructorGen.java +++ b/src/main/java/com/google/gwtorm/server/SchemaConstructorGen.java
@@ -15,15 +15,13 @@ package com.google.gwtorm.server; import com.google.gwtorm.schema.Util; - +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - /** Generates a factory to efficiently create new Schema instances. */ public class SchemaConstructorGen<T extends Schema> implements Opcodes { private static final String CTX = "schemaArg"; @@ -35,8 +33,7 @@ private String implClassName; private String implTypeName; - public SchemaConstructorGen(final GeneratedClassLoader loader, - final Class<T> c, final Object f) { + public SchemaConstructorGen(final GeneratedClassLoader loader, final Class<T> c, final Object f) { classLoader = loader; schemaImpl = c; schemaArg = f; @@ -51,7 +48,6 @@ classLoader.defineClass(implClassName, cw.toByteArray()); } - public SchemaFactory<T> create() throws OrmException { defineClass(); try { @@ -77,34 +73,43 @@ } private void init() { - implClassName = - schemaImpl.getName() + "_Factory_" + Util.createRandomName(); + implClassName = schemaImpl.getName() + "_Factory_" + Util.createRandomName(); implTypeName = implClassName.replace('.', '/'); cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - cw.visit(V1_3, ACC_PUBLIC | ACC_FINAL | ACC_SUPER, implTypeName, null, Type - .getInternalName(Object.class), new String[] {Type - .getInternalName(SchemaFactory.class)}); + cw.visit( + V1_3, + ACC_PUBLIC | ACC_FINAL | ACC_SUPER, + implTypeName, + null, + Type.getInternalName(Object.class), + new String[] {Type.getInternalName(SchemaFactory.class)}); } private void declareFactoryField() { - cw.visitField(ACC_PRIVATE | ACC_FINAL, CTX, - Type.getType(schemaArg.getClass()).getDescriptor(), null, null) + cw.visitField( + ACC_PRIVATE | ACC_FINAL, + CTX, + Type.getType(schemaArg.getClass()).getDescriptor(), + null, + null) .visitEnd(); } private void implementConstructor() { final Type ft = Type.getType(schemaArg.getClass()); final String consName = "<init>"; - final String consDesc = - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {ft}); + final String consDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {ft}); final MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, consName, consDesc, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), - consName, Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); + mv.visitMethodInsn( + INVOKESPECIAL, + Type.getInternalName(Object.class), + consName, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); @@ -119,9 +124,12 @@ final Type ft = Type.getType(schemaArg.getClass()); final String typeName = Type.getType(schemaImpl).getInternalName(); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "open", Type - .getMethodDescriptor(Type.getType(Schema.class), new Type[] {}), - null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "open", + Type.getMethodDescriptor(Type.getType(Schema.class), new Type[] {}), + null, + null); mv.visitCode(); Constructor<?> c = schemaImpl.getDeclaredConstructors()[0]; @@ -131,8 +139,11 @@ mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, implTypeName, CTX, ft.getDescriptor()); - mv.visitMethodInsn(INVOKESPECIAL, typeName, "<init>", Type - .getMethodDescriptor(Type.VOID_TYPE, new Type[] {argType})); + mv.visitMethodInsn( + INVOKESPECIAL, + typeName, + "<init>", + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {argType})); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); mv.visitEnd();
diff --git a/src/main/java/com/google/gwtorm/server/SchemaFactory.java b/src/main/java/com/google/gwtorm/server/SchemaFactory.java index 2cc6d35..3909fca 100644 --- a/src/main/java/com/google/gwtorm/server/SchemaFactory.java +++ b/src/main/java/com/google/gwtorm/server/SchemaFactory.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - /** * Creates new application Schema instances on demand. * @@ -25,9 +24,8 @@ * Open a new connection to the database and get a Schema wrapper. * * @return a new connection, wrapped up in the application's Schema. - * @throws OrmException the connection could not be opened to the database. - * The exception detail should be examined to determine the root cause - * of the connection failure. + * @throws OrmException the connection could not be opened to the database. The exception detail + * should be examined to determine the root cause of the connection failure. */ S open() throws OrmException; }
diff --git a/src/main/java/com/google/gwtorm/server/SchemaGen.java b/src/main/java/com/google/gwtorm/server/SchemaGen.java index b0a44de..cbee521 100644 --- a/src/main/java/com/google/gwtorm/server/SchemaGen.java +++ b/src/main/java/com/google/gwtorm/server/SchemaGen.java
@@ -18,22 +18,19 @@ import com.google.gwtorm.schema.SchemaModel; import com.google.gwtorm.schema.SequenceModel; import com.google.gwtorm.schema.Util; - +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - /** Generates a concrete implementation of a {@link Schema} extension. */ public class SchemaGen<S extends AbstractSchema> implements Opcodes { public interface AccessGenerator { - Class<?> create(GeneratedClassLoader loader, RelationModel rm) - throws OrmException; + Class<?> create(GeneratedClassLoader loader, RelationModel rm) throws OrmException; } private final GeneratedClassLoader classLoader; @@ -46,9 +43,12 @@ private String implClassName; private String implTypeName; - public SchemaGen(final GeneratedClassLoader loader, - final SchemaModel schemaModel, final Class<?> databaseType, - final Class<S> superType, final AccessGenerator ag) { + public SchemaGen( + final GeneratedClassLoader loader, + final SchemaModel schemaModel, + final Class<?> databaseType, + final Class<S> superType, + final AccessGenerator ag) { classLoader = loader; schema = schemaModel; databaseClass = databaseType; @@ -100,16 +100,18 @@ relations.add(new RelationGen(rel, a)); } - Collections.sort(relations, new Comparator<RelationGen>() { - @Override - public int compare(RelationGen a, RelationGen b) { - int cmp = a.model.getRelationID() - b.model.getRelationID(); - if (cmp == 0) { - cmp = a.model.getRelationName().compareTo(b.model.getRelationName()); - } - return cmp; - } - }); + Collections.sort( + relations, + new Comparator<RelationGen>() { + @Override + public int compare(RelationGen a, RelationGen b) { + int cmp = a.model.getRelationID() - b.model.getRelationID(); + if (cmp == 0) { + cmp = a.model.getRelationName().compareTo(b.model.getRelationName()); + } + return cmp; + } + }); } private void init() { @@ -117,9 +119,13 @@ implTypeName = implClassName.replace('.', '/'); cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - cw.visit(V1_3, ACC_PUBLIC | ACC_FINAL | ACC_SUPER, implTypeName, null, Type - .getInternalName(schemaSuperClass), new String[] {getSchemaClassName() - .replace('.', '/')}); + cw.visit( + V1_3, + ACC_PUBLIC | ACC_FINAL | ACC_SUPER, + implTypeName, + null, + Type.getInternalName(schemaSuperClass), + new String[] {getSchemaClassName().replace('.', '/')}); } private void implementRelationFields() { @@ -134,27 +140,41 @@ final Type dbType = Type.getType(databaseClass); final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC, consName, Type.getMethodDescriptor( - Type.VOID_TYPE, new Type[] {dbType}), null, null); + cw.visitMethod( + ACC_PUBLIC, + consName, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {dbType}), + null, + null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); - mv.visitMethodInsn(INVOKESPECIAL, superType.getInternalName(), consName, - Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {Type - .getType(schemaSuperClass.getDeclaredConstructors()[0] - .getParameterTypes()[0])})); + mv.visitMethodInsn( + INVOKESPECIAL, + superType.getInternalName(), + consName, + Type.getMethodDescriptor( + Type.VOID_TYPE, + new Type[] { + Type.getType(schemaSuperClass.getDeclaredConstructors()[0].getParameterTypes()[0]) + })); for (final RelationGen info : relations) { mv.visitVarInsn(ALOAD, 0); mv.visitTypeInsn(NEW, info.accessType.getInternalName()); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, info.accessType.getInternalName(), - consName, Type.getMethodDescriptor(Type.VOID_TYPE, - new Type[] {superType})); - mv.visitFieldInsn(PUTFIELD, implTypeName, info - .getAccessInstanceFieldName(), info.accessType.getDescriptor()); + mv.visitMethodInsn( + INVOKESPECIAL, + info.accessType.getInternalName(), + consName, + Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {superType})); + mv.visitFieldInsn( + PUTFIELD, + implTypeName, + info.getAccessInstanceFieldName(), + info.accessType.getDescriptor()); } mv.visitInsn(RETURN); @@ -166,18 +186,22 @@ for (final SequenceModel seq : schema.getSequences()) { final Type retType = Type.getType(seq.getResultType()); final MethodVisitor mv = - cw - .visitMethod(ACC_PUBLIC, seq.getMethodName(), Type - .getMethodDescriptor(retType, new Type[] {}), null, - new String[] {Type.getType(OrmException.class) - .getInternalName()}); + cw.visitMethod( + ACC_PUBLIC, + seq.getMethodName(), + Type.getMethodDescriptor(retType, new Type[] {}), + null, + new String[] {Type.getType(OrmException.class).getInternalName()}); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(seq.getSequenceName()); - mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(schemaSuperClass), - "nextLong", Type.getMethodDescriptor(Type.getType(Long.TYPE), - new Type[] {Type.getType(String.class)})); + mv.visitMethodInsn( + INVOKEVIRTUAL, + Type.getInternalName(schemaSuperClass), + "nextLong", + Type.getMethodDescriptor( + Type.getType(Long.TYPE), new Type[] {Type.getType(String.class)})); if (retType.getSize() == 1) { mv.visitInsn(L2I); mv.visitInsn(IRETURN); @@ -197,9 +221,12 @@ private void implementAllRelationsMethod() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, "allRelations", Type - .getMethodDescriptor(Type.getType(Access[].class), new Type[] {}), - null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, + "allRelations", + Type.getMethodDescriptor(Type.getType(Access[].class), new Type[] {}), + null, + null); mv.visitCode(); final int r = 1; @@ -214,8 +241,8 @@ cgs.push(index++); mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKEVIRTUAL, getImplTypeName(), info.model - .getMethodName(), info.getDescriptor()); + mv.visitMethodInsn( + INVOKEVIRTUAL, getImplTypeName(), info.model.getMethodName(), info.getDescriptor()); mv.visitInsn(AASTORE); } @@ -236,8 +263,13 @@ } void implementField() { - cw.visitField(ACC_PRIVATE | ACC_FINAL, getAccessInstanceFieldName(), - accessType.getDescriptor(), null, null).visitEnd(); + cw.visitField( + ACC_PRIVATE | ACC_FINAL, + getAccessInstanceFieldName(), + accessType.getDescriptor(), + null, + null) + .visitEnd(); } String getAccessInstanceFieldName() { @@ -246,20 +278,20 @@ void implementMethod() { final MethodVisitor mv = - cw.visitMethod(ACC_PUBLIC | ACC_FINAL, model.getMethodName(), - getDescriptor(), null, null); + cw.visitMethod( + ACC_PUBLIC | ACC_FINAL, model.getMethodName(), getDescriptor(), null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, implTypeName, getAccessInstanceFieldName(), - accessType.getDescriptor()); + mv.visitFieldInsn( + GETFIELD, implTypeName, getAccessInstanceFieldName(), accessType.getDescriptor()); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); } String getDescriptor() { - return Type.getMethodDescriptor(Type.getObjectType(model - .getAccessInterfaceName().replace('.', '/')), new Type[] {}); + return Type.getMethodDescriptor( + Type.getObjectType(model.getAccessInterfaceName().replace('.', '/')), new Type[] {}); } } }
diff --git a/src/main/java/com/google/gwtorm/server/Sequence.java b/src/main/java/com/google/gwtorm/server/Sequence.java index 5be3371..45acf3f 100644 --- a/src/main/java/com/google/gwtorm/server/Sequence.java +++ b/src/main/java/com/google/gwtorm/server/Sequence.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.server; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -22,9 +21,8 @@ /** * Annotation marking a method in {@link Schema} interface as number generator. - * <p> - * Sequence methods must return a primitive <code>int</code> or - * <code>long</code> type. + * + * <p>Sequence methods must return a primitive <code>int</code> or <code>long</code> type. * * <pre> * public interface BarSchema extends Schema { @@ -32,31 +30,27 @@ * int nextId(); * } * </pre> - * <p> - * The sequence name will be taken from the method name, after removing the - * optional prefix "next". + * + * <p>The sequence name will be taken from the method name, after removing the optional prefix + * "next". */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Sequence { - /** - * @return the name of the sequence. Defaults to the method name. - */ + /** @return the name of the sequence. Defaults to the method name. */ String name() default ""; /** - * @return the initial value of the sequence. Defaults to 1, or whatever the - * database dialect defaults to if the sequence starting value is not - * supplied in the sequence declaration. + * @return the initial value of the sequence. Defaults to 1, or whatever the database dialect + * defaults to if the sequence starting value is not supplied in the sequence declaration. */ long startWith() default 0; /** - * @return maximum number of values to cache in memory from the sequence. - * Defaults to -1, indicating a default caching level should be - * determined by the database. Cached values may be lost (never - * returned by the sequence, creating gaps) if the application or the - * database is shutdown and restarted. + * @return maximum number of values to cache in memory from the sequence. Defaults to -1, + * indicating a default caching level should be determined by the database. Cached values may + * be lost (never returned by the sequence, creating gaps) if the application or the database + * is shutdown and restarted. */ int cache() default -1; }
diff --git a/src/main/java/com/google/gwtorm/server/StandardKeyEncoder.java b/src/main/java/com/google/gwtorm/server/StandardKeyEncoder.java index c9076e8..1339542 100644 --- a/src/main/java/com/google/gwtorm/server/StandardKeyEncoder.java +++ b/src/main/java/com/google/gwtorm/server/StandardKeyEncoder.java
@@ -15,14 +15,13 @@ package com.google.gwtorm.server; import com.google.gwtorm.client.KeyUtil.Encoder; - import java.io.UnsupportedEncodingException; import java.util.Arrays; public class StandardKeyEncoder extends Encoder { - private static final char[] hexc = - {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', - 'E', 'F'}; + private static final char[] hexc = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; private static final char safe[]; private static final byte hexb[]; @@ -39,21 +38,15 @@ safe[')'] = ')'; safe['/'] = '/'; safe[' '] = '+'; - for (char c = '0'; c <= '9'; c++) - safe[c] = c; - for (char c = 'A'; c <= 'Z'; c++) - safe[c] = c; - for (char c = 'a'; c <= 'z'; c++) - safe[c] = c; + for (char c = '0'; c <= '9'; c++) safe[c] = c; + for (char c = 'A'; c <= 'Z'; c++) safe[c] = c; + for (char c = 'a'; c <= 'z'; c++) safe[c] = c; hexb = new byte['f' + 1]; Arrays.fill(hexb, (byte) -1); - for (char i = '0'; i <= '9'; i++) - hexb[i] = (byte) (i - '0'); - for (char i = 'A'; i <= 'F'; i++) - hexb[i] = (byte) ((i - 'A') + 10); - for (char i = 'a'; i <= 'f'; i++) - hexb[i] = (byte) ((i - 'a') + 10); + for (char i = '0'; i <= '9'; i++) hexb[i] = (byte) (i - '0'); + for (char i = 'A'; i <= 'F'; i++) hexb[i] = (byte) ((i - 'A') + 10); + for (char i = 'a'; i <= 'f'; i++) hexb[i] = (byte) ((i - 'a') + 10); } @Override @@ -89,7 +82,7 @@ final byte[] b = new byte[e.length()]; int bPtr = 0; try { - for (int i = 0; i < e.length();) { + for (int i = 0; i < e.length(); ) { final char c = e.charAt(i); if (c == '%' && i + 2 < e.length()) { final int v = (hexb[e.charAt(i + 1)] << 4) | hexb[e.charAt(i + 2)]; @@ -115,4 +108,4 @@ throw new RuntimeException("No UTF-8 support", e1); } } -} \ No newline at end of file +}
diff --git a/src/test/java/com/google/gwtorm/client/IntKeyTestCase.java b/src/test/java/com/google/gwtorm/client/IntKeyTestCase.java index e985f5b..104068a 100644 --- a/src/test/java/com/google/gwtorm/client/IntKeyTestCase.java +++ b/src/test/java/com/google/gwtorm/client/IntKeyTestCase.java
@@ -14,16 +14,15 @@ package com.google.gwtorm.client; -import com.google.gwtorm.server.StandardKeyEncoder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import com.google.gwtorm.server.StandardKeyEncoder; import org.junit.Before; import org.junit.Test; - public class IntKeyTestCase { @SuppressWarnings("serial") private abstract static class IntKeyImpl<T extends Key<?>> extends IntKey<T> {
diff --git a/src/test/java/com/google/gwtorm/client/LongKeyTestCase.java b/src/test/java/com/google/gwtorm/client/LongKeyTestCase.java index 1e46753..17b298b 100644 --- a/src/test/java/com/google/gwtorm/client/LongKeyTestCase.java +++ b/src/test/java/com/google/gwtorm/client/LongKeyTestCase.java
@@ -20,15 +20,12 @@ import static org.junit.Assert.assertTrue; import com.google.gwtorm.server.StandardKeyEncoder; - import org.junit.Before; import org.junit.Test; - public class LongKeyTestCase { @SuppressWarnings("serial") - private abstract static class LongKeyImpl<T extends Key<?>> extends - LongKey<T> { + private abstract static class LongKeyImpl<T extends Key<?>> extends LongKey<T> { @Column(id = 1) long id;
diff --git a/src/test/java/com/google/gwtorm/client/StringKeyTestCase.java b/src/test/java/com/google/gwtorm/client/StringKeyTestCase.java index 0833347..731cf8c 100644 --- a/src/test/java/com/google/gwtorm/client/StringKeyTestCase.java +++ b/src/test/java/com/google/gwtorm/client/StringKeyTestCase.java
@@ -20,15 +20,12 @@ import static org.junit.Assert.assertTrue; import com.google.gwtorm.server.StandardKeyEncoder; - import org.junit.Before; import org.junit.Test; - public class StringKeyTestCase { @SuppressWarnings("serial") - private abstract static class StringKeyImpl<T extends Key<?>> extends - StringKey<T> { + private abstract static class StringKeyImpl<T extends Key<?>> extends StringKey<T> { @Column(id = 1) String name;
diff --git a/src/test/java/com/google/gwtorm/data/Address.java b/src/test/java/com/google/gwtorm/data/Address.java index cc4c907..4bdae52 100644 --- a/src/test/java/com/google/gwtorm/data/Address.java +++ b/src/test/java/com/google/gwtorm/data/Address.java
@@ -60,8 +60,7 @@ @Column(id = 3, notNull = false) protected byte[] photo; - protected Address() { - } + protected Address() {} public Address(final Address.Key city, final String where) { this.city = city;
diff --git a/src/test/java/com/google/gwtorm/data/Person.java b/src/test/java/com/google/gwtorm/data/Person.java index 13ff465..2bf0a80 100644 --- a/src/test/java/com/google/gwtorm/data/Person.java +++ b/src/test/java/com/google/gwtorm/data/Person.java
@@ -17,15 +17,13 @@ import com.google.gwtorm.client.Column; import com.google.gwtorm.client.StringKey; - public class Person { @SuppressWarnings("serial") public static class Key extends StringKey<com.google.gwtorm.client.Key<?>> { @Column(id = 1, length = 20) protected String name; - protected Key() { - } + protected Key() {} public Key(final String name) { this.name = name; @@ -51,8 +49,7 @@ @Column(id = 3) protected boolean registered; - protected Person() { - } + protected Person() {} public Person(final Key key, final int age) { this.name = key;
diff --git a/src/test/java/com/google/gwtorm/data/Person2.java b/src/test/java/com/google/gwtorm/data/Person2.java index ab363e7..07a14a5 100644 --- a/src/test/java/com/google/gwtorm/data/Person2.java +++ b/src/test/java/com/google/gwtorm/data/Person2.java
@@ -16,7 +16,6 @@ import com.google.gwtorm.client.Column; - public class Person2 { @Column(id = 1) protected Person.Key name;
diff --git a/src/test/java/com/google/gwtorm/data/PersonAccess.java b/src/test/java/com/google/gwtorm/data/PersonAccess.java index af36e7a..c80cce6 100644 --- a/src/test/java/com/google/gwtorm/data/PersonAccess.java +++ b/src/test/java/com/google/gwtorm/data/PersonAccess.java
@@ -32,8 +32,7 @@ ResultSet<Person> olderThan(int age) throws OrmException; @Query("WHERE age > ? ORDER BY name DESC") - ResultSet<Person> olderThanDescByName(int age) - throws OrmException; + ResultSet<Person> olderThanDescByName(int age) throws OrmException; @Query("WHERE name = 'bob' LIMIT ?") ResultSet<Person> firstNBob(int n) throws OrmException;
diff --git a/src/test/java/com/google/gwtorm/jdbc/AbstractTestJdbcAccess.java b/src/test/java/com/google/gwtorm/jdbc/AbstractTestJdbcAccess.java index 267bfcc..74e703c 100644 --- a/src/test/java/com/google/gwtorm/jdbc/AbstractTestJdbcAccess.java +++ b/src/test/java/com/google/gwtorm/jdbc/AbstractTestJdbcAccess.java
@@ -14,7 +14,6 @@ package com.google.gwtorm.jdbc; - import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import static org.mockito.Mockito.doNothing; @@ -32,13 +31,6 @@ import com.google.gwtorm.server.OrmConcurrencyException; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.ResultSet; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.mockito.stubbing.OngoingStubbing; - import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; @@ -47,6 +39,11 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.mockito.stubbing.OngoingStubbing; @RunWith(Parameterized.class) public abstract class AbstractTestJdbcAccess { @@ -67,7 +64,7 @@ protected SQLException sqlException = null; - static abstract class IterableProvider<T> { + abstract static class IterableProvider<T> { abstract Iterable<T> createIterable(T... ts); } @@ -102,12 +99,13 @@ @Parameters public static Collection<Object[]> data() { - return Arrays.asList(new Object[][] { {LIST_PROVIDER}, - {UNMODIFIABLE_LIST_PROVIDER}, {LIST_RESULT_SET_PROVIDER},}); + return Arrays.asList( + new Object[][] { + {LIST_PROVIDER}, {UNMODIFIABLE_LIST_PROVIDER}, {LIST_RESULT_SET_PROVIDER}, + }); } - public AbstractTestJdbcAccess(IterableProvider<Data> dataProvider) - throws SQLException { + public AbstractTestJdbcAccess(IterableProvider<Data> dataProvider) throws SQLException { noData = dataProvider.createIterable(); oneRow = dataProvider.createIterable(new Data(1)); twoRows = dataProvider.createIterable(new Data(1), new Data(2)); @@ -119,8 +117,8 @@ protected abstract SqlDialect createDialect() throws SQLException; - private PreparedStatement stubStatementWithUpdateCounts(String command, - final int... updateCounts) throws SQLException { + private PreparedStatement stubStatementWithUpdateCounts(String command, final int... updateCounts) + throws SQLException { PreparedStatement ps = mock(PreparedStatement.class); // batching @@ -162,8 +160,7 @@ return classUnderTest; } - private static JdbcSchema setupSchema(final SqlDialect dialect, - final Connection conn) { + private static JdbcSchema setupSchema(final SqlDialect dialect, final Connection conn) { @SuppressWarnings("rawtypes") Database db = mock(Database.class); try { @@ -186,8 +183,8 @@ assertExpectedIdsUsed(ps, ids); } - protected static void assertUsedNonBatchingOnly(PreparedStatement ps, - int... ids) throws SQLException { + protected static void assertUsedNonBatchingOnly(PreparedStatement ps, int... ids) + throws SQLException { verify(ps, never()).addBatch(); verify(ps, never()).executeBatch(); verify(ps, times(ids.length)).executeUpdate(); @@ -198,14 +195,13 @@ verifyZeroInteractions(insert); } - protected abstract void assertCorrectUpdating(PreparedStatement ps, - int... ids) throws SQLException; + protected abstract void assertCorrectUpdating(PreparedStatement ps, int... ids) + throws SQLException; - protected abstract void assertCorrectAttempting(PreparedStatement ps, - int... ids) throws SQLException; + protected abstract void assertCorrectAttempting(PreparedStatement ps, int... ids) + throws SQLException; - private static void assertExpectedIdsUsed(PreparedStatement ps, int... ids) - throws SQLException { + private static void assertExpectedIdsUsed(PreparedStatement ps, int... ids) throws SQLException { for (int id : ids) { verify(ps).setInt(1, id); } @@ -228,8 +224,7 @@ @Test public void testInsertOneException() throws SQLException { sqlException = new BatchUpdateException(); - PreparedStatement insert = - stubStatementThrowExceptionOnExecute(INSERT, sqlException); + PreparedStatement insert = stubStatementThrowExceptionOnExecute(INSERT, sqlException); try { classUnderTest.insert(oneRow); fail("missingException"); @@ -258,8 +253,7 @@ @Test public void testUpdateOneException() throws SQLException { sqlException = new BatchUpdateException(); - PreparedStatement update = - stubStatementThrowExceptionOnExecute(UPDATE, sqlException); + PreparedStatement update = stubStatementThrowExceptionOnExecute(UPDATE, sqlException); try { classUnderTest.update(oneRow); fail("missingException"); @@ -272,8 +266,7 @@ } @Test - public void testUpdateTwoConcurrentlyModifiedException() throws SQLException, - OrmException { + public void testUpdateTwoConcurrentlyModifiedException() throws SQLException, OrmException { PreparedStatement update = stubStatementWithUpdateCounts(UPDATE, 0, 0); try { classUnderTest.update(twoRows); @@ -303,8 +296,7 @@ @Test public void upsertOneException() throws SQLException { SQLException exception = new BatchUpdateException(); - PreparedStatement update = - stubStatementThrowExceptionOnExecute(UPDATE, exception); + PreparedStatement update = stubStatementThrowExceptionOnExecute(UPDATE, exception); try { classUnderTest.upsert(oneRow); fail("missingException"); @@ -328,8 +320,7 @@ } @Test - public void testUpsertTwoNotExistingZeroLengthArray() throws SQLException, - OrmException { + public void testUpsertTwoNotExistingZeroLengthArray() throws SQLException, OrmException { PreparedStatement update = stubStatementWithUpdateCounts(UPDATE); PreparedStatement insert = stubStatementWithUpdateCounts(INSERT, 1, 1); @@ -373,8 +364,7 @@ } @Test - public void testUpsertTwoUpdateCountsAreNull() throws SQLException, - OrmException { + public void testUpsertTwoUpdateCountsAreNull() throws SQLException, OrmException { PreparedStatement update = stubStatementWithUpdateCounts(UPDATE, null); PreparedStatement insert = stubStatementWithUpdateCounts(INSERT, 1, 1); @@ -427,7 +417,6 @@ public Access<?, ?>[] allRelations() { throw new UnsupportedOperationException(); } - } static class Data { @@ -449,9 +438,7 @@ public void fromString(String in) { throw new UnsupportedOperationException(); } - } - } private static class DataJdbcAccess extends JdbcAccess<Data, Data.DataKey> { @@ -496,26 +483,22 @@ } @Override - protected void bindOneInsert(PreparedStatement ps, Data entity) - throws SQLException { + protected void bindOneInsert(PreparedStatement ps, Data entity) throws SQLException { ps.setInt(1, entity.id); } @Override - protected void bindOneUpdate(PreparedStatement ps, Data entity) - throws SQLException { + protected void bindOneUpdate(PreparedStatement ps, Data entity) throws SQLException { ps.setInt(1, entity.id); } @Override - protected void bindOneDelete(PreparedStatement ps, Data entity) - throws SQLException { + protected void bindOneDelete(PreparedStatement ps, Data entity) throws SQLException { ps.setInt(1, entity.id); } @Override - protected void bindOneFetch(java.sql.ResultSet rs, Data entity) - throws SQLException { + protected void bindOneFetch(java.sql.ResultSet rs, Data entity) throws SQLException { throw new UnsupportedOperationException(); } @@ -528,7 +511,5 @@ public ResultSet<Data> iterateAllEntities() throws OrmException { throw new UnsupportedOperationException(); } - } - }
diff --git a/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessBatching.java b/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessBatching.java index 0d687d6..7e3ca88 100644 --- a/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessBatching.java +++ b/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessBatching.java
@@ -18,30 +18,25 @@ import static org.mockito.Mockito.mock; import com.google.gwtorm.schema.sql.SqlDialect; - -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import java.sql.PreparedStatement; import java.sql.SQLException; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class TestJdbcAccessBatching extends AbstractTestJdbcAccess { - public TestJdbcAccessBatching(IterableProvider<Data> dataProvider) - throws SQLException { + public TestJdbcAccessBatching(IterableProvider<Data> dataProvider) throws SQLException { super(dataProvider); } @Override - protected void assertCorrectUpdating(PreparedStatement ps, - int ... ids) throws SQLException { + protected void assertCorrectUpdating(PreparedStatement ps, int... ids) throws SQLException { assertUsedBatchingOnly(ps, ids); } @Override - protected void assertCorrectAttempting(PreparedStatement ps, - int ... ids) throws SQLException { + protected void assertCorrectAttempting(PreparedStatement ps, int... ids) throws SQLException { assertUsedBatchingOnly(ps, ids); } @@ -49,5 +44,4 @@ protected SqlDialect createDialect() { return mock(SqlDialect.class, CALLS_REAL_METHODS); } - }
diff --git a/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessNonBatching.java b/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessNonBatching.java index 7ab5b80..50297ac 100644 --- a/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessNonBatching.java +++ b/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessNonBatching.java
@@ -20,30 +20,25 @@ import static org.mockito.Mockito.when; import com.google.gwtorm.schema.sql.SqlDialect; - -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import java.sql.PreparedStatement; import java.sql.SQLException; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class TestJdbcAccessNonBatching extends AbstractTestJdbcAccess { - public TestJdbcAccessNonBatching(IterableProvider<Data> dataProvider) - throws SQLException { + public TestJdbcAccessNonBatching(IterableProvider<Data> dataProvider) throws SQLException { super(dataProvider); } @Override - protected void assertCorrectUpdating(PreparedStatement ps, int... ids) - throws SQLException { + protected void assertCorrectUpdating(PreparedStatement ps, int... ids) throws SQLException { assertUsedNonBatchingOnly(ps, ids); } @Override - protected void assertCorrectAttempting(PreparedStatement ps, int... ids) - throws SQLException { + protected void assertCorrectAttempting(PreparedStatement ps, int... ids) throws SQLException { assertUsedNonBatchingOnly(ps, ids); } @@ -51,10 +46,8 @@ protected SqlDialect createDialect() { final SqlDialect dialect = mock(SqlDialect.class); when(dialect.canDetermineIndividualBatchUpdateCounts()).thenReturn(FALSE); - when( - dialect.convertError(any(String.class), any(String.class), - any(SQLException.class))).thenCallRealMethod(); + when(dialect.convertError(any(String.class), any(String.class), any(SQLException.class))) + .thenCallRealMethod(); return dialect; } - }
diff --git a/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessTotalUpdateCount.java b/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessTotalUpdateCount.java index 9e329aa..9df4d8a 100644 --- a/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessTotalUpdateCount.java +++ b/src/test/java/com/google/gwtorm/jdbc/TestJdbcAccessTotalUpdateCount.java
@@ -22,32 +22,27 @@ import static org.mockito.Mockito.when; import com.google.gwtorm.schema.sql.SqlDialect; - +import java.sql.PreparedStatement; +import java.sql.SQLException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.sql.PreparedStatement; -import java.sql.SQLException; - @RunWith(Parameterized.class) public class TestJdbcAccessTotalUpdateCount extends AbstractTestJdbcAccess { - public TestJdbcAccessTotalUpdateCount(IterableProvider<Data> dataProvider) - throws SQLException { + public TestJdbcAccessTotalUpdateCount(IterableProvider<Data> dataProvider) throws SQLException { super(dataProvider); } @Override - protected void assertCorrectUpdating(PreparedStatement ps, int... ids) - throws SQLException { + protected void assertCorrectUpdating(PreparedStatement ps, int... ids) throws SQLException { verify(dialect).executeBatch(ps); } @Override - protected void assertCorrectAttempting(PreparedStatement ps, int... ids) - throws SQLException { + protected void assertCorrectAttempting(PreparedStatement ps, int... ids) throws SQLException { assertUsedNonBatchingOnly(ps, ids); } @@ -56,25 +51,24 @@ SqlDialect dialect = mock(SqlDialect.class); when(dialect.canDetermineIndividualBatchUpdateCounts()).thenReturn(FALSE); when(dialect.canDetermineTotalBatchUpdateCount()).thenReturn(TRUE); - when(dialect.executeBatch(any(PreparedStatement.class))).thenAnswer( - new Answer<Integer>() { + when(dialect.executeBatch(any(PreparedStatement.class))) + .thenAnswer( + new Answer<Integer>() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - if (sqlException != null) { - throw sqlException; - } - if (totalUpdateCount == null) { - throw new IllegalStateException("totalCount is not set"); - } - return totalUpdateCount; - } - }); - when( - dialect.convertError(any(String.class), any(String.class), - any(SQLException.class))).thenCallRealMethod(); + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + if (sqlException != null) { + throw sqlException; + } + if (totalUpdateCount == null) { + throw new IllegalStateException("totalCount is not set"); + } + return totalUpdateCount; + } + }); + when(dialect.convertError(any(String.class), any(String.class), any(SQLException.class))) + .thenCallRealMethod(); return dialect; } - }
diff --git a/src/test/java/com/google/gwtorm/nosql/IndexFunctionTest.java b/src/test/java/com/google/gwtorm/nosql/IndexFunctionTest.java index 4db5e85..28d8fbb 100644 --- a/src/test/java/com/google/gwtorm/nosql/IndexFunctionTest.java +++ b/src/test/java/com/google/gwtorm/nosql/IndexFunctionTest.java
@@ -25,7 +25,6 @@ import com.google.gwtorm.schema.java.JavaSchemaModel; import com.google.gwtorm.server.GeneratedClassLoader; import com.google.gwtorm.server.OrmException; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -76,8 +75,7 @@ @Test public void testPersonByNameAge_OrderByName() throws Exception { - IndexFunction<Person> idx = - index("nameAge", "WHERE name=? AND age=? ORDER BY name"); + IndexFunction<Person> idx = index("nameAge", "WHERE name=? AND age=? ORDER BY name"); Assert.assertEquals("nameAge", idx.getName()); IndexKeyBuilder b; @@ -92,8 +90,7 @@ @Test public void testPersonByNameAge_OrderByRegistered() throws Exception { - IndexFunction<Person> idx = - index("nameAge", "WHERE name=? AND age=? ORDER BY registered"); + IndexFunction<Person> idx = index("nameAge", "WHERE name=? AND age=? ORDER BY registered"); Assert.assertEquals("nameAge", idx.getName()); IndexKeyBuilder b; @@ -104,16 +101,24 @@ p.register(); assertTrue(idx.includes(p)); idx.encode(b, p); - assertEqualToBuilderResult(new byte[] {'q', 0x00, 0x01, // name - 0x01, 42, 0x00, 0x01, // age - 0x01, 0x01 // registered - }, b); + assertEqualToBuilderResult( + new byte[] { + 'q', + 0x00, + 0x01, // name + 0x01, + 42, + 0x00, + 0x01, // age + 0x01, + 0x01 // registered + }, + b); } @Test public void testPersonByNameRange_OrderByName() throws Exception { - IndexFunction<Person> idx = - index("nameSuggest", "WHERE name >= ? AND name <= ? ORDER BY name"); + IndexFunction<Person> idx = index("nameSuggest", "WHERE name >= ? AND name <= ? ORDER BY name"); assertEquals("nameSuggest", idx.getName()); IndexKeyBuilder b; @@ -128,8 +133,7 @@ @Test public void testOnlyRegistered() throws Exception { - IndexFunction<Person> idx = - index("isregistered", "WHERE registered = true ORDER BY name"); + IndexFunction<Person> idx = index("isregistered", "WHERE registered = true ORDER BY name"); assertEquals("isregistered", idx.getName()); IndexKeyBuilder b; @@ -147,8 +151,7 @@ @Test public void testOnlyAge42() throws Exception { - IndexFunction<Person> idx = - index("isOldEnough", "WHERE age = 42 ORDER BY name"); + IndexFunction<Person> idx = index("isOldEnough", "WHERE age = 42 ORDER BY name"); assertEquals("isOldEnough", idx.getName()); IndexKeyBuilder b; @@ -185,11 +188,11 @@ } @SuppressWarnings("rawtypes") - private IndexFunction<Person> index(String name, String query) - throws OrmException { + private IndexFunction<Person> index(String name, String query) throws OrmException { final QueryModel qm = new QueryModel(people, name, query); - return new IndexFunctionGen(new GeneratedClassLoader(Person.class - .getClassLoader()), qm, Person.class).create(); + return new IndexFunctionGen( + new GeneratedClassLoader(Person.class.getClassLoader()), qm, Person.class) + .create(); } private static void assertEqualToBuilderResult(byte[] exp, IndexKeyBuilder ic) { @@ -205,7 +208,8 @@ return dst.toString(); } - private static final char[] hexchar = - {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // - 'a', 'b', 'c', 'd', 'e', 'f'}; + private static final char[] hexchar = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // + 'a', 'b', 'c', 'd', 'e', 'f' + }; }
diff --git a/src/test/java/com/google/gwtorm/nosql/IndexKeyBuilderTest.java b/src/test/java/com/google/gwtorm/nosql/IndexKeyBuilderTest.java index e08059f..804802a 100644 --- a/src/test/java/com/google/gwtorm/nosql/IndexKeyBuilderTest.java +++ b/src/test/java/com/google/gwtorm/nosql/IndexKeyBuilderTest.java
@@ -18,7 +18,7 @@ import org.junit.Test; -public class IndexKeyBuilderTest { +public class IndexKeyBuilderTest { @Test public void testInt() { @@ -85,7 +85,8 @@ return dst.toString(); } - private static final char[] hexchar = - {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // - 'a', 'b', 'c', 'd', 'e', 'f'}; + private static final char[] hexchar = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // + 'a', 'b', 'c', 'd', 'e', 'f' + }; }
diff --git a/src/test/java/com/google/gwtorm/nosql/NoSqlPhoneBookTest.java b/src/test/java/com/google/gwtorm/nosql/NoSqlPhoneBookTest.java index a89627c..cfd7293 100644 --- a/src/test/java/com/google/gwtorm/nosql/NoSqlPhoneBookTest.java +++ b/src/test/java/com/google/gwtorm/nosql/NoSqlPhoneBookTest.java
@@ -28,16 +28,14 @@ import com.google.gwtorm.server.Access; import com.google.gwtorm.server.OrmConcurrencyException; import com.google.gwtorm.server.OrmException; - +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class NoSqlPhoneBookTest { +public class NoSqlPhoneBookTest { protected MemoryDatabase<PhoneBookDb> db; private List<PhoneBookDb> openSchemas; @@ -166,8 +164,7 @@ final Person p1 = new Person(new Person.Key("Bob"), 18); sp.insert(Collections.singleton(p1)); - final List<Person> list = - sp.get(Collections.singleton(sp.primaryKey(p1))).toList(); + final List<Person> list = sp.get(Collections.singleton(sp.primaryKey(p1))).toList(); assertNotNull(list); assertEquals(1, list.size()); @@ -237,8 +234,7 @@ final Person bob1 = new Person(new Person.Key("Bob"), 18); schema.people().insert(Collections.singleton(bob1)); - final Person bob2 = - schema.people().get(new Person.Key(bob1.name())); + final Person bob2 = schema.people().get(new Person.Key(bob1.name())); assertNotNull(bob2); assertNotSame(bob1, bob2); assertEquals(bob1.name(), bob2.name()); @@ -267,19 +263,16 @@ final Person bob = new Person(new Person.Key("Bob"), 18); schema.people().insert(Collections.singleton(bob)); - assertEquals(bob.isRegistered(), schema.people().all().toList().get(0) - .isRegistered()); + assertEquals(bob.isRegistered(), schema.people().all().toList().get(0).isRegistered()); bob.register(); schema.people().update(Collections.singleton(bob)); - assertEquals(bob.isRegistered(), schema.people().all().toList().get(0) - .isRegistered()); + assertEquals(bob.isRegistered(), schema.people().all().toList().get(0).isRegistered()); bob.unregister(); schema.people().update(Collections.singleton(bob)); - assertEquals(bob.isRegistered(), schema.people().all().toList().get(0) - .isRegistered()); + assertEquals(bob.isRegistered(), schema.people().all().toList().get(0).isRegistered()); } }
diff --git a/src/test/java/com/google/gwtorm/protobuf/ProtobufEncoderTest.java b/src/test/java/com/google/gwtorm/protobuf/ProtobufEncoderTest.java index 78f1938..15e1aea 100644 --- a/src/test/java/com/google/gwtorm/protobuf/ProtobufEncoderTest.java +++ b/src/test/java/com/google/gwtorm/protobuf/ProtobufEncoderTest.java
@@ -26,9 +26,6 @@ import com.google.gwtorm.data.Person; import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; - -import org.junit.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -38,19 +35,32 @@ import java.util.List; import java.util.SortedSet; import java.util.TreeSet; +import org.junit.Test; public class ProtobufEncoderTest { - private static final byte[] testingBin = new byte[] { - // - // name - 0x0a, 0x09, - // name.name - 0x0a, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, // - // age - 0x10, (byte) 75, // - // registered (true) - 0x18, 0x01 // - // + private static final byte[] testingBin = + new byte[] { + // + // name + 0x0a, + 0x09, + // name.name + 0x0a, + 0x07, + 0x74, + 0x65, + 0x73, + 0x74, + 0x69, + 0x6e, + 0x67, // + // age + 0x10, + (byte) 75, // + // registered (true) + 0x18, + 0x01 // + // }; @SuppressWarnings("cast") @@ -72,8 +82,7 @@ @Test public void testAddress() { - final ProtobufCodec<Address> e = - CodecFactory.encoder(Address.class); + final ProtobufCodec<Address> e = CodecFactory.encoder(Address.class); Address a = e.decode(new byte[0]); assertNotNull(a); assertNull(a.location()); @@ -122,8 +131,7 @@ } @Test - public void testEncodeNonArrayByteBuffer() - throws UnsupportedEncodingException { + public void testEncodeNonArrayByteBuffer() throws UnsupportedEncodingException { ProtobufCodec<Person> e = CodecFactory.encoder(Person.class); Person p = new Person(new Person.Key("testing"), 75); @@ -159,11 +167,24 @@ StringList other = e.decode(act); assertNotNull(other.list); assertEquals(list.list, other.list); - assertEquals(asString(new byte[] { // - // - 0x12, 0x03, 'm', 'o', 'e', // - 0x12, 0x05, 'l', 'a', 'r', 'r', 'y' // - }), asString(act)); + assertEquals( + asString( + new byte[] { // + // + 0x12, + 0x03, + 'm', + 'o', + 'e', // + 0x12, + 0x05, + 'l', + 'a', + 'r', + 'r', + 'y' // + }), + asString(act)); } @Test @@ -179,11 +200,24 @@ StringSet other = e.decode(act); assertNotNull(other.list); assertEquals(list.list, other.list); - assertEquals(asString(new byte[] { // - // - 0x0a, 0x05, 'l', 'a', 'r', 'r', 'y', // - 0x0a, 0x03, 'm', 'o', 'e' // - }), asString(act)); + assertEquals( + asString( + new byte[] { // + // + 0x0a, + 0x05, + 'l', + 'a', + 'r', + 'r', + 'y', // + 0x0a, + 0x03, + 'm', + 'o', + 'e' // + }), + asString(act)); } @Test @@ -235,7 +269,7 @@ } @Test - public void testEncodeToStream()throws IOException { + public void testEncodeToStream() throws IOException { ProtobufCodec<ThingWithEnum> e = CodecFactory.encoder(ThingWithEnum.class); ThingWithEnum thing = new ThingWithEnum(); @@ -255,8 +289,7 @@ assertSame(thing.type, other.type); } - private static String asString(byte[] bin) - throws UnsupportedEncodingException { + private static String asString(byte[] bin) throws UnsupportedEncodingException { return new String(bin, "ISO-8859-1"); } @@ -275,8 +308,7 @@ SortedSet<String> list; } - static class Item { - } + static class Item {} static class ItemCodec extends ProtobufCodec<Item> { @Override @@ -308,7 +340,8 @@ static class ThingWithEnum { static enum Type { - A, B; + A, + B; } @Column(id = 1)
diff --git a/src/test/java/com/google/gwtorm/schema/QueryModelTest.java b/src/test/java/com/google/gwtorm/schema/QueryModelTest.java index 13e914c..72c9441 100644 --- a/src/test/java/com/google/gwtorm/schema/QueryModelTest.java +++ b/src/test/java/com/google/gwtorm/schema/QueryModelTest.java
@@ -22,12 +22,10 @@ import com.google.gwtorm.schema.java.JavaSchemaModel; import com.google.gwtorm.schema.sql.DialectH2; import com.google.gwtorm.server.OrmException; - +import java.util.List; import org.junit.Before; import org.junit.Test; -import java.util.List; - public class QueryModelTest { private RelationModel people;
diff --git a/src/test/java/com/google/gwtorm/schema/QueryParserTest.java b/src/test/java/com/google/gwtorm/schema/QueryParserTest.java index ad90e0a..471de76 100644 --- a/src/test/java/com/google/gwtorm/schema/QueryParserTest.java +++ b/src/test/java/com/google/gwtorm/schema/QueryParserTest.java
@@ -20,13 +20,11 @@ import static org.junit.Assert.assertTrue; import com.google.gwtorm.server.OrmException; - -import org.antlr.runtime.tree.Tree; -import org.junit.Test; - import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; +import org.antlr.runtime.tree.Tree; +import org.junit.Test; public class QueryParserTest { private final class DummyColumn extends ColumnModel { @@ -65,30 +63,31 @@ } protected Tree parse(final String str) throws QueryParseException { - final RelationModel dummy = new RelationModel() { - { - final Collection<ColumnModel> c = new ArrayList<>(); - try { - c.add(new DummyColumn(1, "name")); - c.add(new DummyColumn(2, "a")); - c.add(new DummyColumn(3, "b")); - c.add(new DummyColumn(4, "c")); - initColumns(c); - } catch (OrmException e) { - throw new RuntimeException("init columns failure", e); - } - } + final RelationModel dummy = + new RelationModel() { + { + final Collection<ColumnModel> c = new ArrayList<>(); + try { + c.add(new DummyColumn(1, "name")); + c.add(new DummyColumn(2, "a")); + c.add(new DummyColumn(3, "b")); + c.add(new DummyColumn(4, "c")); + initColumns(c); + } catch (OrmException e) { + throw new RuntimeException("init columns failure", e); + } + } - @Override - public String getAccessInterfaceName() { - return getClass().getName(); - } + @Override + public String getAccessInterfaceName() { + return getClass().getName(); + } - @Override - public String getEntityTypeClassName() { - return getClass().getName(); - } - }; + @Override + public String getEntityTypeClassName() { + return getClass().getName(); + } + }; return QueryParser.parse(dummy, str); }
diff --git a/src/test/java/com/google/gwtorm/schema/java/DeclaredFieldsOrderTest.java b/src/test/java/com/google/gwtorm/schema/java/DeclaredFieldsOrderTest.java index c38399f..c32870b 100644 --- a/src/test/java/com/google/gwtorm/schema/java/DeclaredFieldsOrderTest.java +++ b/src/test/java/com/google/gwtorm/schema/java/DeclaredFieldsOrderTest.java
@@ -14,16 +14,14 @@ package com.google.gwtorm.schema.java; -import static com.google.gwtorm.schema.java.JavaColumnModel.sort; import static com.google.common.collect.Collections2.permutations; +import static com.google.gwtorm.schema.java.JavaColumnModel.sort; import static org.junit.Assert.assertEquals; import com.google.gwtorm.client.Column; - import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; - import org.junit.Test; public class DeclaredFieldsOrderTest { @@ -31,15 +29,19 @@ private static class C { @Column(id = 1) private String c; + @Column(id = 2) private String b; + @Column(id = 3) private String a; @SuppressWarnings("unused") private String d; + @SuppressWarnings("unused") private String e; + @SuppressWarnings("unused") private String f; }
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectDB2Test.java b/src/test/java/com/google/gwtorm/schema/sql/DialectDB2Test.java index 82e2330..13566bf 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectDB2Test.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectDB2Test.java
@@ -28,19 +28,18 @@ import com.google.gwtorm.jdbc.JdbcSchema; import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collections; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectDB2Test extends SqlDialectTest { - private final static String DB2_DRIVER = "com.ibm.db2.jcc.DB2Driver"; + private static final String DB2_DRIVER = "com.ibm.db2.jcc.DB2Driver"; + @Before public void setUp() throws Exception { try { @@ -53,8 +52,7 @@ final String user = "gwtorm"; // user final String pass = "gwtorm"; // pwd - db = DriverManager.getConnection("jdbc:db2://127.0.0.1:50001/" - + database, user, pass); + db = DriverManager.getConnection("jdbc:db2://127.0.0.1:50001/" + database, user, pass); executor = new JdbcExecutor(db); dialect = new DialectDB2().refine(db); @@ -63,10 +61,8 @@ p.setProperty("url", db.getMetaData().getURL()); p.setProperty("user", user); p.setProperty("password", pass); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } @After @@ -196,8 +192,7 @@ final Person bob = new Person(pk, nextAddressId); p.people().insert(Collections.singleton(bob)); - final Address addr = - new Address(new Address.Key(pk, "home"), "some place"); + final Address addr = new Address(new Address.Key(pk, "home"), "some place"); p.addresses().insert(Collections.singleton(addr)); } finally { p.close();
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectDerbyTest.java b/src/test/java/com/google/gwtorm/schema/sql/DialectDerbyTest.java index bbf5c94..9275014 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectDerbyTest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectDerbyTest.java
@@ -28,11 +28,6 @@ import com.google.gwtorm.jdbc.JdbcSchema; import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -42,6 +37,9 @@ import java.util.List; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectDerbyTest extends SqlDialectTest { @@ -57,10 +55,8 @@ p.setProperty("driver", org.apache.derby.jdbc.EmbeddedDriver.class.getName()); p.setProperty("url", db.getMetaData().getURL()); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } @After @@ -175,8 +171,7 @@ final Person bob = new Person(pk, p.nextAddressId()); p.people().insert(Collections.singleton(bob)); - final Address addr = - new Address(new Address.Key(pk, "home"), "some place"); + final Address addr = new Address(new Address.Key(pk, "home"), "some place"); p.addresses().insert(Collections.singleton(addr)); } finally { p.close(); @@ -193,11 +188,11 @@ * for more information about the restriction of the RENAME COLUMN command. */ String sqlCatalog = - "select c.constraintname, ch.checkdefinition" - + " from sys.sysconstraints c, sys.systables t, sys.syschecks ch" - + " WHERE c.tableid = t.tableid" - + " and t.tablename = ?" - + " and c.constraintid = ch.constraintid"; + "select c.constraintname, ch.checkdefinition" + + " from sys.sysconstraints c, sys.systables t, sys.syschecks ch" + + " WHERE c.tableid = t.tableid" + + " and t.tablename = ?" + + " and c.constraintid = ch.constraintid"; PreparedStatement ps = db.prepareStatement(sqlCatalog); String tableName = "PEOPLE"; ps.setString(1, tableName); @@ -210,20 +205,19 @@ constraintNames.add(rs.getString(1)); checkDefs.add(rs.getString(2).replace("registered", "is_registered")); break; - } + } } rs.close(); ps.close(); if (constraintNames.isEmpty()) { fail("Constraint not found"); } - for (String c: constraintNames) { + for (String c : constraintNames) { execute("alter table " + tableName + " drop check " + c); } - ((JdbcSchema) p2).renameField(executor, "people", "registered", - "isRegistered"); - for (String cd: checkDefs) { - execute("alter table " + tableName + " add check "+ cd); + ((JdbcSchema) p2).renameField(executor, "people", "registered", "isRegistered"); + for (String cd : checkDefs) { + execute("alter table " + tableName + " add check " + cd); } } catch (OrmException e) { fail(e.getMessage());
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectH2Test.java b/src/test/java/com/google/gwtorm/schema/sql/DialectH2Test.java index a94f641..6d927f2 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectH2Test.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectH2Test.java
@@ -27,16 +27,14 @@ import com.google.gwtorm.jdbc.JdbcSchema; import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collections; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectH2Test extends SqlDialectTest { @Before @@ -49,10 +47,8 @@ final Properties p = new Properties(); p.setProperty("driver", org.h2.Driver.class.getName()); p.setProperty("url", db.getMetaData().getURL()); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } @After @@ -171,8 +167,7 @@ final Person bob = new Person(pk, p.nextAddressId()); p.people().insert(Collections.singleton(bob)); - final Address addr = - new Address(new Address.Key(pk, "home"), "some place"); + final Address addr = new Address(new Address.Key(pk, "home"), "some place"); p.addresses().insert(Collections.singleton(addr)); } finally { p.close(); @@ -180,8 +175,7 @@ final PhoneBookDb2 p2 = phoneBook2.open(); try { - ((JdbcSchema) p2).renameField(executor, "people", "registered", - "isRegistered"); + ((JdbcSchema) p2).renameField(executor, "people", "registered", "isRegistered"); } finally { p2.close(); }
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectHANATest.java b/src/test/java/com/google/gwtorm/schema/sql/DialectHANATest.java index 83f34f4..0f3836b 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectHANATest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectHANATest.java
@@ -32,16 +32,14 @@ import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collections; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectHANATest extends SqlDialectTest { private static final String HANA_URL_KEY = "hana.url"; @@ -204,8 +202,7 @@ PhoneBookDb2 p2 = phoneBook2.open(); try { - ((JdbcSchema) p2).renameField(executor, "people", "registered", - "isRegistered"); + ((JdbcSchema) p2).renameField(executor, "people", "registered", "isRegistered"); } finally { p2.close(); }
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectMariaDBTest.java b/src/test/java/com/google/gwtorm/schema/sql/DialectMariaDBTest.java index c73b1f5..b00ee5d 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectMariaDBTest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectMariaDBTest.java
@@ -21,11 +21,9 @@ import com.google.gwtorm.jdbc.Database; import com.google.gwtorm.jdbc.JdbcExecutor; import com.google.gwtorm.jdbc.SimpleDataSource; - -import org.junit.Before; - import java.sql.DriverManager; import java.util.Properties; +import org.junit.Before; public class DialectMariaDBTest extends DialectMySQLTest { @Before @@ -51,9 +49,7 @@ p.setProperty("url", db.getMetaData().getURL()); p.setProperty("user", user); p.setProperty("password", pass); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } }
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectMaxDBTest.java b/src/test/java/com/google/gwtorm/schema/sql/DialectMaxDBTest.java index 97937b2..5149707 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectMaxDBTest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectMaxDBTest.java
@@ -32,16 +32,14 @@ import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collections; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectMaxDBTest extends SqlDialectTest { private static final String MAXDB_URL_KEY = "maxdb.url"; @@ -70,10 +68,8 @@ p.setProperty("url", db.getMetaData().getURL()); p.setProperty("user", user); p.setProperty("password", pass); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } private void drop(String drop) { @@ -198,8 +194,7 @@ final Person bob = new Person(pk, p.nextAddressId()); p.people().insert(asList(bob)); - final Address addr = - new Address(new Address.Key(pk, "home"), "some place"); + final Address addr = new Address(new Address.Key(pk, "home"), "some place"); p.addresses().insert(asList(addr)); } finally { p.close(); @@ -207,8 +202,7 @@ final PhoneBookDb2 p2 = phoneBook2.open(); try { - ((JdbcSchema) p2).renameField(executor, "people", "registered", - "isRegistered"); + ((JdbcSchema) p2).renameField(executor, "people", "registered", "isRegistered"); } finally { p2.close(); } @@ -271,8 +265,8 @@ Person joe = new Person(joePk, p.nextAddressId()); joe.setAge(40); try { - p.people().insert(asList(joe)); - fail(); + p.people().insert(asList(joe)); + fail(); } catch (OrmDuplicateKeyException duprec) { fail(); } catch (OrmException noDuprec) {
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectMySQLTest.java b/src/test/java/com/google/gwtorm/schema/sql/DialectMySQLTest.java index 032bb33..8789122 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectMySQLTest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectMySQLTest.java
@@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. - package com.google.gwtorm.schema.sql; import static org.junit.Assert.assertEquals; @@ -29,16 +28,14 @@ import com.google.gwtorm.jdbc.JdbcSchema; import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collections; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectMySQLTest extends SqlDialectTest { @Before @@ -64,10 +61,8 @@ p.setProperty("url", db.getMetaData().getURL()); p.setProperty("user", user); p.setProperty("password", pass); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } @After @@ -190,8 +185,7 @@ final Person bob = new Person(pk, p.nextAddressId()); p.people().insert(Collections.singleton(bob)); - final Address addr = - new Address(new Address.Key(pk, "home"), "some place"); + final Address addr = new Address(new Address.Key(pk, "home"), "some place"); p.addresses().insert(Collections.singleton(addr)); } finally { p.close(); @@ -199,8 +193,7 @@ final PhoneBookDb2 p2 = phoneBook2.open(); try { - ((JdbcSchema) p2).renameField(executor, "people", "registered", - "isRegistered"); + ((JdbcSchema) p2).renameField(executor, "people", "registered", "isRegistered"); } finally { p2.close(); }
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectOracleSQLTest.java b/src/test/java/com/google/gwtorm/schema/sql/DialectOracleSQLTest.java index 8bb00ce..53369d8 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectOracleSQLTest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectOracleSQLTest.java
@@ -28,19 +28,17 @@ import com.google.gwtorm.jdbc.JdbcSchema; import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collections; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectOracleSQLTest extends SqlDialectTest { - private final static String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver"; + private static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver"; @Before public void setUp() throws Exception { @@ -54,8 +52,7 @@ final String user = "gwtorm"; // Oracle schema=user name=database final String pass = "gwtorm"; - db = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:" - + sid, user, pass); + db = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:" + sid, user, pass); executor = new JdbcExecutor(db); dialect = new DialectOracle().refine(db); @@ -64,10 +61,8 @@ p.setProperty("url", db.getMetaData().getURL()); p.setProperty("user", user); p.setProperty("password", pass); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } @After @@ -192,8 +187,7 @@ final Person bob = new Person(pk, p.nextAddressId()); p.people().insert(Collections.singleton(bob)); - final Address addr = - new Address(new Address.Key(pk, "home"), "some place"); + final Address addr = new Address(new Address.Key(pk, "home"), "some place"); p.addresses().insert(Collections.singleton(addr)); } finally { p.close(); @@ -201,8 +195,7 @@ final PhoneBookDb2 p2 = phoneBook2.open(); try { - ((JdbcSchema) p2).renameField(executor, "people", "registered", - "isRegistered"); + ((JdbcSchema) p2).renameField(executor, "people", "registered", "isRegistered"); } finally { p2.close(); }
diff --git a/src/test/java/com/google/gwtorm/schema/sql/DialectPostgreSQLTest.java b/src/test/java/com/google/gwtorm/schema/sql/DialectPostgreSQLTest.java index cbdc050..fb256c5 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/DialectPostgreSQLTest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/DialectPostgreSQLTest.java
@@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. - package com.google.gwtorm.schema.sql; import static org.junit.Assert.assertEquals; @@ -29,16 +28,14 @@ import com.google.gwtorm.jdbc.JdbcSchema; import com.google.gwtorm.jdbc.SimpleDataSource; import com.google.gwtorm.server.OrmException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.DriverManager; import java.sql.SQLException; import java.util.Collections; import java.util.Properties; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DialectPostgreSQLTest extends SqlDialectTest { @Before @@ -62,10 +59,8 @@ p.setProperty("url", db.getMetaData().getURL()); p.setProperty("user", user); p.setProperty("password", pass); - phoneBook = - new Database<>(new SimpleDataSource(p), PhoneBookDb.class); - phoneBook2 = - new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); + phoneBook = new Database<>(new SimpleDataSource(p), PhoneBookDb.class); + phoneBook2 = new Database<>(new SimpleDataSource(p), PhoneBookDb2.class); } @After @@ -189,8 +184,7 @@ final Person bob = new Person(pk, p.nextAddressId()); p.people().insert(Collections.singleton(bob)); - final Address addr = - new Address(new Address.Key(pk, "home"), "some place"); + final Address addr = new Address(new Address.Key(pk, "home"), "some place"); p.addresses().insert(Collections.singleton(addr)); } finally { p.close(); @@ -198,8 +192,7 @@ final PhoneBookDb2 p2 = phoneBook2.open(); try { - ((JdbcSchema) p2).renameField(executor, "people", "registered", - "isRegistered"); + ((JdbcSchema) p2).renameField(executor, "people", "registered", "isRegistered"); } finally { p2.close(); }
diff --git a/src/test/java/com/google/gwtorm/schema/sql/SqlDialectTest.java b/src/test/java/com/google/gwtorm/schema/sql/SqlDialectTest.java index 422ba0a..6306a66 100644 --- a/src/test/java/com/google/gwtorm/schema/sql/SqlDialectTest.java +++ b/src/test/java/com/google/gwtorm/schema/sql/SqlDialectTest.java
@@ -28,14 +28,12 @@ import com.google.gwtorm.server.OrmConcurrencyException; import com.google.gwtorm.server.OrmDuplicateKeyException; import com.google.gwtorm.server.OrmException; - -import org.junit.Test; - import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.junit.Test; public abstract class SqlDialectTest { protected JdbcExecutor executor; @@ -84,8 +82,7 @@ } @Test - public void testThrowsOrmDuplicateKeyExceptionWhenTryingToInsertDuplicates() - throws Exception { + public void testThrowsOrmDuplicateKeyExceptionWhenTryingToInsertDuplicates() throws Exception { PhoneBookDb p = phoneBook.open(); try { p.updateSchema(executor); @@ -126,8 +123,7 @@ } @Test - public void testInsertExistingRowThrowsOrmDuplicateKeyException() - throws Exception { + public void testInsertExistingRowThrowsOrmDuplicateKeyException() throws Exception { PhoneBookDb p = phoneBook.open(); try { p.updateSchema(executor); @@ -147,8 +143,7 @@ } @Test - public void testInsertExistingRowInTransactionThrowsOrmDuplicateKeyException() - throws Exception { + public void testInsertExistingRowInTransactionThrowsOrmDuplicateKeyException() throws Exception { PhoneBookDb p = phoneBook.open(); try { p.updateSchema(executor); @@ -175,8 +170,7 @@ } @Test - public void testUpdateNonexistentRowThrowsOrmConcurrencyException() - throws Exception { + public void testUpdateNonexistentRowThrowsOrmConcurrencyException() throws Exception { PhoneBookDb p = phoneBook.open(); try { p.updateSchema(executor); @@ -222,8 +216,7 @@ } @Test - public void testDeleteNonexistentRowThrowsOrmConcurrencyException() - throws Exception { + public void testDeleteNonexistentRowThrowsOrmConcurrencyException() throws Exception { PhoneBookDb p = phoneBook.open(); try { p.updateSchema(executor);
diff --git a/src/test/java/com/google/gwtorm/server/PhoneBookDbTestCase.java b/src/test/java/com/google/gwtorm/server/PhoneBookDbTestCase.java index 4f99f61..7d151e9 100644 --- a/src/test/java/com/google/gwtorm/server/PhoneBookDbTestCase.java +++ b/src/test/java/com/google/gwtorm/server/PhoneBookDbTestCase.java
@@ -29,11 +29,6 @@ import com.google.gwtorm.jdbc.JdbcExecutor; import com.google.gwtorm.jdbc.JdbcSchema; import com.google.gwtorm.jdbc.SimpleDataSource; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -41,6 +36,9 @@ import java.util.Collections; import java.util.List; import java.util.Properties; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class PhoneBookDbTestCase { private static int runCount; @@ -206,8 +204,7 @@ final Person p1 = new Person(new Person.Key("Bob"), 18); sp.insert(Collections.singleton(p1)); - final List<Person> list = - sp.get(Collections.singleton(sp.primaryKey(p1))).toList(); + final List<Person> list = sp.get(Collections.singleton(sp.primaryKey(p1))).toList(); assertNotNull(list); assertEquals(1, list.size()); @@ -304,8 +301,7 @@ final Person bob1 = new Person(new Person.Key("Bob"), 18); schema.people().insert(Collections.singleton(bob1)); - final Person bob2 = - schema.people().get(new Person.Key(bob1.name())); + final Person bob2 = schema.people().get(new Person.Key(bob1.name())); assertNotNull(bob2); assertNotSame(bob1, bob2); assertEquals(bob1.name(), bob2.name()); @@ -337,8 +333,7 @@ all.add(new Person(new Person.Key("Zak"), 33)); schema.people().insert(all); - final List<Person> r = - schema.people().olderThanDescByName(18).toList(); + final List<Person> r = schema.people().olderThanDescByName(18).toList(); assertEquals(2, r.size()); assertEquals(all.get(2).name(), r.get(0).name()); assertEquals(all.get(1).name(), r.get(1).name()); @@ -358,8 +353,7 @@ assertEquals("N", rs.getString(1)); assertFalse(rs.next()); rs.close(); - assertEquals(bob.isRegistered(), schema.people().all().toList().get(0) - .isRegistered()); + assertEquals(bob.isRegistered(), schema.people().all().toList().get(0).isRegistered()); bob.register(); schema.people().update(Collections.singleton(bob)); @@ -368,8 +362,7 @@ assertEquals("Y", rs.getString(1)); assertFalse(rs.next()); rs.close(); - assertEquals(bob.isRegistered(), schema.people().all().toList().get(0) - .isRegistered()); + assertEquals(bob.isRegistered(), schema.people().all().toList().get(0).isRegistered()); bob.unregister(); schema.people().update(Collections.singleton(bob)); @@ -378,8 +371,7 @@ assertEquals("N", rs.getString(1)); assertFalse(rs.next()); rs.close(); - assertEquals(bob.isRegistered(), schema.people().all().toList().get(0) - .isRegistered()); + assertEquals(bob.isRegistered(), schema.people().all().toList().get(0).isRegistered()); st.close(); }
diff --git a/src/test/java/com/google/gwtorm/server/PrintCreateTablesTestCase.java b/src/test/java/com/google/gwtorm/server/PrintCreateTablesTestCase.java index 66a13d2..2b79b1b 100644 --- a/src/test/java/com/google/gwtorm/server/PrintCreateTablesTestCase.java +++ b/src/test/java/com/google/gwtorm/server/PrintCreateTablesTestCase.java
@@ -17,7 +17,6 @@ import com.google.gwtorm.data.PhoneBookDb; import com.google.gwtorm.schema.java.JavaSchemaModel; import com.google.gwtorm.schema.sql.DialectH2; - import org.junit.Test; public class PrintCreateTablesTestCase {