Java Code Examples for javax.tools.FileObject#openWriter()
The following examples show how to use
javax.tools.FileObject#openWriter() .
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: ComponentDescriptorGenerator.java From appinventor-extensions with Apache License 2.0 | 6 votes |
@Override protected void outputResults() throws IOException { StringBuilder sb = new StringBuilder(); sb.append('['); String separator = ""; // Components are already sorted. for (Map.Entry<String, ComponentInfo> entry : components.entrySet()) { ComponentInfo component = entry.getValue(); sb.append(separator); outputComponent(component, sb); separator = ",\n"; } sb.append(']'); FileObject src = createOutputFileObject(OUTPUT_FILE_NAME); Writer writer = src.openWriter(); writer.write(sb.toString()); writer.flush(); writer.close(); messager.printMessage(Diagnostic.Kind.NOTE, "Wrote file " + src.toUri()); }
Example 2
Source File: ProcessorImpl.java From takari-lifecycle with Eclipse Public License 1.0 | 6 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element element : roundEnv.getElementsAnnotatedWith(Annotation.class)) { try { TypeElement cls = (TypeElement) element; PackageElement pkg = (PackageElement) cls.getEnclosingElement(); String clsSimpleName = getGeneratedClassName(cls, prefix); String pkgName = pkg.getQualifiedName().toString(); FileObject sourceFile = createFile(pkgName, clsSimpleName, element); BufferedWriter w = new BufferedWriter(sourceFile.openWriter()); try { w.append("package ").append(pkgName).append(";"); w.newLine(); appendClassAnnotations(w); w.append("public class ").append(clsSimpleName); appendBody(pkgName, clsSimpleName, w); } finally { w.close(); } } catch (IOException e) { e.printStackTrace(); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), element); } } return false; // not "claimed" so multiple processors can be tested }
Example 3
Source File: ConfigurationDocWriter.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
public void generateIncomingDocumentation(Connector connector, List<ConnectorAttribute> commonAttributes, List<ConnectorAttribute> incomingAttributes) throws IOException { FileObject resource = environment.getFiler() .createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/connector/" + connector.value() + "-incoming.adoc"); resource.delete(); try (PrintWriter out = new PrintWriter(resource.openWriter())) { out.println(".Incoming Attributes of the '" + connector.value() + "' connector"); writeTableBegin(out); commonAttributes.forEach(att -> { if (!att.hiddenFromDocumentation()) { generateLine(att, out); } }); incomingAttributes.forEach(att -> { if (!att.hiddenFromDocumentation()) { generateLine(att, out); } }); out.println("|==="); } }
Example 4
Source File: ConfigurationDocWriter.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
public void generateOutgoingDocumentation(Connector connector, List<ConnectorAttribute> commonAttributes, List<ConnectorAttribute> incomingAttributes) throws IOException { FileObject resource = environment.getFiler() .createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/connector/" + connector.value() + "-outgoing.adoc"); resource.delete(); // merge and sort the attributes List<ConnectorAttribute> list = new ArrayList<>(commonAttributes); list.addAll(incomingAttributes); list.sort(Comparator.comparing(ConnectorAttribute::name)); try (PrintWriter out = new PrintWriter(resource.openWriter())) { out.println(".Outgoing Attributes of the '" + connector.value() + "' connector"); writeTableBegin(out); list.forEach(att -> { if (!att.hiddenFromDocumentation()) { generateLine(att, out); } }); out.println("|==="); } }
Example 5
Source File: JNIWriter.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
/** Emit a class file for a given class. * @param c The class from which a class file is generated. */ public FileObject write(ClassSymbol c) throws IOException { String className = c.flatName().toString(); FileObject outFile = fileManager.getFileForOutput(StandardLocation.NATIVE_HEADER_OUTPUT, "", className.replaceAll("[.$]", "_") + ".h", null); Writer out = outFile.openWriter(); try { write(out, c); if (verbose) log.printVerbose("wrote.file", outFile); out.close(); out = null; } finally { if (out != null) { // if we are propogating an exception, delete the file out.close(); outFile.delete(); outFile = null; } } return outFile; // may be null if write failed }
Example 6
Source File: ProcessorLastRound.java From takari-lifecycle with Eclipse Public License 1.0 | 6 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element element : roundEnv.getElementsAnnotatedWith(Annotation.class)) { TypeElement cls = (TypeElement) element; types.add(cls.getQualifiedName().toString()); } if (roundEnv.processingOver()) { try { FileObject resource = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "types.lst"); BufferedWriter w = new BufferedWriter(resource.openWriter()); try { for (String type : types) { w.append(type); w.newLine(); } } finally { w.close(); } } catch (IOException e) { processingEnv.getMessager().printMessage(Kind.ERROR, "Could not create output " + e.getMessage()); } } return false; // not "claimed" so multiple processors can be tested }
Example 7
Source File: JavaGeneratingProcessor.java From sundrio with Apache License 2.0 | 6 votes |
/** * Generates a source file from the specified {@link io.sundr.codegen.model.TypeDef}. * * @param model The model of the class to generate. * @param parameters The external parameters to pass to the template. * @param fileObject Where to save the generated class. * @param content The template to use. * @throws IOException If it fails to create the source file. */ public <T> void generateFromStringTemplate(T model, String[] parameters, FileObject fileObject, String content) throws IOException { if (fileObject.getName().endsWith(SOURCE_SUFFIX)) { TypeDef newModel = createTypeFromTemplate(model, parameters, content); if (processingEnv.getElementUtils().getTypeElement(newModel.getFullyQualifiedName()) != null) { System.err.println("Skipping: " + fileObject.getName()+ ". File already exists."); return; } if (classExists(newModel)) { System.err.println("Skipping: " + newModel.getFullyQualifiedName()+ ". Class already exists."); return; } } System.err.println("Generating: "+fileObject.getName()); try (Writer writer = fileObject.openWriter()) { new CodeGeneratorBuilder<T>() .withContext(context) .withModel(model) .withParameters(parameters) .withWriter(writer) .withTemplateContent(content) .build() .generate(); } }
Example 8
Source File: JNIWriter.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** Emit a class file for a given class. * @param c The class from which a class file is generated. */ public FileObject write(ClassSymbol c) throws IOException { String className = c.flatName().toString(); FileObject outFile = fileManager.getFileForOutput(StandardLocation.NATIVE_HEADER_OUTPUT, "", className.replaceAll("[.$]", "_") + ".h", null); Writer out = outFile.openWriter(); try { write(out, c); if (verbose) log.printVerbose("wrote.file", outFile); out.close(); out = null; } finally { if (out != null) { // if we are propogating an exception, delete the file out.close(); outFile.delete(); outFile = null; } } return outFile; // may be null if write failed }
Example 9
Source File: JNIWriter.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** Emit a class file for a given class. * @param c The class from which a class file is generated. */ public FileObject write(ClassSymbol c) throws IOException { String className = c.flatName().toString(); Location outLocn; if (multiModuleMode) { ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle; outLocn = fileManager.getLocationForModule(StandardLocation.NATIVE_HEADER_OUTPUT, msym.name.toString()); } else { outLocn = StandardLocation.NATIVE_HEADER_OUTPUT; } FileObject outFile = fileManager.getFileForOutput(outLocn, "", className.replaceAll("[.$]", "_") + ".h", null); PrintWriter out = new PrintWriter(outFile.openWriter()); try { write(out, c); if (verbose) log.printVerbose("wrote.file", outFile); out.close(); out = null; } finally { if (out != null) { // if we are propogating an exception, delete the file out.close(); outFile.delete(); outFile = null; } } return outFile; // may be null if write failed }
Example 10
Source File: BundlerClassProcessor.java From easybundler with Apache License 2.0 | 5 votes |
private void processClass(TypeElement typeElement) { // Get some metadata about the class to be processed BundlerClassInfo info = new BundlerClassInfo(typeElement); // Log a message for each class we process processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "[EasyBundler] processing class " + info); // Create a new Bundler and generate the source Bundler bundler = new Bundler(processingEnvironment, info); String javaSource = bundler.getBundlerClassSource(); try { // Create a source file FileObject file = processingEnvironment.getFiler() .createSourceFile(bundler.getQualifiedBundlerClassName(), typeElement); // Log a note for each class file created processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "[EasyBundler] Writing class file " + file.getName()); // Write the generated source Writer writer = file.openWriter(); writer.write(javaSource); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
Example 11
Source File: JNIWriter.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** Emit a class file for a given class. * @param c The class from which a class file is generated. */ public FileObject write(ClassSymbol c) throws IOException { String className = c.flatName().toString(); Location outLocn; if (multiModuleMode) { ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle; outLocn = fileManager.getLocationForModule(StandardLocation.NATIVE_HEADER_OUTPUT, msym.name.toString()); } else { outLocn = StandardLocation.NATIVE_HEADER_OUTPUT; } FileObject outFile = fileManager.getFileForOutput(outLocn, "", className.replaceAll("[.$]", "_") + ".h", null); PrintWriter out = new PrintWriter(outFile.openWriter()); try { write(out, c); if (verbose) log.printVerbose("wrote.file", outFile); out.close(); out = null; } finally { if (out != null) { // if we are propogating an exception, delete the file out.close(); outFile.delete(); outFile = null; } } return outFile; // may be null if write failed }
Example 12
Source File: ProcessorUtil.java From picocli with Apache License 2.0 | 5 votes |
static void write(String text, FileObject resource) throws IOException { Writer writer = null; try { writer = resource.openWriter(); writer.write(text); writer.flush(); } finally { if (writer != null) { writer.close(); } } }
Example 13
Source File: AnnotatedCommandSourceGeneratorProcessor.java From picocli with Apache License 2.0 | 5 votes |
private void generateCode(SourceUnit sourceUnit) throws IOException { TypeElement typeElement = (TypeElement) sourceUnit.topLevel; int count = 0; for (CommandSpec spec : sourceUnit.commandHierarchies()) { AnnotatedCommandSourceGenerator generator = new AnnotatedCommandSourceGenerator(spec); generator.setOutputPackage("generated." + generator.getOutputPackage()); String unique = count == 0 ? "" : count + ""; count++; // create a resource to prevent recursive processing of the annotations in the generated file FileObject sourceFile = processingEnv.getFiler().createResource( SOURCE_OUTPUT, generator.getOutputPackage(), typeElement.getSimpleName() + unique + ".java"); Writer writer = null; try { writer = sourceFile.openWriter(); //PrintWriter pw = new PrintWriter(writer); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); generator.writeTo(pw, ""); pw.flush(); //System.out.println(sw); writer.write(sw.toString()); writer.flush(); } finally { if (writer != null) { writer.close(); } } } }
Example 14
Source File: DocumentationProcessor.java From armeria with Apache License 2.0 | 5 votes |
private void writeProperties(String className, Properties properties) throws IOException { if (properties.isEmpty()) { return; } final FileObject resource = processingEnv.getFiler().createResource( StandardLocation.CLASS_OUTPUT, "", getFileName(className)); try (Writer writer = resource.openWriter()) { properties.store(writer, "Generated list of parameter description of REST interfaces."); } }
Example 15
Source File: MappingWriter.java From Mixin with MIT License | 5 votes |
/** * Open a writer for an output file * * @param fileName output file name (resource path) * @param description description of file being requested, for logging * @return new PrintWriter for opened resource * @throws IOException if the resource cannot be opened */ protected PrintWriter openFileWriter(String fileName, String description) throws IOException { if (fileName.matches("^.*[\\\\/:].*$")) { File outFile = new File(fileName); outFile.getParentFile().mkdirs(); this.messager.printMessage(Kind.NOTE, "Writing " + description + " to " + outFile.getAbsolutePath()); return new PrintWriter(outFile); } FileObject outResource = this.filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName); this.messager.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outResource.toUri()).getAbsolutePath()); return new PrintWriter(outResource.openWriter()); }
Example 16
Source File: BundleAnnotationProcessor.java From jlibs with Apache License 2.0 | 5 votes |
public Info(Element element, AnnotationMirror mirror) throws IOException{ pakage = ModelUtil.getPackage(element); if(ModelUtil.exists(pakage, basename+".properties")) throw new AnnotationError(element, mirror, basename+".properties in package "+pakage+" already exists in source path"); FileObject resource = Environment.get().getFiler().createResource(StandardLocation.CLASS_OUTPUT, pakage, basename+".properties"); props = new BufferedWriter(resource.openWriter()); }
Example 17
Source File: PackageReferenceValidator.java From deptective with Apache License 2.0 | 5 votes |
@Override public void onCompletingCompilation() { log.useSource(null); List<Cycle<IdentifiableComponent>> cycles = GraphUtils.detectCycles(allowedPackageDependencies.getComponents()); if (!cycles.isEmpty()) { String cyclesAsString = "- " + cycles.stream() .map(Cycle::toString) .collect(Collectors.joining("," + System.lineSeparator() + "- ")); log.report(cycleReportingPolicy, DeptectiveMessages.CYCLE_IN_ARCHITECTURE, cyclesAsString); } if (!createDotFile) { return; } actualPackageDependencies.updateFromCycles(cycles); DotSerializer serializer = new DotSerializer(); actualPackageDependencies.build().serialize(serializer); try { FileObject output = jfm.getFileForOutput(StandardLocation.SOURCE_OUTPUT, "", "deptective.dot", null); log.note(DeptectiveMessages.GENERATED_DOT_REPRESENTATION, output.toUri()); Writer writer = output.openWriter(); writer.append(serializer.serialize()); writer.close(); } catch (IOException e) { throw new RuntimeException("Failed to write deptective.dot file", e); } }
Example 18
Source File: ApiGeneratorProcessor.java From flo with Apache License 2.0 | 5 votes |
private void writeApiInterface( GenerateTaskBuilder genTaskBuilder, Name packageName, String interfaceName) throws IOException { final Map<String, Object> data = new HashMap<>(); data.put("packageName", packageName); data.put("interfaceName", interfaceName); data.put("genFn", IntStream.rangeClosed(0, genTaskBuilder.upTo()) .mapToObj(this::fn).toArray()); data.put("genBuilder", IntStream.range(1, genTaskBuilder.upTo()) .mapToObj(this::builder).toArray()); final String output = engine.getMustache("TaskBuilder").render(data); final String outputScala = engine.getMustache("ScalaApi").render(data); if (!genTaskBuilder.scala()) { final String fileName = packageName + "." + interfaceName; final JavaFileObject filerSourceFile = filer.createSourceFile(fileName, processingElement); try (final Writer writer = filerSourceFile.openWriter()) { writer.write(output); } } else { final FileObject scalaFile = filer.createResource( StandardLocation.SOURCE_OUTPUT, packageName, "ScalaApi.scala", processingElement); try (final Writer writer = scalaFile.openWriter()) { writer.write(outputScala); } } }
Example 19
Source File: PluginAnnotationProcessor.java From Velocity with MIT License | 4 votes |
@Override public synchronized boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { return false; } for (Element element : roundEnv.getElementsAnnotatedWith(Plugin.class)) { if (element.getKind() != ElementKind.CLASS) { environment.getMessager() .printMessage(Diagnostic.Kind.ERROR, "Only classes can be annotated with " + Plugin.class.getCanonicalName()); return false; } Name qualifiedName = ((TypeElement) element).getQualifiedName(); if (Objects.equals(pluginClassFound, qualifiedName.toString())) { if (!warnedAboutMultiplePlugins) { environment.getMessager() .printMessage(Diagnostic.Kind.WARNING, "Velocity does not yet currently support " + "multiple plugins. We are using " + pluginClassFound + " for your plugin's main class."); warnedAboutMultiplePlugins = true; } return false; } Plugin plugin = element.getAnnotation(Plugin.class); if (!SerializedPluginDescription.ID_PATTERN.matcher(plugin.id()).matches()) { environment.getMessager().printMessage(Diagnostic.Kind.ERROR, "Invalid ID for plugin " + qualifiedName + ". IDs must start alphabetically, have alphanumeric characters, and can " + "contain dashes or underscores."); return false; } // All good, generate the velocity-plugin.json. SerializedPluginDescription description = SerializedPluginDescription .from(plugin, qualifiedName.toString()); try { FileObject object = environment.getFiler() .createResource(StandardLocation.CLASS_OUTPUT, "", "velocity-plugin.json"); try (Writer writer = new BufferedWriter(object.openWriter())) { new Gson().toJson(description, writer); } pluginClassFound = qualifiedName.toString(); } catch (IOException e) { environment.getMessager() .printMessage(Diagnostic.Kind.ERROR, "Unable to generate plugin file"); } } return false; }
Example 20
Source File: JavacFiler.java From java-n-IDE-for-Android with Apache License 2.0 | 4 votes |
/** * @param fileObject the fileObject to be written to * @param typeName name of source file or {@code null} if just a * text file */ FilerWriter(String typeName, FileObject fileObject) throws IOException { super(fileObject.openWriter()); this.typeName = typeName; this.fileObject = fileObject; }