Java Code Examples for com.squareup.javapoet.JavaFile

The following are top voted examples for showing how to use com.squareup.javapoet.JavaFile. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: slimorm   File: SlimOrmProcessor.java   View source code 6 votes vote down vote up
private void generateClass(TypeElement typeElement, List<VariableElement> listOfVariables) {

        final ClassName pojoType = ClassName.get(typeElement);

        TypeSpec.Builder classBuilder = TypeSpec.
                classBuilder(typeElement.getSimpleName() + "Converter")
                .addModifiers(Modifier.PUBLIC);

        classBuilder.addMethod(generateSingleRowParseMethod(typeElement, listOfVariables, "toSingleRow", Modifier.PUBLIC));
        classBuilder.addMethod(generateSingleRowParseMethod(typeElement, listOfVariables, "parseToSingleRow", Modifier.PUBLIC, Modifier.STATIC));

        classBuilder.addMethod(generateListParseMethod(pojoType, "toList", "toSingleRow", Modifier.PUBLIC));
        classBuilder.addMethod(generateListParseMethod(pojoType, "parseToList", "parseToSingleRow", Modifier.PUBLIC, Modifier.STATIC));

        classBuilder.addMethod(generateToContentValuesMethod(typeElement, listOfVariables, "toContentValues", Modifier.PUBLIC));
        classBuilder.addMethod(generateToContentValuesMethod(typeElement, listOfVariables, "parseToContentValues", Modifier.PUBLIC, Modifier.STATIC));

        try {
            JavaFile.builder(pojoType.packageName(), classBuilder.build())
                    .build()
                    .writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
 
Example 2
Project: GitHub   File: ButterKnifeProcessor.java   View source code 6 votes vote down vote up
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
  Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);

  for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
    TypeElement typeElement = entry.getKey();
    BindingSet binding = entry.getValue();

    JavaFile javaFile = binding.brewJava(sdk);
    try {
      javaFile.writeTo(filer);
    } catch (IOException e) {
      error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
    }
  }

  return false;
}
 
Example 3
Project: Alligator   File: NavigationFactoryGenerator.java   View source code 6 votes vote down vote up
public JavaFile generate(List<RegistrationAnnotatedClass> annotatedClasses) throws ProcessingException {
	MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
			.addModifiers(Modifier.PUBLIC);

	for (RegistrationAnnotatedClass annotatedClass : annotatedClasses) {
		ClassName annotatedClassName = ClassName.get(annotatedClass.getClassElement());
		ClassName screenClassName = ClassName.bestGuess(annotatedClass.getScreenClassName());

		if (annotatedClass.getScreenResultClassName() == null) {
			String registrationMethod = getRegistrationMethod(annotatedClass.getScreenType());
			constructorBuilder.addStatement(registrationMethod, screenClassName, annotatedClassName);
		} else {
			String registrationForResultMethod = getRegistrationForResultMethod(annotatedClass.getScreenType());
			ClassName screenResultClassName = ClassName.bestGuess(annotatedClass.getScreenResultClassName());
			constructorBuilder.addStatement(registrationForResultMethod, screenClassName, annotatedClassName, screenResultClassName);
		}
	}

	TypeSpec navigationFactory = TypeSpec.classBuilder(CLASS_NAME)
			.addModifiers(Modifier.PUBLIC)
			.superclass(ClassName.get(PACKAGE, SUPERCLASS_NAME))
			.addMethod(constructorBuilder.build())
			.build();

	return JavaFile.builder(PACKAGE, navigationFactory).build();
}
 
Example 4
Project: DaggerAutoInject   File: DaggerAutoInjectProcessor.java   View source code 6 votes vote down vote up
private void constructActivityModule() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.ACTIVITY_MODULE)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .addAnnotation(Constants.DAGGER_MODULE);

    for (ActivityHolder activityHolder : activityHolders.values()) {
        builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_CONTRIBUTE + activityHolder.className)
                .addAnnotation(Constants.DAGGER_ANDROID_ANNOTATION)
                .addModifiers(Modifier.ABSTRACT)
                .returns(activityHolder.classNameComplete)
                .build()
        );
    }

    final TypeSpec newClass = builder.build();
    final JavaFile javaFile = JavaFile.builder(Constants.PACKAGE_NAME, newClass).build();

    try {
        javaFile.writeTo(System.out);
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: butterknife-parent   File: ButterKnifeProcessor.java   View source code 6 votes vote down vote up
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
  Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);

  for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
    TypeElement typeElement = entry.getKey();
    BindingSet binding = entry.getValue();

    JavaFile javaFile = binding.brewJava(sdk);
    try {
      javaFile.writeTo(filer);
    } catch (IOException e) {
      error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
    }
  }

  return false;
}
 
Example 6
Project: RxRetroJsoup   File: RetroJsoupProcessor.java   View source code 6 votes vote down vote up
public void construct(JsoupModelHolder modelHolder) {

        final TypeSpec.Builder builder = TypeSpec.classBuilder(modelHolder.className + Constants.PARSER)
                .addModifiers(Modifier.PUBLIC);

        for (JsoupModelFieldHolder field : modelHolder.fields) {
            builder.addMethod(MethodSpec.methodBuilder(field.name.replace("-","_").replace(" ","_"))
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(modelHolder.classNameComplete, "item")
                    .addParameter(TypeName.get(String.class), "value")
                    .addStatement("item.$L = value", field.name)
                    .build());
        }

        final TypeSpec newClass = builder.build();

        final JavaFile javaFile = JavaFile.builder(modelHolder.classNameComplete.packageName(), newClass).build();

        try {
            javaFile.writeTo(System.out);
            javaFile.writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 7
Project: json-log-domain   File: JavaGenerator.java   View source code 6 votes vote down vote up
public static void generate(Domain ontology, Path outputDirectory) throws IOException {
	JavaFile tags = TagGenerator.tag(ontology);
	JavaFile marker = MarkerGenerator.marker(ontology);
	JavaFile builder = MarkerGenerator.markerBuilder(ontology);
	JavaFile statement = LoggerGenerator.statement(ontology);
	JavaFile logger = LoggerGenerator.logger(ontology);
	JavaFile mdc = MdcGenerator.statement(ontology);

	Files.createDirectories(outputDirectory);

	for(JavaFile file : new JavaFile[]{tags, marker, builder, statement, logger, mdc}) {
		if(file != null) {
			if(changed(file, outputDirectory)) {
				file.writeTo(outputDirectory);
			} else {
				// do not write this file
			}
		}
	}
}
 
Example 8
Project: json-log-domain   File: LoggerGenerator.java   View source code 6 votes vote down vote up
public static JavaFile logger(Domain ontology) {
	ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + LOGGER);

	ClassName statementName = ClassName.get(ontology.getTargetPackage(), ontology.getName() + STATEMENT);

	ParameterSpec loggerParameter = ParameterSpec.builder(org.slf4j.Logger.class, "logger").build();

	return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
		.superclass(ParameterizedTypeName.get(ClassName.get(AbstractDomainLogger.class), statementName))				
		.addJavadoc(composeJavadoc(ontology, name))
		.addModifiers(Modifier.PUBLIC)
		.addMethod(MethodSpec.constructorBuilder()
			.addModifiers(Modifier.PUBLIC)
			.addParameter(loggerParameter)
			.addStatement("super($N)", loggerParameter)
	        .build())
		.addMethod(getCreateLogStatementMethod(statementName)).build()).build();
}
 
Example 9
Project: prefpin   File: PrefPinProcessor.java   View source code 6 votes vote down vote up
private void writeBinding(String targetClassName, Set<Element> annotationFields)
    throws IOException {
  String packageName = null;
  int lastDot = targetClassName.lastIndexOf('.');
  if (lastDot > 0) {
    packageName = targetClassName.substring(0, lastDot);
  }

  String targetSimpleClassName = targetClassName.substring(lastDot + 1);
  String bindingClassName = targetClassName + "_PrefBinding";
  String bindingSimpleClassName = bindingClassName.substring(lastDot + 1);

  ClassName targetClass = ClassName.get(packageName, targetSimpleClassName);

  TypeSpec binding = TypeSpec.classBuilder(bindingSimpleClassName)
      .addModifiers(Modifier.PUBLIC)
      .addMethod(buildConstructor(targetClass, annotationFields))
      .build();

  JavaFile javaFile = JavaFile.builder(packageName, binding).build();

  javaFile.writeTo(processingEnv.getFiler());
}
 
Example 10
Project: ActivityBuilder   File: ConsumerHelper.java   View source code 6 votes vote down vote up
private static ClassName writeConsumer(int count) throws IOException {
  String packageName = "info.dourok.esactivity.function";
  MethodSpec.Builder method = MethodSpec.methodBuilder("accept")
      .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);

  TypeSpec.Builder type = TypeSpec.interfaceBuilder("Consumer" + count)
      .addModifiers(Modifier.PUBLIC);
  for (int i = 0; i < count; i++) {
    type.addTypeVariable(TypeVariableName.get("T" + i));
    method.addParameter(
        TypeVariableName.get("T" + i), "t" + i);
  }
  type.addMethod(method.build());
  JavaFile.builder(packageName, type.build())
      .build()
      .writeTo(EasyUtils.getFiler());
  return ClassName.get(packageName, "Consumer" + count);
}
 
Example 11
Project: AnnotationProcessorStarter   File: AnnotatedClass.java   View source code 6 votes vote down vote up
public void writeInto(final Filer pFiler, final Messager pMessager) {
    // prepare generated class
    final GeneratedClass lGeneratedClass = new GeneratedClass(mEnclosingClass, mMethods);

    final TypeSpec lTypeSpecGeneratedClass = lGeneratedClass.buildTypeSpec();
    final String lPackageName = lGeneratedClass.packageName();

    // create generated class to a file
    try {
        JavaFile.builder(lPackageName, lTypeSpecGeneratedClass)
                .build()
                .writeTo(pFiler);
    } catch (IOException pE) {
        logError(pMessager, mEnclosingClass, "error while writing generated class");
    }
}
 
Example 12
Project: r-parser   File: ExampleProcessor.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    parser.scan(roundEnvironment);
    TypeSpec.Builder builder = TypeSpec.classBuilder("Testing")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    for (Element element : roundEnvironment.getElementsAnnotatedWith(Parse.class))
        builder.addField(FieldSpec.builder(String.class, element.getSimpleName().toString())
                .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                .initializer("$S", parser.parse("com.example.rparser", element.getAnnotation(Parse.class).value()))
                .build());
    JavaFile javaFile = JavaFile.builder("com.example.rparser", builder.build())
            .build();
    try {
        javaFile.writeTo(filer);
    } catch (IOException ignored) {
    }
    return false;
}
 
Example 13
Project: Stitch   File: StitchProcessor.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
    Map<TypeElement, StitchGenerator> stitchGeneratorMap = processAnnotations(env);
    for (Entry<TypeElement, StitchGenerator> typeElementCodeGeneratorEntry : stitchGeneratorMap
            .entrySet()) {
        TypeElement typeElement = typeElementCodeGeneratorEntry.getKey();
        StitchGenerator stitchGenerator = typeElementCodeGeneratorEntry.getValue();
        JavaFile javaFile = stitchGenerator.makeFile();
        try {
            javaFile.writeTo(processingEnv.getFiler());
        } catch (IOException e) {
            mMessager.printMessage(Kind.ERROR, String
                    .format("Unable to write binding for type %s: %s",
                            typeElement.getSimpleName(),
                            e.getMessage()));
        }
    }
    return false;
}
 
Example 14
Project: DeeplinkRouter   File: DeeplinkRouterProcessor.java   View source code 6 votes vote down vote up
private void innerGenerateRouterInit(MethodSpec.Builder methodBuilder)
{
    TypeSpec routerInit = TypeSpec.classBuilder(ROUTER_INIT_CLASS_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addSuperinterface(ClassName.get(ROUTER_API_PACKAGE_NAME, ROUTER_INIT_INTERFACE_NAME))
            .addMethod(methodBuilder.build())
            .build();
    try
    {
        JavaFile.builder(ROUTER_API_PACKAGE_NAME, routerInit)
                .build()
                .writeTo(mFiler);
    }
    catch (Exception e)
    {
        error("Failed to generate file %s", routerInit.name);
    }
}
 
Example 15
Project: auto   File: DecoratorProcessor.java   View source code 6 votes vote down vote up
private JavaFile process(EnrichedTypeElement element) throws AbortProcessingException {
  TypeSpec.Builder builder = TypeSpec.classBuilder(element.getClassName(DECORATOR_SUFFIX))
      .addModifiers(element.getAccessModifier())
      .addTypeVariables(element.getTypeVariables())
      .addField(createDelegateFieldSpec(element))
      .addMethod(createConstructorMethod(element))
      .addMethods(createOverridingMethods(element));

  if (element.isInterface()) {
    builder.addSuperinterface(element.getTypeName());
  } else if (element.isAbstract()) {
    builder.superclass(element.getTypeName());
  } else {
    throw new AbortProcessingException("Cannot generate implementation for final class");
  }

  return JavaFile.builder(element.getPackageName(), builder.build())
      .build();
}
 
Example 16
Project: D-Router   File: RouterTableGenerator.java   View source code 6 votes vote down vote up
public void generateMappingTable(Filer filer) throws IOException {
    if (routerTable.isEmpty()) {
        return;
    }
    FieldSpec tableFieldSpec = FieldSpec.builder(Map.class, "routerTable")
            .addModifiers(Modifier.PRIVATE)
            .build();
    MethodSpec initTableMethodSpec = getInitTableMethodSpec();
    MethodSpec queryTableMethodSpec = getqueryTableMethodSpec();
    MethodSpec constructorMethodSpec = getconstructorMethodSpec(tableFieldSpec, initTableMethodSpec);
    MethodSpec addRouterMethodSpec = getAddRouterMethodSpec();
    TypeSpec routerTableClassTypeSpec = getRouterTableClassTypeSpec(tableFieldSpec, initTableMethodSpec, queryTableMethodSpec, constructorMethodSpec, addRouterMethodSpec);
    String packageName = Constants.GENERATED_PACKAGE_NAME;
    JavaFile javaFile = JavaFile.builder(packageName, routerTableClassTypeSpec).build();
    javaFile.writeTo(filer);
}
 
Example 17
Project: Spyglass   File: TestGetDefaultMethodGenerator.java   View source code 6 votes vote down vote up
private void checkCompiles(final MethodSpec method) {
	final TypeSpec wrapperTypeSpec = CallerDef
			.getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
			.addMethod(CallerDef.getNewCallMethodPrototype().build())
			.addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
			.addMethod(method)
			.build();

	final JavaFile wrapperJavaFile = JavaFile
			.builder("", wrapperTypeSpec)
			.build();

	final Set<JavaFile> filesToCompile = new HashSet<>();
	filesToCompile.add(wrapperJavaFile);
	filesToCompile.add(CallerDef.SRC_FILE);

	CompileChecker.checkCompiles(filesToCompile);
}
 
Example 18
Project: Spyglass   File: TestGetPlaceholderMethodGenerator.java   View source code 6 votes vote down vote up
private void checkCompiles(final MethodSpec method) {
	final TypeSpec wrapperTypeSpec = CallerDef
			.getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
			.addMethod(CallerDef.getNewCallMethodPrototype().build())
			.addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
			.addMethod(method)
			.build();

	final JavaFile wrapperJavaFile = JavaFile
			.builder("", wrapperTypeSpec)
			.build();

	final Set<JavaFile> filesToCompile = new HashSet<>();
	filesToCompile.add(wrapperJavaFile);
	filesToCompile.add(CallerDef.SRC_FILE);

	CompileChecker.checkCompiles(filesToCompile);
}
 
Example 19
Project: Spyglass   File: TestValueIsAvailableMethodGenerator.java   View source code 6 votes vote down vote up
private void checkCompiles(final MethodSpec method) {
	final TypeSpec wrapperTypeSpec = CallerDef
			.getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
			.addMethod(CallerDef.getNewCallMethodPrototype().build())
			.addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
			.addMethod(method)
			.build();

	final JavaFile wrapperJavaFile = JavaFile
			.builder("", wrapperTypeSpec)
			.build();

	final Set<JavaFile> filesToCompile = new HashSet<>();
	filesToCompile.add(wrapperJavaFile);
	filesToCompile.add(CallerDef.SRC_FILE);

	CompileChecker.checkCompiles(filesToCompile);
}
 
Example 20
Project: Spyglass   File: TestGetValueMethodGenerator.java   View source code 6 votes vote down vote up
private void checkCompiles(final MethodSpec method) {
	final TypeSpec wrapperTypeSpec = CallerDef
			.getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
			.addMethod(CallerDef.getNewCallMethodPrototype().build())
			.addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
			.addMethod(method)
			.build();

	final JavaFile wrapperJavaFile = JavaFile
			.builder("", wrapperTypeSpec)
			.build();

	final Set<JavaFile> filesToCompile = new HashSet<>();
	filesToCompile.add(wrapperJavaFile);
	filesToCompile.add(CallerDef.SRC_FILE);

	CompileChecker.checkCompiles(filesToCompile);
}
 
Example 21
Project: immu   File: ImmuCompilerTest.java   View source code 6 votes vote down vote up
@Test
public void write_withIOException() throws Exception {
  final ProcessingEnvironment env = mock(ProcessingEnvironment.class);
  final Messager messager = mock(Messager.class);
  final Filer filer = mock(Filer.class);

  when(env.getMessager()).thenReturn(messager);
  when(env.getFiler()).thenReturn(filer);

  compiler.init(env);

  final JavaFile javaFile = mock(JavaFile.class);
  doThrow(IOException.class).when(javaFile).writeTo(any(Filer.class));

  compiler.writeSource(javaFile);

  verify(messager, times(1)).printMessage(eq(Diagnostic.Kind.ERROR), any());
}
 
Example 22
Project: data-mediator   File: SharedPropertiesNGenerator.java   View source code 6 votes vote down vote up
public static boolean generateSharedProperties(Collection<FieldData> fields,
                                               Elements elements, Filer filer, ProcessorPrinter pp){
    final ClassName cn_sp = ClassName.get(PKG_DM_INTERNAL, SIMPLE_NAME_SHARED_PROP);
    CodeBlock.Builder staticBuilder = CodeBlock.builder();
    for(FieldData fd : fields){
        staticBuilder.add("$T.putToCache($S, $S, $L);\n", cn_sp, fd.getTypeCompat().toString(),
                fd.getPropertyName(), fd.getComplexType());
    }
    String classSimpleName = SIMPLE_NAME_SHARED_PROP + "_" + findBestIndex(elements);
    TypeSpec typeSpec = TypeSpec.classBuilder(classSimpleName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();

    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
 
Example 23
Project: auto   File: NoOpProcessor.java   View source code 6 votes vote down vote up
private JavaFile process(EnrichedTypeElement element) throws AbortProcessingException {
  TypeSpec.Builder builder = TypeSpec.classBuilder(element.getClassName(NO_OP_SUFFIX));

  if (element.getAnnotation(AutoNoOp.class).instance()) {
    builder
        .addField(createInstanceField(element))
        .addMethod(createInstanceMethod(element));
  }

  if (element.isInterface()) {
    builder.addSuperinterface(element.getTypeName());
  } else if (element.isAbstract()) {
    builder.superclass(element.getTypeName());
  } else {
    throw new AbortProcessingException("Cannot generate implementation for final class");
  }

  builder
      .addModifiers(element.getAccessModifier())
      .addTypeVariables(element.getTypeVariables())
      .addMethods(createOverridingMethods(element));

  return JavaFile.builder(element.getPackageName(), builder.build())
      .build();
}
 
Example 24
Project: jdoocsoup   File: JDoocsSoupAnnotationProcessor.java   View source code 5 votes vote down vote up
private void createJavaFile(String packageName, TypeSpec typeSpec) {
    try {
        JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
                .build();
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException ex) {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.ERROR, "It was not possible to generate java files due to an error: \n" + ex.getMessage());
    }
}
 
Example 25
Project: GitHub   File: ProcessorUtil.java   View source code 5 votes vote down vote up
void writeClass(String packageName, TypeSpec clazz) {
  try {
    debugLog("Writing class:\n" + clazz);
    JavaFile.builder(packageName, clazz).build().writeTo(processingEnv.getFiler());
  } catch (Throwable e) {
    throw new RuntimeException(e);
  }
}
 
Example 26
Project: auto-nav   File: NavProcessor.java   View source code 5 votes vote down vote up
private void createNavigator(Set<ActivityIntentModel> activityModels) {

        TypeSpec.Builder navigatorBuilder = TypeSpec.classBuilder(navigatorClassName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

        for (ActivityIntentModel model : activityModels) {
            createActivityIntent(model);

            /**
             *         public static MainActivityIntent toMainActivity(Context context){
             *             MainActivityIntent intent = new MainActivityIntent(context, "com.com.MainActivity");
             *             return intent;
             *         }
             */

            ClassName returnType = ClassName.get(model.getPackageName(), model.getIntentClzName());
            MethodSpec.Builder methodSpecBuilder = MethodSpec
                    .methodBuilder(METHOD_PREFIX + model.getClzName());
            methodSpecBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(classContext, "context")
                    .returns(ClassName.get(model.getPackageName(), model.getIntentClzName()))
                    .addStatement("$T intent = new $T($L,$S)", returnType, returnType, "context", model.getQualifiedName())
                    .addStatement("return intent");

            navigatorBuilder.addMethod(methodSpecBuilder.build());
        }

        addPreGoListener(navigatorBuilder);


        try {
            JavaFile.builder(navigatorPackageName, navigatorBuilder.build()).build().writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
 
Example 27
Project: GitHub   File: DelegateClassGenerator.java   View source code 5 votes vote down vote up
@Override
public JavaFile build() {
    TypeSpec.Builder result =
            TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
                    .addSuperinterface(
                            ParameterizedTypeName.get(VIEW_DELEGATE, viewClass,
                                                      getPresenterFactoryTypeName()));
    decorator.build(result);
    return JavaFile.builder(getPackageName(), result.build())
            .addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
 
Example 28
Project: Rx.Observe   File: RxObserveProcessor.java   View source code 5 votes vote down vote up
private void writeRxObserve() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.CLASS)
            .addModifiers(Modifier.PUBLIC);

    for (ClassName className : observeHolders.keySet()) {
        final ObserveHolder observeHolder = observeHolders.get(className);
        final String simpleName = className.simpleName();
        final TypeName returnType = ClassName.bestGuess(className.packageName() + "." + simpleName + Constants.OBSERVE_CLASS);

        if (processUtils.allMethodsAreStatic(observeHolder.methods)) {
            builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_OF + simpleName)
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .returns(returnType)
                    .addStatement("return new $T()", returnType)
                    .build());
        } else {
            builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_OF)
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(className, Constants.TARGET)
                    .returns(returnType)
                    .addStatement("return new $T($L)", returnType, Constants.TARGET)
                    .build());
        }
    }

    final TypeSpec newClass = builder.build();

    final JavaFile javaFile = JavaFile.builder(Constants.PACKAGE, newClass).build();

    try {
        javaFile.writeTo(System.out);
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 29
Project: GitHub   File: ProcessorUtil.java   View source code 5 votes vote down vote up
void writeClass(String packageName, TypeSpec clazz) {
  try {
    debugLog("Writing class:\n" + clazz);
    JavaFile.builder(packageName, clazz).build().writeTo(processingEnv.getFiler());
  } catch (Throwable e) {
    throw new RuntimeException(e);
  }
}
 
Example 30
Project: GitHub   File: ObjectMapperInjector.java   View source code 5 votes vote down vote up
public String getJavaClassFile() {
    try {
        return JavaFile.builder(mJsonObjectHolder.packageName, getTypeSpec()).build().toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 31
Project: easybundler   File: Bundler.java   View source code 5 votes vote down vote up
/**
 * Process the BundlerClass and return the source of a generated Bundler class, as a String.
 * The output of this method is intended for writing to a ".java" file.
 */
public String getBundlerClassSource() {
    // Create class named {FooObject}Bundler
    TypeSpec bundlerType = TypeSpec.classBuilder(getBundlerClassName())
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(createToBundleMethod())
            .addMethod(createFromBundleMethod())
            .build();

    JavaFile javaFile = JavaFile.builder(info.className.packageName(), bundlerType)
            .build();

    return javaFile.toString();
}
 
Example 32
Project: greycat   File: Generator.java   View source code 5 votes vote down vote up
private void generateJava(String packageName, String pluginName, File target) {
    List<JavaFile> collector = new ArrayList<JavaFile>();
    TypeGenerator.generate(packageName, model, collector);
    IndexGenerator.generate(packageName, model, collector);
    ConstantGenerator.generate(packageName, model, collector);
    PluginGenerator.generate(packageName, pluginName, model, collector);
    for (JavaFile file : collector) {
        try {
            file.writeTo(target);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 33
Project: android-state   File: StateProcessor.java   View source code 5 votes vote down vote up
private boolean writeJavaFile(JavaFile javaFile) {
    StringBuilder builder = new StringBuilder();

    JavaFileObject filerSourceFile = null;

    try {
        builder.append(LICENSE_HEADER);
        javaFile.writeTo(builder);

        String fileName = javaFile.packageName.isEmpty() ? javaFile.typeSpec.name : javaFile.packageName + "." + javaFile.typeSpec.name;
        List<Element> originatingElements = javaFile.typeSpec.originatingElements;
        filerSourceFile = mFiler.createSourceFile(fileName, originatingElements.toArray(new Element[originatingElements.size()]));

        try (Writer writer = filerSourceFile.openWriter()) {
            writer.write(builder.toString());
        }
        return true;

    } catch (Exception e) {
        mMessager.printMessage(Diagnostic.Kind.ERROR, "Couldn't generate classes " + javaFile.packageName + '.' + javaFile.typeSpec.name);
        e.printStackTrace();

        if (filerSourceFile != null) {
            filerSourceFile.delete();
        }

        return false;
    }
}
 
Example 34
Project: konohana   File: StoreWriter.java   View source code 5 votes vote down vote up
private void write() {
    try {
        JavaFile.builder(storeDefinition.getInterfaceName().packageName(), buildTypeSpec())
                .build()
                .writeTo(storeDefinition.getFiler());
    } catch (IOException e) {
        throw storeDefinition.newProcessingException(e);
    }
}
 
Example 35
Project: lazythreetenbp   File: JavaWriter.java   View source code 5 votes vote down vote up
void writeZoneIds(String version, Set<String> zoneIds) throws IOException {
    TypeSpec typeSpec = TypeSpec.classBuilder("LazyZoneRules")
            .addModifiers(FINAL)
            .addField(version(version))
            .addField(regionId(zoneIds))
            .build();

    if (!Files.exists(outputDir)) {
        Files.createDirectories(outputDir);
    }
    JavaFile.builder("com.gabrielittner.threetenbp", typeSpec)
            .build()
            .writeTo(outputDir);
}
 
Example 36
Project: limitjson   File: LJSONAnnotatedClass.java   View source code 5 votes vote down vote up
public static void toWrite(ProcessorHelper helper, LJSONTypeElement ljsonElement, Filer filer) throws IOException {

        // create common ClassName
        ClassName thisObj = ClassName.bestGuess(ljsonElement.getTypeName());
        ClassName jsonObject = ClassName.get("org.json", "JSONObject");

        MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .returns(thisObj)
                .addParameter(ClassName.get(String.class), "json", Modifier.FINAL)
                .addParameter(TypeName.BOOLEAN, "allowNull", Modifier.FINAL)
                .addStatement("$T thisObj = new $T()", thisObj, thisObj)
                .beginControlFlow("try")
                .addStatement("$T root = new $T(json)", jsonObject, jsonObject);

        List<LIMITJSONVariable> ljsonVariableElements = ljsonElement.getVariableElements();
        addLJSONVariable(helper, createMethod, ljsonVariableElements);

        createMethod.nextControlFlow("catch (Exception e)")
                .beginControlFlow("if (allowNull)")
                .addStatement("return null")
                .endControlFlow()
                .endControlFlow();

        createMethod.addStatement("return thisObj");
        // generate whole class
        TypeSpec finderClass = TypeSpec.classBuilder(ljsonElement.getTypeName() + "$$CREATOR")
                .addModifiers(Modifier.PUBLIC)
//                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(CORE_PACKAGE_NAME, "Core"), TypeName.get(classElement.asType())))
                .addMethod(createMethod.build())
//                .addMethod(parseIntentBuilder.build())
//                .addMethod(saveInstanceStateBuilder.build())
                .build();

        String packageName = ljsonElement.getTypePackageName();
        // generate file
        JavaFile.builder(packageName, finderClass).build().writeTo(filer);
    }
 
Example 37
Project: Hannibai   File: ElementGenerator.java   View source code 5 votes vote down vote up
@Override
public void generate() {
    try {
        JavaFile.builder(mPackageName, onCreateTypeSpec(mElement, mPackageName, mClassName))
                .build()
                .writeTo(EnvironmentManager.getManager().getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 38
Project: Surgeon   File: SurgeonProcessor.java   View source code 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
    List<JavaFile> files = findAndParseTargets(env);
    for (JavaFile javaFile : files) {
        try {
            javaFile.writeTo(filer);
        } catch (IOException e) {
            error("Unable to write same name %s: %s", javaFile.packageName, e.getMessage());
        }
    }
    return false;
}
 
Example 39
Project: DDComponentForAndroid   File: RouterProcessor.java   View source code 5 votes vote down vote up
/**
 * generate HostUIRouter.java
 */
private void generateRouterImpl() {

    String claName = RouteUtils.genHostUIRouterClass(host);

    //pkg
    String pkg = claName.substring(0, claName.lastIndexOf("."));
    //simpleName
    String cn = claName.substring(claName.lastIndexOf(".") + 1);
    // superClassName
    ClassName superClass = ClassName.get(elements.getTypeElement(BASECOMPROUTER));

    MethodSpec initHostMethod = generateInitHostMethod();
    MethodSpec initMapMethod = generateInitMapMethod();

    try {
        JavaFile.builder(pkg, TypeSpec.classBuilder(cn)
                .addModifiers(PUBLIC)
                .superclass(superClass)
                .addMethod(initHostMethod)
                .addMethod(initMapMethod)
                .build()
        ).build().writeTo(mFiler);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 40
Project: json-log-domain   File: MdcGenerator.java   View source code 5 votes vote down vote up
public static JavaFile statement(Domain ontology) {
	
	ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + MARKER_MDC);

	ClassName markerName = MarkerGenerator.getName(ontology);
	
    TypeName wildcard = WildcardTypeName.subtypeOf(DomainMarker.class);
    TypeName classOfAny = ParameterizedTypeName.get(ClassName.get(Class.class), wildcard);
    
	ParameterSpec type = ParameterSpec.builder(classOfAny, "type").build();

	return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
				.superclass(ParameterizedTypeName.get( ClassName.get(DomainMdc.class), markerName))
				.addModifiers(Modifier.PUBLIC)
				.addMethod(MethodSpec.constructorBuilder()
					.addModifiers(Modifier.PUBLIC)
					.addStatement("super($T.QUALIFIER)", markerName)
					.build()
				)
				.addMethod(MethodSpec.methodBuilder("createMarker")
						.addModifiers(Modifier.PUBLIC)
						.addStatement("return new $T()", markerName)
						.returns(markerName)
						.build()
					)
				.addMethod(MethodSpec.methodBuilder("supports")
						.addModifiers(Modifier.PUBLIC)
						.addParameter(type)
						.addStatement("return $T.class == $N", markerName, type)
						.returns(boolean.class)
						.build()
					)
				.build())
			
			.build();
}