Java Code Examples for javax.annotation.processing.Filer#createSourceFile()
The following examples show how to use
javax.annotation.processing.Filer#createSourceFile() .
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: JavaFile.java From javapoet with Apache License 2.0 | 6 votes |
/** Writes this to {@code filer}. */ public void writeTo(Filer filer) throws IOException { String fileName = packageName.isEmpty() ? typeSpec.name : packageName + "." + typeSpec.name; List<Element> originatingElements = typeSpec.originatingElements; JavaFileObject filerSourceFile = filer.createSourceFile(fileName, originatingElements.toArray(new Element[originatingElements.size()])); try (Writer writer = filerSourceFile.openWriter()) { writeTo(writer); } catch (Exception e) { try { filerSourceFile.delete(); } catch (Exception ignored) { } throw e; } }
Example 2
Source File: ExtensionTest.java From auto with Apache License 2.0 | 6 votes |
@Override public String generateClass( Context context, String className, String classToExtend, boolean isFinal) { String sideClassName = "Side_" + context.autoValueClass().getSimpleName(); String sideClass = "" // + "package " + context.packageName() + ";\n" + "class " + sideClassName + " {}\n"; Filer filer = context.processingEnvironment().getFiler(); try { String sideClassFqName = context.packageName() + "." + sideClassName; JavaFileObject sourceFile = filer.createSourceFile(sideClassFqName, context.autoValueClass()); try (Writer sourceWriter = sourceFile.openWriter()) { sourceWriter.write(sideClass); } } catch (IOException e) { context .processingEnvironment() .getMessager() .printMessage(Diagnostic.Kind.ERROR, e.toString()); } return null; }
Example 3
Source File: AnnotationProcessor.java From buck with Apache License 2.0 | 6 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { Filer filer = processingEnv.getFiler(); try { JavaFileObject sourceFile = filer.createSourceFile("com.example.buck.Test"); try (OutputStream out = sourceFile.openOutputStream()) { out.write("package com.example.buck; class Test { }".getBytes()); } } catch (IOException e) { throw new AssertionError(e); } } return false; }
Example 4
Source File: LayoutProcessor.java From FastLayout with Apache License 2.0 | 6 votes |
private File getProjectRoot() throws Exception { if (projectRoot == null) { Filer filer = processingEnv.getFiler(); JavaFileObject dummySourceFile = filer.createSourceFile("dummy" + System.currentTimeMillis()); String dummySourceFilePath = dummySourceFile.toUri().toString(); if (dummySourceFilePath.startsWith("file:")) { if (!dummySourceFilePath.startsWith("file://")) { dummySourceFilePath = "file://" + dummySourceFilePath.substring("file:".length()); } } else { dummySourceFilePath = "file://" + dummySourceFilePath; } URI cleanURI = new URI(dummySourceFilePath); File dummyFile = new File(cleanURI); projectRoot = dummyFile.getParentFile(); } return projectRoot; }
Example 5
Source File: JavaWriter.java From dagger2-sample with Apache License 2.0 | 6 votes |
public void file(Filer filer, CharSequence name, Iterable<? extends Element> originatingElements) throws IOException { JavaFileObject sourceFile = filer.createSourceFile(name, Iterables.toArray(originatingElements, Element.class)); Closer closer = Closer.create(); try { write(closer.register(sourceFile.openWriter())); } catch (Exception e) { try { sourceFile.delete(); } catch (Exception e2) { // couldn't delete the file } throw closer.rethrow(e); } finally { closer.close(); } }
Example 6
Source File: JavaFile.java From JReFrameworker with MIT License | 6 votes |
/** Writes this to {@code filer}. */ public void writeTo(Filer filer) throws IOException { String fileName = packageName.isEmpty() ? typeSpec.name : packageName + "." + typeSpec.name; List<Element> originatingElements = typeSpec.originatingElements; JavaFileObject filerSourceFile = filer.createSourceFile(fileName, originatingElements.toArray(new Element[originatingElements.size()])); try (Writer writer = filerSourceFile.openWriter()) { writeTo(writer); } catch (Exception e) { try { filerSourceFile.delete(); } catch (Exception ignored) { } throw e; } }
Example 7
Source File: JavaFile.java From JReFrameworker with MIT License | 6 votes |
/** Writes this to {@code filer}. */ public void writeTo(Filer filer) throws IOException { String fileName = packageName.isEmpty() ? typeSpec.name : packageName + "." + typeSpec.name; List<Element> originatingElements = typeSpec.originatingElements; JavaFileObject filerSourceFile = filer.createSourceFile(fileName, originatingElements.toArray(new Element[originatingElements.size()])); try (Writer writer = filerSourceFile.openWriter()) { writeTo(writer); } catch (Exception e) { try { filerSourceFile.delete(); } catch (Exception ignored) { } throw e; } }
Example 8
Source File: ProcessorUtils.java From jackdaw with Apache License 2.0 | 5 votes |
public static JavaFileObject createSourceFile( final TypeElement baseElement, final String packageName, final String className ) throws Exception { final ProcessingEnvironment env = ProcessorContextHolder.getProcessingEnvironment(); final Filer filer = env.getFiler(); return filer.createSourceFile(packageName + SourceTextUtils.PACKAGE_SEPARATOR + className, baseElement); }
Example 9
Source File: AnnotationProcessor.java From buck with Apache License 2.0 | 5 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!roundEnv.processingOver() && !generated) { try { Filer filer = processingEnv.getFiler(); JavaFileObject cSource = filer.createSourceFile("ImmutableC"); try (OutputStream outputStream = cSource.openOutputStream()) { outputStream.write("public class ImmutableC { }".getBytes()); } JavaFileObject dSource = filer.createSourceFile("RemovableD"); try (OutputStream outputStream = dSource.openOutputStream()) { outputStream.write("public class RemovableD { }".getBytes()); } FileObject dResource = filer.createResource(StandardLocation.CLASS_OUTPUT, "", "RemovableD"); try (OutputStream outputStream = dResource.openOutputStream()) { outputStream.write("foo".getBytes()); } generated = true; } catch (IOException e) { throw new AssertionError(e); } } return true; }
Example 10
Source File: BaseProcessorTest.java From vertx-docgen with Apache License 2.0 | 5 votes |
@Test public void testGen() throws Exception { AtomicInteger count = new AtomicInteger(); AbstractProcessor proc = new AbstractProcessor() { @Override public Set<String> getSupportedAnnotationTypes() { return Collections.singleton("*"); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (count.getAndIncrement() == 0) { try { Filer filer = processingEnv.getFiler(); Element elt = processingEnv.getElementUtils().getTypeElement("gen.GeneratedClass"); JavaFileObject src = filer.createSourceFile("io.vertx.test.gen.GeneratedClass", elt); try (Writer writer = src.openWriter()) { writer.append("package io.vertx.test.gen;\npublic class GeneratedClass {\n}"); } } catch (Exception e) { e.printStackTrace(); } } return true; } }; Compiler<TestGenProcessor> compiler = buildCompiler(new TestGenProcessor(), "io.vertx.test.gen"); compiler.addProcessor(proc); compiler.assertCompile(); assertEquals(3, count.get()); }
Example 11
Source File: OptionProcessor.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
protected PrintWriter createSourceFile(String pkg, String relativeName, Filer filer, Element... originatingElements) { try { // Ensure Unix line endings to comply with code style guide checked by Checkstyle JavaFileObject sourceFile = filer.createSourceFile(pkg + "." + relativeName, originatingElements); return new PrintWriter(sourceFile.openWriter()) { @Override public void println() { print("\n"); } }; } catch (IOException e) { throw new RuntimeException(e); } }
Example 12
Source File: MasterProcessor.java From soabase-halva with Apache License 2.0 | 5 votes |
private void internalCreateSourceFile(String packageName, ClassName templateQualifiedClassName, ClassName generatedQualifiedClassName, String annotationType, TypeSpec.Builder builder, TypeElement element) { AnnotationSpec generated = AnnotationSpec .builder(Generated.class) .addMember("value", "\"" + annotationType + "\"") .build(); builder.addAnnotation(generated); TypeSpec classSpec = builder.build(); JavaFile javaFile = JavaFile.builder(packageName, classSpec) .addFileComment("Auto generated from $L by Soabase " + annotationType + " annotation processor", templateQualifiedClassName) .indent(" ") .build(); Filer filer = processingEnv.getFiler(); try { JavaFileObject sourceFile = filer.createSourceFile(generatedQualifiedClassName.toString()); try ( Writer writer = sourceFile.openWriter() ) { javaFile.writeTo(writer); } } catch ( IOException e ) { String message = "Could not create source file"; if ( e.getMessage() != null ) { message = message + ": " + e.getMessage(); } processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element); } }
Example 13
Source File: BaseViewGenerator.java From PowerfulRecyclerViewAdapter with Apache License 2.0 | 5 votes |
/** * create a Java source file * * @return */ protected JavaFileObject createFile() { JavaFileObject result = null; Filer filer = processingEnvironment.getFiler(); try { result = filer.createSourceFile(getModelClassName()); } catch (IOException e) { logger.log(Diagnostic.Kind.ERROR, "create source file failed"); e.printStackTrace(); } return result; }
Example 14
Source File: MatchProcessor.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
protected PrintWriter createSourceFile(String pkg, String relativeName, Filer filer, Element... originatingElements) { try { // Ensure Unix line endings to comply with Graal code style guide checked by Checkstyle JavaFileObject sourceFile = filer.createSourceFile(pkg + "." + relativeName, originatingElements); return new PrintWriter(sourceFile.openWriter()) { @Override public void println() { print("\n"); } }; } catch (IOException e) { throw new RuntimeException(e); } }
Example 15
Source File: SensorAnnotationsFileBuilder.java From SensorAnnotations with Apache License 2.0 | 4 votes |
/** * Generates the code for our "Sensor Binder" class and writes it to the same package as the * annotated class. * * @param groupedMethodsMap Map of annotated methods per class. * @param elementUtils ElementUtils class from {@link ProcessingEnvironment}. * @param filer File writer class from {@link ProcessingEnvironment}. * @throws IOException * @throws ProcessingException */ static void generateCode(@NonNull Map<String, AnnotatedMethodsPerClass> groupedMethodsMap, @NonNull Elements elementUtils, @NonNull Filer filer) throws IOException, ProcessingException { for (AnnotatedMethodsPerClass groupedMethods : groupedMethodsMap.values()) { // If we've annotated methods in an activity called "ExampleActivity" then that will be // the enclosing type element. TypeElement enclosingClassTypeElement = elementUtils.getTypeElement(groupedMethods.getEnclosingClassName()); // Create the parameterized type that our generated class will implement, // (such as "SensorBinder<ExampleActivity>"). ParameterizedTypeName parameterizedInterface = ParameterizedTypeName.get(SENSOR_BINDER, TypeName.get(enclosingClassTypeElement.asType())); // Create the target parameter that will be used in the constructor and bind method, // (such as "ExampleActivity"). ParameterSpec targetParameter = ParameterSpec.builder(TypeName.get(enclosingClassTypeElement.asType()), "target") .addModifiers(Modifier.FINAL) .build(); MethodSpec constructor = createConstructor(targetParameter, groupedMethods.getItemsMap()); MethodSpec bindMethod = createBindMethod(targetParameter, groupedMethods); TypeSpec sensorBinderClass = TypeSpec.classBuilder(enclosingClassTypeElement.getSimpleName() + SUFFIX) .addModifiers(Modifier.FINAL) .addSuperinterface(parameterizedInterface) .addField(SENSOR_MANAGER_FIELD) .addField(LISTENER_WRAPPERS_FIELD) .addMethod(constructor) .addMethod(bindMethod) .addMethod(UNBIND_METHOD) .build(); // Output our generated file with the same package as the target class. PackageElement packageElement = elementUtils.getPackageOf(enclosingClassTypeElement); JavaFileObject jfo = filer.createSourceFile(enclosingClassTypeElement.getQualifiedName() + SUFFIX); Writer writer = jfo.openWriter(); JavaFile.builder(packageElement.toString(), sensorBinderClass) .addFileComment("This class is generated code from Sensor Lib. Do not modify!") .addStaticImport(CONTEXT, "SENSOR_SERVICE") .build() .writeTo(writer); writer.close(); } }
Example 16
Source File: SystemConfigFactoryGenerator.java From qpid-broker-j with Apache License 2.0 | 4 votes |
private String generateObjectFactory(final Filer filer, final ExecutableElement constructorElement) { TypeElement classElement = (TypeElement) constructorElement.getEnclosingElement(); String factoryName = classElement.getQualifiedName().toString() + "Factory"; String factorySimpleName = classElement.getSimpleName().toString() + "Factory"; String objectSimpleName = classElement.getSimpleName().toString(); processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generating factory file for " + classElement.getQualifiedName().toString()); PackageElement packageElement = (PackageElement) classElement.getEnclosingElement(); try { JavaFileObject factoryFile = filer.createSourceFile(factoryName); PrintWriter pw = new PrintWriter(new OutputStreamWriter(factoryFile.openOutputStream(), "UTF-8")); pw.println("/*"); for(String headerLine : License.LICENSE) { pw.println(" *" + headerLine); } pw.println(" */"); pw.println(); pw.print("package "); pw.print(packageElement.getQualifiedName()); pw.println(";"); pw.println(); pw.println("import java.security.Principal;"); pw.println("import java.util.Map;"); pw.println(); pw.println("import org.apache.qpid.server.configuration.updater.TaskExecutor;"); pw.println("import org.apache.qpid.server.logging.EventLogger;"); pw.println("import org.apache.qpid.server.model.ConfiguredObjectTypeRegistry;"); pw.println("import org.apache.qpid.server.model.SystemConfig;"); pw.println("import org.apache.qpid.server.plugin.PluggableService;"); pw.println("import org.apache.qpid.server.plugin.SystemConfigFactory;"); pw.println(); pw.println("@PluggableService"); pw.println("public final class " + factorySimpleName + " implements SystemConfigFactory<"+ objectSimpleName +">"); pw.println("{"); pw.println(" public " + factorySimpleName + "()"); pw.println(" {"); pw.println(" }"); pw.println(); pw.println(" @Override"); pw.println(" public final String getType()"); pw.println(" {"); pw.println(" return ConfiguredObjectTypeRegistry.getType(" + objectSimpleName + ".class);"); pw.println(" }"); pw.println(); pw.println(" @Override"); pw.println(" public "+objectSimpleName+" newInstance(final TaskExecutor taskExecutor,"); pw.println(" final EventLogger eventLogger,"); pw.println(" final Principal systemPrincipal,"); pw.println(" final Map<String,Object> attributes)"); pw.println(" {"); pw.println(" return new "+objectSimpleName+"(taskExecutor, eventLogger, systemPrincipal, attributes);"); pw.println(" }"); pw.println("}"); pw.close(); } catch (IOException e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to write factory file: " + factoryName + " - " + e.getLocalizedMessage()); } return factoryName; }
Example 17
Source File: CompositeTypeConstructorGenerator.java From qpid-broker-j with Apache License 2.0 | 4 votes |
private void generateCompositeTypeConstructor(final Filer filer, final TypeElement typeElement) { String objectQualifiedClassName = typeElement.getQualifiedName().toString(); String objectSimpleName = typeElement.getSimpleName().toString(); String compositeTypeConstructorNameSimpleName = objectSimpleName + "Constructor"; PackageElement packageElement = (PackageElement) typeElement.getEnclosingElement(); final String compositeTypeConstructorPackage = packageElement.getQualifiedName() + ".codec"; String compositeTypeConstructorName = compositeTypeConstructorPackage + "." + compositeTypeConstructorNameSimpleName; final CompositeType annotation = typeElement.getAnnotation(CompositeType.class); processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generating composite constructor file for " + objectQualifiedClassName); try { JavaFileObject factoryFile = filer.createSourceFile(compositeTypeConstructorName); PrintWriter pw = new PrintWriter(new OutputStreamWriter(factoryFile.openOutputStream(), "UTF-8")); pw.println("/*"); for(String headerLine : License.LICENSE) { pw.println(" *" + headerLine); } pw.println(" */"); pw.println(); pw.print("package "); pw.print(compositeTypeConstructorPackage); pw.println(";"); pw.println(); pw.println("import java.util.List;"); pw.println(); pw.println("import org.apache.qpid.server.protocol.v1_0.codec.AbstractCompositeTypeConstructor;"); pw.println("import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;"); pw.println("import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;"); pw.println("import org.apache.qpid.server.protocol.v1_0.type.Symbol;"); pw.println("import org.apache.qpid.server.protocol.v1_0.type.UnsignedLong;"); pw.println("import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;"); pw.println("import org.apache.qpid.server.protocol.v1_0.type.transport.Error;"); pw.println("import " + objectQualifiedClassName + ";"); pw.println(); pw.println("public final class " + compositeTypeConstructorNameSimpleName + " extends AbstractCompositeTypeConstructor<"+ objectSimpleName +">"); pw.println("{"); pw.println(" private static final " + compositeTypeConstructorNameSimpleName + " INSTANCE = new " + compositeTypeConstructorNameSimpleName + "();"); pw.println(); pw.println(" public static void register(DescribedTypeConstructorRegistry registry)"); pw.println(" {"); pw.println(" registry.register(Symbol.valueOf(\"" + annotation.symbolicDescriptor() + "\"), INSTANCE);"); pw.println(String.format(" registry.register(UnsignedLong.valueOf(%#016x), INSTANCE);", annotation.numericDescriptor())); pw.println(" }"); pw.println(); pw.println(" @Override"); pw.println(" protected String getTypeName()"); pw.println(" {"); pw.println(" return " + objectSimpleName + ".class.getSimpleName();"); pw.println(" }"); pw.println(); pw.println(" @Override"); pw.println(" protected " + objectSimpleName + " construct(final FieldValueReader fieldValueReader) throws AmqpErrorException"); pw.println(" {"); pw.println(" " + objectSimpleName + " obj = new " + objectSimpleName + "();"); pw.println(); generateAssigners(pw, typeElement); pw.println(" return obj;"); pw.println(" }"); pw.println("}"); pw.close(); } catch (IOException e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to write composite constructor file: " + compositeTypeConstructorName + " - " + e.getLocalizedMessage()); } }