Java Code Examples for com.squareup.javawriter.JavaWriter#endType()

The following examples show how to use com.squareup.javawriter.JavaWriter#endType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ParcelerGenerator.java    From postman with MIT License 6 votes vote down vote up
public void generateParceler() throws IOException {

        JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(parcelerName);
        JavaWriter writer = new JavaWriter(sourceFile.openWriter());

        writer.emitPackage(processingEnv.getElementUtils().getPackageOf(
                elementToParcel).getQualifiedName().toString());

        writer.emitImports(getImports());
        writer.emitEmptyLine();
        elementCompressedName = writer.compressType(elementToParcel.getQualifiedName().toString());
        writer.beginType(parcelerName, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL), null,
                         JavaWriter.type(Parceler.class, elementCompressedName));
        writer.emitEmptyLine();

        writeWriteToParcelMethod(writer);
        writer.emitEmptyLine();
        writeReadFromParcelMethod(writer);
        writer.emitEmptyLine();
        writeNewArrayMethod(writer);
        writer.emitEmptyLine();

        writer.endType();
        writer.close();
    }
 
Example 2
Source File: AdapterHolderWriter.java    From Ollie with Apache License 2.0 6 votes vote down vote up
@Override
public void writeSource(Writer writer, TypeElement element) throws IOException {
	JavaWriter javaWriter = new JavaWriter(writer);
	javaWriter.setCompressingTypes(true);
	javaWriter.setIndent("\t");

	javaWriter.emitSingleLineComment("Generated by Ollie. Do not modify!");
	javaWriter.emitPackage("ollie");

	writeImports(javaWriter);

	javaWriter.beginType(AdapterHolder.IMPL_CLASS_NAME, "class", METHOD_MODIFIERS, null, "AdapterHolder");

	writeCollections(javaWriter);
	writeStaticInitializations(javaWriter);
	writeGetMigrations(javaWriter);
	writeGetModelAdapter(javaWriter);
	writeGetModelAdapters(javaWriter);
	writeGetTypeAdpater(javaWriter);

	javaWriter.endType();
}
 
Example 3
Source File: MementoProcessor.java    From memento with Apache License 2.0 6 votes vote down vote up
private void generateMemento(Set<? extends Element> elements, Element hostActivity, TypeElement activityType)
        throws IOException {
    PackageElement packageElement = processingEnv.getElementUtils().getPackageOf(hostActivity);
    final String simpleClassName = hostActivity.getSimpleName() + "$Memento";
    final String qualifiedClassName = packageElement.getQualifiedName() + "." + simpleClassName;

    log("writing class " + qualifiedClassName);
    JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(
            qualifiedClassName, elements.toArray(new Element[elements.size()]));

    JavaWriter writer = new JavaWriter(sourceFile.openWriter());

    emitClassHeader(packageElement, activityType, writer);

    writer.beginType(qualifiedClassName, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL),
            "Fragment", LIB_PACKAGE + ".MementoMethods");

    emitFields(elements, writer);
    emitConstructor(simpleClassName, writer);
    emitReaderMethod(elements, hostActivity, writer);
    emitWriterMethod(elements, hostActivity, writer);

    writer.endType();
    writer.close();
}
 
Example 4
Source File: BuildConfigGenerator.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generates the BuildConfig class.
 */
public void generate() throws IOException {
    File pkgFolder = getFolderPath();
    if (!pkgFolder.isDirectory()) {
        if (!pkgFolder.mkdirs()) {
            throw new RuntimeException("Failed to create " + pkgFolder.getAbsolutePath());
        }
    }

    File buildConfigJava = new File(pkgFolder, BUILD_CONFIG_NAME);

    Closer closer = Closer.create();
    try {
        FileOutputStream fos = closer.register(new FileOutputStream(buildConfigJava));
        OutputStreamWriter out = closer.register(new OutputStreamWriter(fos, Charsets.UTF_8));
        JavaWriter writer = closer.register(new JavaWriter(out));

        writer.emitJavadoc("Automatically generated file. DO NOT MODIFY")
                .emitPackage(mBuildConfigPackageName)
                .beginType("BuildConfig", "class", PUBLIC_FINAL);

        for (ClassField field : mFields) {
            emitClassField(writer, field);
        }

        for (Object item : mItems) {
            if (item instanceof ClassField) {
                emitClassField(writer, (ClassField) item);
            } else if (item instanceof String) {
                writer.emitSingleLineComment((String) item);
            }
        }

        writer.endType();
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}
 
Example 5
Source File: TableObject.java    From shillelagh with Apache License 2.0 5 votes vote down vote up
/** Create the java functions required for the internal class */
void brewJava(Writer writer) throws IOException {
  logger.d("brewJava");
  JavaWriter javaWriter = new JavaWriter(writer);
  javaWriter.setCompressingTypes(false);

  javaWriter.emitSingleLineComment("Generated code from Shillelagh. Do not modify!") //
      .emitPackage(classPackage) //
      /* Knows nothing of android types, must use strings. */ //
      .emitImports("android.content.ContentValues", "android.database.Cursor", //
          "android.database.DatabaseUtils", "android.database.sqlite.SQLiteDatabase") //
      .emitImports(ShillelaghUtil.class, ByteArrayInputStream.class, ByteArrayOutputStream.class,
          IOException.class, ObjectInputStream.class, ObjectOutputStream.class, LinkedList.class,
          Date.class, List.class) //
      .beginType(className, "class", EnumSet.of(PUBLIC, FINAL));

  if (this.isChildTable) {
    emitParentInsert(javaWriter);
    emitSelectAll(javaWriter);
  }
  emitInsert(javaWriter);
  emitOneToOneInsert(javaWriter);
  emitGetId(javaWriter);
  emitCreateTable(javaWriter);
  emitDropTable(javaWriter);
  emitUpdate(javaWriter);
  emitUpdateColumnId(javaWriter);
  emitDeleteWithId(javaWriter);
  emitDeleteWithObject(javaWriter);
  emitMapCursorToObject(javaWriter);
  emitSingleMap(javaWriter);
  emitSelectById(javaWriter);
  javaWriter.endType();
}
 
Example 6
Source File: ModelAdapterWriter.java    From Ollie with Apache License 2.0 5 votes vote down vote up
@Override
public void writeSource(Writer writer, TypeElement element) throws IOException {
	final String simpleName = createSimpleName(element);
	final String modelSimpleName = element.getSimpleName().toString();
	final String modelQualifiedName = element.getQualifiedName().toString();
	final String tableName = element.getAnnotation(Table.class).value();
	final Set<ColumnElement> columns = registry.getColumnElements(element);

	JavaWriter javaWriter = new JavaWriter(writer);
	javaWriter.setCompressingTypes(true);
	javaWriter.setIndent("\t");

	javaWriter.emitSingleLineComment("Generated by Ollie. Do not modify!");
	javaWriter.emitPackage("ollie");

	writeImports(javaWriter, modelQualifiedName, columns);

	javaWriter.beginType(simpleName, "class", MODIFIERS, "ModelAdapter<" + modelSimpleName + ">");

	writeGetModelType(javaWriter, modelSimpleName);
	writeGetTableName(javaWriter, tableName);
	writeGetSchema(javaWriter, tableName, columns);
	writeLoad(javaWriter, modelQualifiedName, columns);
	writeSave(javaWriter, modelQualifiedName, columns);
	writeDelete(javaWriter, modelQualifiedName, tableName);

	javaWriter.endType();
}
 
Example 7
Source File: DialogNewClass.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
private void createNewClass() {
    String className = mEditName.getText().toString();
    if (className.isEmpty()) {
        mEditName.setError(getString(R.string.enter_name));
        return;
    }
    if (!className.matches(PatternFactory.IDENTIFIER.pattern())) {
        mEditName.setError(getString(R.string.invalid_name));
        return;
    }
    String currentPackage = mPackage.getText().toString();
    if (currentPackage.trim().isEmpty()) {
        mPackage.setError(getString(R.string.enter_package));
        return;
    }
    if (!currentPackage.matches(PatternFactory.PACKAGE_NAME.pattern())) {
        mPackage.setError(getString(R.string.invalid_name));
        return;
    }

    Set<javax.lang.model.element.Modifier> modifiers = new ArraySet<>();
    if ((mVisibility.getCheckedRadioButtonId() == R.id.rad_public)) {
        modifiers.add(javax.lang.model.element.Modifier.PUBLIC);
    }

    int checkedRadioButtonId = mModifiers.getCheckedRadioButtonId();
    if (checkedRadioButtonId == R.id.rad_abstract) {
        modifiers.add(javax.lang.model.element.Modifier.ABSTRACT);
    } else if (checkedRadioButtonId == R.id.rad_final) {
        modifiers.add(javax.lang.model.element.Modifier.FINAL);
    }
    String kind = mKind.getSelectedItem().toString();
    try {
        StringWriter out = new StringWriter();
        JavaWriter writer = new JavaWriter(out);
        writer.emitPackage(currentPackage)
                .beginType(className, kind, modifiers)
                .emitEmptyLine();
        if (mCreateMainFunc.isChecked()) {
            //public static void main
            modifiers.clear();
            modifiers.add(Modifier.PUBLIC);
            modifiers.add(Modifier.STATIC);
            writer.beginMethod("void", "main", modifiers, "String[]", "args")
                    .emitEmptyLine()
                    .endMethod()
                    .emitEmptyLine();
        }
        writer.endType();
        writer.close();

        String content = out.toString();
        File clazz = project.createClass(currentPackage, className, content);
        if (listener != null) {
            listener.onFileCreated(clazz);
            Toast.makeText(getContext(), "success!", Toast.LENGTH_SHORT).show();
            this.dismiss();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

}
 
Example 8
Source File: StringFogClassGenerator.java    From StringFog with Apache License 2.0 4 votes vote down vote up
public static void generate(File outputFile, String packageName, String className, String key,
                            String implementation) throws IOException {
    File outputDir = outputFile.getParentFile();
    if (!outputDir.exists() && !outputDir.mkdirs()) {
        throw new IOException("Can not mkdirs the dir: " + outputDir);
    }

    int lastIndexOfDot = implementation.lastIndexOf(".");
    String implementationSimpleClassName = lastIndexOfDot == -1 ? implementation :
            implementation.substring(implementation.lastIndexOf(".") + 1);

    JavaWriter javaWriter = new JavaWriter(new FileWriter(outputFile));
    javaWriter.emitPackage(packageName);
    javaWriter.emitEmptyLine();
    javaWriter.emitImports(implementation);
    javaWriter.emitEmptyLine();

    javaWriter.emitJavadoc("Generated code from StringFog gradle plugin. Do not modify!");
    javaWriter.beginType(className, "class", ImmutableSet.of(Modifier.PUBLIC,
            Modifier.FINAL));

    javaWriter.emitField(implementationSimpleClassName, "IMPL",
            ImmutableSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL),
            "new " + implementationSimpleClassName + "()");

    javaWriter.emitEmptyLine();
    javaWriter.beginMethod(String.class.getSimpleName(), "encrypt",
            ImmutableSet.of(Modifier.PUBLIC, Modifier.STATIC),
            String.class.getSimpleName(), "value");
    javaWriter.emitStatement("return " + "IMPL.encrypt(value, \"" + key + "\")");
    javaWriter.endMethod();

    javaWriter.emitEmptyLine();
    javaWriter.beginMethod(String.class.getSimpleName(), "decrypt",
            ImmutableSet.of(Modifier.PUBLIC, Modifier.STATIC),
            String.class.getSimpleName(), "value");
    javaWriter.emitStatement("return " + "IMPL.decrypt(value, \"" + key + "\")");
    javaWriter.endMethod();

    javaWriter.emitEmptyLine();
    javaWriter.beginMethod(boolean.class.getSimpleName(), "overflow",
            ImmutableSet.of(Modifier.PUBLIC, Modifier.STATIC),
            String.class.getSimpleName(), "value");
    javaWriter.emitStatement("return " + "IMPL.overflow(value, \"" + key + "\")");
    javaWriter.endMethod();

    javaWriter.emitEmptyLine();
    javaWriter.endType();

    javaWriter.close();
}
 
Example 9
Source File: ParaphraseWriter.java    From paraphrase with Apache License 2.0 4 votes vote down vote up
private static void writeAbstractPhraseClass(JavaWriter writer) throws IOException {
  writer.beginType(ABSTRACT_PHRASE_CLASS, "class", EnumSet.of(PUBLIC, STATIC, ABSTRACT));

  writer.emitField("int", "resId", EnumSet.of(PRIVATE, FINAL));
  writer.emitField("String[]", "keys", EnumSet.of(PRIVATE, FINAL));
  writer.emitField("CharSequence[]", "values", EnumSet.of(FINAL));
  writer.emitEmptyLine();

  writer.beginConstructor(EnumSet.of(PRIVATE), "int", "resId", "String...", "keys");
  writer.emitStatement("this.resId = resId");
  writer.emitStatement("this.keys = keys");
  writer.emitStatement("this.values = new String[keys.length]");
  writer.endConstructor();
  writer.emitEmptyLine();

  writer.emitAnnotation(SuppressWarnings.class, "\"ConstantConditions\"");
  writer.beginMethod("CharSequence", "build", EnumSet.of(PUBLIC, FINAL), "View", "view");
  writer.emitStatement("return build(view.getContext().getResources())");
  writer.endMethod();
  writer.emitEmptyLine();

  writer.beginMethod("CharSequence", "build", EnumSet.of(PUBLIC, FINAL), "Context", "context");
  writer.emitStatement("return build(context.getResources())");
  writer.endMethod();
  writer.emitEmptyLine();

  writer.beginMethod("CharSequence", "build", EnumSet.of(PUBLIC, FINAL), "Resources", "res");
  writer.emitStatement(
      "SpannableStringBuilder text = new SpannableStringBuilder(res.getText(resId))");
  writer.emitStatement("int token = 0");
  writer.beginControlFlow("while ((token = nextToken(text, token)) != -1)");
  writer.emitStatement("String key = tokenAt(text, token)");
  writer.beginControlFlow("if (key == null)");
  writer.emitSingleLineComment("Skip this and next character to avoid '{{' instances.");
  writer.emitStatement("token += 2");
  writer.emitStatement("continue");
  writer.endControlFlow();
  writer.emitStatement("int index = Arrays.binarySearch(keys, key)");
  writer.beginControlFlow("if (index < 0)");
  writer.emitStatement(
      "throw new AssertionError(\"Unknown key '\" + key + \"' in: \" + Arrays.toString(keys))");
  writer.endControlFlow();
  writer.emitStatement("CharSequence value = values[index]");
  writer.emitStatement("text.replace(token, token + key.length() + 2, value)");
  writer.emitStatement("token += value.length()");
  writer.endControlFlow();
  writer.emitStatement("return text");
  writer.endMethod();
  writer.emitEmptyLine();

  writer.beginMethod("int", "nextToken", EnumSet.of(PRIVATE, STATIC), "SpannableStringBuilder",
      "b", "int", "start");
  writer.beginControlFlow("for (int i = start + 1, end = b.length(); i < end; i++)");
  writer.beginControlFlow("if (b.charAt(i) == '{')");
  writer.emitStatement("return i");
  writer.endControlFlow();
  writer.endControlFlow();
  writer.emitStatement("return -1");
  writer.endMethod();
  writer.emitEmptyLine();

  writer.beginMethod("String", "tokenAt", EnumSet.of(PRIVATE, STATIC), "SpannableStringBuilder",
      "b", "int", "start");
  writer.beginControlFlow("for (int i = start + 1, end = b.length(); i < end; i++)");
  writer.emitStatement("char current = b.charAt(i)");
  writer.beginControlFlow("if (current == '}')");
  writer.emitStatement("return b.subSequence(start + 1, i).toString()");
  writer.endControlFlow();
  writer.beginControlFlow("if (current < 'a' || current > 'z')");
  writer.emitStatement("break");
  writer.endControlFlow();
  writer.endControlFlow();
  writer.emitStatement("return null");
  writer.endMethod();

  writer.endType();
}