Search in sources :

Example 1 with JavaWriter

use of com.squareup.javawriter.JavaWriter in project realm-java by realm.

the class RealmProxyClassGenerator method emitPrimitiveType.

/**
     * Primitives and boxed types
     */
private void emitPrimitiveType(JavaWriter writer, final VariableElement field, final String fieldName, String fieldTypeCanonicalName) throws IOException {
    final String realmType = Constants.JAVA_TO_REALM_TYPES.get(fieldTypeCanonicalName);
    // Getter
    writer.emitAnnotation("SuppressWarnings", "\"cast\"").beginMethod(fieldTypeCanonicalName, metadata.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC)).emitStatement("proxyState.getRealm$realm().checkIfValid()");
    // For String and bytes[], null value will be returned by JNI code. Try to save one JNI call here.
    if (metadata.isNullable(field) && !Utils.isString(field) && !Utils.isByteArray(field)) {
        writer.beginControlFlow("if (proxyState.getRow$realm().isNull(%s))", fieldIndexVariableReference(field)).emitStatement("return null").endControlFlow();
    }
    // For Boxed types, this should be the corresponding primitive types. Others remain the same.
    String castingBackType;
    if (Utils.isBoxedType(fieldTypeCanonicalName)) {
        Types typeUtils = processingEnvironment.getTypeUtils();
        castingBackType = typeUtils.unboxedType(field.asType()).toString();
    } else {
        castingBackType = fieldTypeCanonicalName;
    }
    writer.emitStatement("return (%s) proxyState.getRow$realm().get%s(%s)", castingBackType, realmType, fieldIndexVariableReference(field));
    writer.endMethod().emitEmptyLine();
    // Setter
    writer.beginMethod("void", metadata.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value");
    emitCodeForUnderConstruction(writer, metadata.isPrimaryKey(field), new CodeEmitter() {

        @Override
        public void emit(JavaWriter writer) throws IOException {
            // set value as default value
            writer.emitStatement("final Row row = proxyState.getRow$realm()");
            if (metadata.isNullable(field)) {
                writer.beginControlFlow("if (value == null)").emitStatement("row.getTable().setNull(%s, row.getIndex(), true)", fieldIndexVariableReference(field)).emitStatement("return").endControlFlow();
            } else if (!metadata.isNullable(field) && !Utils.isPrimitiveType(field)) {
                writer.beginControlFlow("if (value == null)").emitStatement(Constants.STATEMENT_EXCEPTION_ILLEGAL_NULL_VALUE, fieldName).endControlFlow();
            }
            writer.emitStatement("row.getTable().set%s(%s, row.getIndex(), value, true)", realmType, fieldIndexVariableReference(field));
            writer.emitStatement("return");
        }
    });
    writer.emitStatement("proxyState.getRealm$realm().checkIfValid()");
    // Compared with getter, null value won't trigger more native calls in setter which is relatively cheaper.
    if (metadata.isPrimaryKey(field)) {
        // Primary key is not allowed to be changed after object created.
        writer.emitStatement(Constants.STATEMENT_EXCEPTION_PRIMARY_KEY_CANNOT_BE_CHANGED, fieldName);
    } else {
        if (metadata.isNullable(field)) {
            writer.beginControlFlow("if (value == null)").emitStatement("proxyState.getRow$realm().setNull(%s)", fieldIndexVariableReference(field)).emitStatement("return").endControlFlow();
        } else if (!metadata.isNullable(field) && !Utils.isPrimitiveType(field)) {
            // Same reason, throw IAE earlier.
            writer.beginControlFlow("if (value == null)").emitStatement(Constants.STATEMENT_EXCEPTION_ILLEGAL_NULL_VALUE, fieldName).endControlFlow();
        }
        writer.emitStatement("proxyState.getRow$realm().set%s(%s, value)", realmType, fieldIndexVariableReference(field));
    }
    writer.endMethod();
}
Also used : Types(javax.lang.model.util.Types) JavaWriter(com.squareup.javawriter.JavaWriter) IOException(java.io.IOException)

Example 2 with JavaWriter

use of com.squareup.javawriter.JavaWriter in project realm-java by realm.

the class RealmProxyInterfaceGenerator method generate.

public void generate() throws IOException {
    String qualifiedGeneratedInterfaceName = String.format("%s.%s", Constants.REALM_PACKAGE_NAME, Utils.getProxyInterfaceName(className));
    JavaFileObject sourceFile = processingEnvironment.getFiler().createSourceFile(qualifiedGeneratedInterfaceName);
    JavaWriter writer = new JavaWriter(new BufferedWriter(sourceFile.openWriter()));
    writer.setIndent(Constants.INDENT);
    writer.emitPackage(Constants.REALM_PACKAGE_NAME).emitEmptyLine().beginType(qualifiedGeneratedInterfaceName, "interface", EnumSet.of(Modifier.PUBLIC));
    for (VariableElement field : metaData.getFields()) {
        // The field is neither static nor ignored
        if (!field.getModifiers().contains(Modifier.STATIC) && field.getAnnotation(Ignore.class) == null) {
            String fieldName = field.getSimpleName().toString();
            String fieldTypeCanonicalName = field.asType().toString();
            writer.beginMethod(fieldTypeCanonicalName, metaData.getInternalGetter(fieldName), EnumSet.of(Modifier.PUBLIC)).endMethod().beginMethod("void", metaData.getInternalSetter(fieldName), EnumSet.of(Modifier.PUBLIC), fieldTypeCanonicalName, "value").endMethod();
        }
    }
    // backlinks are final and have only a getter.
    for (Backlink backlink : metaData.getBacklinkFields()) {
        writer.beginMethod(backlink.getTargetFieldType(), metaData.getInternalGetter(backlink.getTargetField()), EnumSet.of(Modifier.PUBLIC)).endMethod();
    }
    writer.endType();
    writer.close();
}
Also used : JavaFileObject(javax.tools.JavaFileObject) JavaWriter(com.squareup.javawriter.JavaWriter) VariableElement(javax.lang.model.element.VariableElement) BufferedWriter(java.io.BufferedWriter)

Example 3 with JavaWriter

use of com.squareup.javawriter.JavaWriter in project realm-java by realm.

the class TestRealmObjectFileObject method getSingleFieldInstance.

// Helper function to create a Realm object java file with a single field.
public static TestRealmObjectFileObject getSingleFieldInstance(String className, String annotationToField, String fieldType, String fieldName) throws IOException {
    String FieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
    StringWriter stringWriter = new StringWriter();
    JavaWriter writer = new JavaWriter(stringWriter);
    // Package name
    writer.emitPackage("some.test");
    // Import Realm classes
    writer.emitImports("io.realm.*");
    writer.emitImports("io.realm.annotations.*");
    // Begin the class definition
    writer.beginType(// full qualified name of the item to generate
    className, // the type of the item
    "class", // modifiers to apply
    EnumSet.of(Modifier.PUBLIC), // class to extend
    "RealmObject").emitEmptyLine();
    // Declaration of field
    writer.emitAnnotation(annotationToField);
    writer.emitField(fieldType, fieldName, EnumSet.of(Modifier.PRIVATE));
    // Getter
    writer.beginMethod(// Return type
    fieldType, // Method name
    "get" + FieldName, // Modifiers
    EnumSet.of(Modifier.PUBLIC));
    writer.emitStatement("return realmGet$" + fieldName + "()");
    writer.endMethod();
    // Setter
    writer.beginMethod(// Return type
    "void", // Method name
    "set" + FieldName, EnumSet.of(Modifier.PUBLIC), fieldType, // Modifiers
    fieldName);
    writer.emitStatement("realmSet$" + fieldName + "(" + fieldName + ")");
    writer.endMethod();
    // Realm Getter
    writer.beginMethod(// Return type
    fieldType, // Method name
    "realmGet$" + fieldName, // Modifiers
    EnumSet.of(Modifier.PUBLIC));
    writer.emitStatement("return " + fieldName);
    writer.endMethod();
    // Realm Setter
    writer.beginMethod(// Return type
    "void", // Method name
    "realmSet$" + fieldName, EnumSet.of(Modifier.PUBLIC), fieldType, // Modifiers
    fieldName);
    writer.emitStatement("this." + fieldName + "=" + fieldName);
    writer.endMethod();
    writer.endType();
    return new TestRealmObjectFileObject(className, stringWriter);
}
Also used : StringWriter(java.io.StringWriter) JavaWriter(com.squareup.javawriter.JavaWriter)

Example 4 with JavaWriter

use of com.squareup.javawriter.JavaWriter in project realm-java by realm.

the class DefaultModuleGenerator method generate.

public void generate() throws IOException {
    String qualifiedGeneratedClassName = String.format("%s.%s", Constants.REALM_PACKAGE_NAME, Constants.DEFAULT_MODULE_CLASS_NAME);
    JavaFileObject sourceFile = env.getFiler().createSourceFile(qualifiedGeneratedClassName);
    JavaWriter writer = new JavaWriter(new BufferedWriter(sourceFile.openWriter()));
    writer.setIndent("    ");
    writer.emitPackage(Constants.REALM_PACKAGE_NAME);
    writer.emitEmptyLine();
    Map<String, Boolean> attributes = new HashMap<String, Boolean>();
    attributes.put("allClasses", Boolean.TRUE);
    writer.emitAnnotation(RealmModule.class, attributes);
    writer.beginType(// full qualified name of the item to generate
    qualifiedGeneratedClassName, // the type of the item
    "class", // modifiers to apply
    Collections.<Modifier>emptySet(), // class to extend
    null);
    writer.emitEmptyLine();
    writer.endType();
    writer.close();
}
Also used : JavaFileObject(javax.tools.JavaFileObject) HashMap(java.util.HashMap) JavaWriter(com.squareup.javawriter.JavaWriter) BufferedWriter(java.io.BufferedWriter)

Example 5 with JavaWriter

use of com.squareup.javawriter.JavaWriter in project realm-java by realm.

the class RealmProxyClassGenerator method generate.

public void generate() throws IOException, UnsupportedOperationException {
    JavaFileObject sourceFile = processingEnvironment.getFiler().createSourceFile(qualifiedGeneratedClassName);
    JavaWriter writer = new JavaWriter(new BufferedWriter(sourceFile.openWriter()));
    // Set source code indent
    writer.setIndent(Constants.INDENT);
    writer.emitPackage(Constants.REALM_PACKAGE_NAME).emitEmptyLine();
    ArrayList<String> imports = new ArrayList<String>();
    imports.add("android.annotation.TargetApi");
    imports.add("android.os.Build");
    imports.add("android.util.JsonReader");
    imports.add("android.util.JsonToken");
    imports.add("io.realm.RealmObjectSchema");
    imports.add("io.realm.RealmSchema");
    imports.add("io.realm.exceptions.RealmMigrationNeededException");
    imports.add("io.realm.internal.ColumnInfo");
    imports.add("io.realm.internal.RealmObjectProxy");
    imports.add("io.realm.internal.Row");
    imports.add("io.realm.internal.Table");
    imports.add("io.realm.internal.SharedRealm");
    imports.add("io.realm.internal.LinkView");
    imports.add("io.realm.internal.android.JsonUtils");
    imports.add("io.realm.log.RealmLog");
    imports.add("java.io.IOException");
    imports.add("java.util.ArrayList");
    imports.add("java.util.Collections");
    imports.add("java.util.List");
    imports.add("java.util.Iterator");
    imports.add("java.util.Date");
    imports.add("java.util.Map");
    imports.add("java.util.HashMap");
    imports.add("org.json.JSONObject");
    imports.add("org.json.JSONException");
    imports.add("org.json.JSONArray");
    writer.emitImports(imports).emitEmptyLine();
    // Begin the class definition
    writer.beginType(// full qualified name of the item to generate
    qualifiedGeneratedClassName, // the type of the item
    "class", // modifiers to apply
    EnumSet.of(Modifier.PUBLIC), // class to extend
    qualifiedClassName, // interfaces to implement
    "RealmObjectProxy", interfaceName).emitEmptyLine();
    emitColumnIndicesClass(writer);
    emitClassFields(writer);
    emitConstructor(writer);
    emitInjectContextMethod(writer);
    emitPersistedFieldAccessors(writer);
    emitBacklinkFieldAccessors(writer);
    emitCreateRealmObjectSchemaMethod(writer);
    emitInitTableMethod(writer);
    emitValidateTableMethod(writer);
    emitGetTableNameMethod(writer);
    emitGetFieldNamesMethod(writer);
    emitCreateOrUpdateUsingJsonObject(writer);
    emitCreateUsingJsonStream(writer);
    emitCopyOrUpdateMethod(writer);
    emitCopyMethod(writer);
    emitInsertMethod(writer);
    emitInsertListMethod(writer);
    emitInsertOrUpdateMethod(writer);
    emitInsertOrUpdateListMethod(writer);
    emitCreateDetachedCopyMethod(writer);
    emitUpdateMethod(writer);
    emitToStringMethod(writer);
    emitRealmObjectProxyImplementation(writer);
    emitHashcodeMethod(writer);
    emitEqualsMethod(writer);
    // End the class definition
    writer.endType();
    writer.close();
}
Also used : JavaFileObject(javax.tools.JavaFileObject) JavaWriter(com.squareup.javawriter.JavaWriter) ArrayList(java.util.ArrayList) BufferedWriter(java.io.BufferedWriter)

Aggregations

JavaWriter (com.squareup.javawriter.JavaWriter)9 BufferedWriter (java.io.BufferedWriter)4 JavaFileObject (javax.tools.JavaFileObject)4 ArrayList (java.util.ArrayList)3 Writer (java.io.Writer)2 JsonElement (com.google.gson.JsonElement)1 File (java.io.File)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 StringWriter (java.io.StringWriter)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 VariableElement (javax.lang.model.element.VariableElement)1 Types (javax.lang.model.util.Types)1