Java Code Examples for javax.tools.FileObject#openOutputStream()

The following examples show how to use javax.tools.FileObject#openOutputStream() . 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: IncrementalAnnotationProcessorProcessor.java    From gradle-incap-helper with Apache License 2.0 6 votes vote down vote up
private void generateConfigFiles() {
  Filer filer = processingEnv.getFiler();
  try {
    // TODO: merge with an existing file (in case of incremental compilation, in a
    // non-incremental-compile-aware environment; e.g. Maven)
    FileObject fileObject =
        filer.createResource(StandardLocation.CLASS_OUTPUT, "", RESOURCE_FILE);
    try (PrintWriter out =
        new PrintWriter(
            new OutputStreamWriter(fileObject.openOutputStream(), StandardCharsets.UTF_8))) {
      processors.forEach((processor, type) -> out.println(processor + "," + type.name()));
      if (out.checkError()) {
        throw new IOException("Error writing to the file");
      }
    }
  } catch (IOException e) {
    fatalError("Unable to create " + RESOURCE_FILE + ", " + e);
  }
}
 
Example 2
Source File: NaluProcessor.java    From nalu with Apache License 2.0 6 votes vote down vote up
private void store(MetaModel model)
    throws ProcessorException {
  Gson gson = new Gson();
  try {
    FileObject fileObject = processingEnv.getFiler()
                                         .createResource(StandardLocation.CLASS_OUTPUT,
                                                         "",
                                                         this.createRelativeFileName());
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(fileObject.openOutputStream(),
                                                                     UTF_8));
    printWriter.print(gson.toJson(model));
    printWriter.flush();
    printWriter.close();
  } catch (IOException e) {
    throw new ProcessorException("NaluProcessor: Unable to write file: >>" + this.createRelativeFileName() + "<< -> exception: " + e.getMessage());
  }
}
 
Example 3
Source File: ModuleConfig.java    From core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void writeModuleFile(Set<String> inheritFrom, Map<String, String> properties) {
    try {
        Map<String, Object> model = new HashMap<>();
        model.put("modules", inheritFrom);
        model.put("properties", properties);

        FileObject sourceFile = filer.createResource(StandardLocation.SOURCE_OUTPUT, MODULE_PACKAGE, filename);
        OutputStream output = sourceFile.openOutputStream();
        new TemplateProcessor().process(template, model, output);
        output.flush();
        output.close();
        System.out.println("Written GWT module to " + sourceFile.toUri().toString());
    } catch (IOException e) {
        throw new RuntimeException("Failed to create file", e);
    }
}
 
Example 4
Source File: AbstractServiceProviderProcessor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void writeServices() {
    for (Map.Entry<Filer,Map<String,SortedSet<ServiceLoaderLine>>> outputFiles : outputFilesByProcessor.entrySet()) {
        Filer filer = outputFiles.getKey();
        for (Map.Entry<String,SortedSet<ServiceLoaderLine>> entry : outputFiles.getValue().entrySet()) {
            try {
                FileObject out = filer.createResource(StandardLocation.CLASS_OUTPUT, "", entry.getKey(),
                        originatingElementsByProcessor.get(filer).get(entry.getKey()).toArray(new Element[0]));
                OutputStream os = out.openOutputStream();
                try {
                    PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
                    for (ServiceLoaderLine line : entry.getValue()) {
                        line.write(w);
                    }
                    w.flush();
                    w.close();
                } finally {
                    os.close();
                }
            } catch (IOException x) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Failed to write to " + entry.getKey() + ": " + x.toString());
            }
        }
    }
}
 
Example 5
Source File: Gen.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 6
Source File: Gen.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 7
Source File: Gen.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 8
Source File: PluggableProcessor.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void generateServiceFiles(Filer filer)
{
    for(String serviceName : factoryImplementations.keySet())
    {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.NOTE, "Generating service file for " + serviceName);

        String relativeName = "META-INF/services/" + serviceName;
        loadExistingServicesFile(filer, serviceName);
        try
        {
            FileObject serviceFile = filer.createResource(StandardLocation.CLASS_OUTPUT, "", relativeName);
            try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(serviceFile.openOutputStream(), "UTF-8")))
            {
                for (String headerLine : License.LICENSE)
                {
                    pw.println("#" + headerLine);
                }
                pw.println("#");
                pw.println("# Note: Parts of this file are auto-generated from annotations.");
                pw.println("#");
                for (String implementation : factoryImplementations.get(serviceName))
                {
                    pw.println(implementation);
                }
            }
        }
        catch (IOException e)
        {
            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "Failed to write services file: "
                                  + relativeName
                                  + " - "
                                  + e.getLocalizedMessage()
                                 );
        }
    }
}
 
Example 9
Source File: Gen.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException | NoSuchFileException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 10
Source File: Gen.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 11
Source File: Gen.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 12
Source File: PluginProcessor.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void writeServiceFile(String pkgName) throws IOException {
    final FileObject fileObject = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, Strings.EMPTY,
            SERVICE_FILE_NAME);
    try (final PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fileObject.openOutputStream(), UTF_8)))) {
        writer.println(createFqcn(pkgName));
    }
}
 
Example 13
Source File: ExtensionAnnotationProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void writeListResourceFile(Collection<String> crListClasses, FileObject listResource) throws IOException {
    try (OutputStream os = listResource.openOutputStream()) {
        try (BufferedOutputStream bos = new BufferedOutputStream(os)) {
            try (OutputStreamWriter osw = new OutputStreamWriter(bos, StandardCharsets.UTF_8)) {
                try (BufferedWriter bw = new BufferedWriter(osw)) {
                    for (String item : crListClasses) {
                        bw.write(item);
                        bw.newLine();
                    }
                }
            }
        }
    }
}
 
Example 14
Source File: PipelineAnnotationsProcessor.java    From datacollector-api with Apache License 2.0 5 votes vote down vote up
private void generateFile(String fileName, List<String> elements, String prefix, String postfix) {
  try {
    FileObject resource = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
    try (Writer writer = new OutputStreamWriter(resource.openOutputStream())) {
      writer.write(toJson(elements, prefix, postfix));
    }
  } catch (IOException e) {
    printError("Could not create/write '{}' file: {}", e.toString());
  }
}
 
Example 15
Source File: AnnotationProcessor.java    From buck with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: Gen.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 17
Source File: JServiceCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
private void writeServices(
    final Filer filer, final String resourceFile, final Collection<String> services
) throws Exception {
    final FileObject file = createResource(filer, resourceFile);
    final OutputStream outputStream = file.openOutputStream();
    try {
        IOUtils.writeLines(services, "\n", outputStream, StandardCharsets.UTF_8);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}
 
Example 18
Source File: JavacFiler.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param typeName name of class or {@code null} if just a
 * binary file
 */
FilerOutputStream(String typeName, FileObject fileObject) throws IOException {
    super(fileObject.openOutputStream());
    this.typeName = typeName;
    this.fileObject = fileObject;
}
 
Example 19
Source File: JavacFiler.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * @param typeName name of class or {@code null} if just a
 * binary file
 */
FilerOutputStream(String typeName, FileObject fileObject) throws IOException {
    super(fileObject.openOutputStream());
    this.typeName = typeName;
    this.fileObject = fileObject;
}
 
Example 20
Source File: PropertiesDocReader.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void writeDefaultMessages()
{
	Properties defaultMessages = new Properties();
	BreakIterator sentenceBreaks = BreakIterator.getSentenceInstance(Locale.US);
	for (CompiledPropertyMetadata prop : properties.getProperties())
	{
		String descriptionMessage = PropertyMetadataConstants.PROPERTY_DESCRIPTION_PREFIX + prop.getName();
		if (propertyMessages == null || !propertyMessages.containsKey(descriptionMessage))
		{
			Element docNode = propertyDocNodes.get(prop.getName());
			if (docNode != null)
			{
				String docText = docNode.getTextContent();
				sentenceBreaks.setText(docText);
				int first = sentenceBreaks.first();
				int next = sentenceBreaks.next();
				
				String firstSentence = docText.substring(first, next);
				firstSentence = PATTERN_LEADING_WHITE_SPACE.matcher(firstSentence).replaceAll("");
				firstSentence = PATTERN_TRAILING_WHITE_SPACE.matcher(firstSentence).replaceAll("");
				
				defaultMessages.setProperty(descriptionMessage, firstSentence);
			}
		}
	}
	
	if (!defaultMessages.isEmpty())
	{
		try
		{
			FileObject res = environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, 
					"", properties.getMessagesName() + PropertyMetadataConstants.MESSAGES_DEFAULTS_SUFFIX, 
					(javax.lang.model.element.Element[]) null);
			try (OutputStream out = res.openOutputStream())
			{
				//TODO lucianc preserve order
				defaultMessages.store(out, null);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException(e);
		}
	}
}