Example usage for java.nio.file StandardOpenOption CREATE

List of usage examples for java.nio.file StandardOpenOption CREATE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption CREATE.

Prototype

StandardOpenOption CREATE

To view the source code for java.nio.file StandardOpenOption CREATE.

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:org.apache.tika.parser.DigestingParserTest.java

private void testMulti(Path tmp, int fileLength, int markLimit, boolean useTikaInputStream) throws IOException {

    OutputStream os = new BufferedOutputStream(Files.newOutputStream(tmp, StandardOpenOption.CREATE));

    for (int i = 0; i < fileLength; i++) {
        os.write(random.nextInt());/* w  w w .j  a  v a 2s. c o m*/
    }
    os.flush();
    os.close();

    Metadata truth = new Metadata();
    addTruth(tmp, CommonsDigester.DigestAlgorithm.MD5, truth);
    addTruth(tmp, CommonsDigester.DigestAlgorithm.SHA1, truth);
    addTruth(tmp, CommonsDigester.DigestAlgorithm.SHA512, truth);

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, CommonsDigester.DigestAlgorithm.SHA512,
            CommonsDigester.DigestAlgorithm.SHA1, CommonsDigester.DigestAlgorithm.MD5);

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, CommonsDigester.DigestAlgorithm.MD5,
            CommonsDigester.DigestAlgorithm.SHA1);

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, CommonsDigester.DigestAlgorithm.SHA1,
            CommonsDigester.DigestAlgorithm.SHA512, CommonsDigester.DigestAlgorithm.MD5);

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, CommonsDigester.DigestAlgorithm.SHA1);

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, CommonsDigester.DigestAlgorithm.MD5);

}

From source file:com.hpe.caf.worker.testing.validation.ReferenceDataValidator.java

@Override
public boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) {

    if (testedPropertyValue == null && validatorPropertyValue == null)
        return true;

    ObjectMapper mapper = new ObjectMapper();

    ContentFileTestExpectation expectation = mapper.convertValue(validatorPropertyValue,
            ContentFileTestExpectation.class);

    ReferencedData referencedData = mapper.convertValue(testedPropertyValue, ReferencedData.class);

    InputStream dataStream;/*from ww w  . j  a  va 2s . com*/

    if (expectation.getExpectedContentFile() == null && expectation.getExpectedSimilarityPercentage() == 0) {
        return true;
    }

    try {
        System.out.println("About to retrieve content for " + referencedData.toString());
        dataStream = ContentDataHelper.retrieveReferencedData(dataStore, codec, referencedData);
        System.out.println("Finished retrieving content for " + referencedData.toString());
    } catch (DataSourceException e) {
        e.printStackTrace();
        System.err.println("Failed to acquire referenced data.");
        e.printStackTrace();
        TestResultHelper.testFailed("Failed to acquire referenced data. Exception message: " + e.getMessage(),
                e);
        return false;
    }
    try {
        String contentFileName = expectation.getExpectedContentFile();
        Path contentFile = Paths.get(contentFileName);
        if (Files.notExists(contentFile) && !Strings.isNullOrEmpty(testSourcefileBaseFolder)) {
            contentFile = Paths.get(testSourcefileBaseFolder, contentFileName);
        }

        if (Files.notExists(contentFile)) {
            contentFile = Paths.get(testDataFolder, contentFileName);
        }

        byte[] expectedFileBytes = Files.readAllBytes(contentFile);

        if (expectation.getComparisonType() == ContentComparisonType.TEXT) {

            String actualText = IOUtils.toString(dataStream, StandardCharsets.UTF_8);
            String expectedText = new String(expectedFileBytes, StandardCharsets.UTF_8);

            if (expectation.getExpectedSimilarityPercentage() == 100) {
                boolean equals = actualText.equals(expectedText);
                if (!equals) {
                    String message = "Expected and actual texts were different.\n\n*** Expected Text ***\n"
                            + expectedText + "\n\n*** Actual Text ***\n" + actualText;
                    System.err.println(message);
                    if (throwOnValidationFailure)
                        TestResultHelper.testFailed(message);
                    return false;
                }
                return true;
            }

            double similarity = ContentComparer.calculateSimilarityPercentage(expectedText, actualText);

            System.out.println("Compared text similarity:" + similarity + "%");

            if (similarity < expectation.getExpectedSimilarityPercentage()) {
                String message = "Expected similarity of " + expectation.getExpectedSimilarityPercentage()
                        + "% but actual similarity was " + similarity + "%";
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        } else {
            byte[] actualDataBytes = IOUtils.toByteArray(dataStream);
            boolean equals = Arrays.equals(actualDataBytes, expectedFileBytes);
            if (!equals) {
                String actualContentFileName = contentFile.getFileName() + "_actual";
                Path actualFilePath = Paths.get(contentFile.getParent().toString(), actualContentFileName);
                Files.deleteIfExists(actualFilePath);
                Files.write(actualFilePath, actualDataBytes, StandardOpenOption.CREATE);
                String message = "Data returned was different than expected for file: " + contentFileName
                        + "\nActual content saved in file: " + actualFilePath.toString();
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        TestResultHelper.testFailed("Error while processing reference data! " + e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:de.huberlin.wbi.cuneiform.core.cre.LocalThread.java

@Override
public void run() {

    Path scriptFile, location, successMarker, reportFile, callLocation, stdErrFile, stdOutFile;
    // Path lockMarker;
    Process process;/*from   w ww .j  a  v  a 2s . c  o  m*/
    int exitValue;
    Set<JsonReportEntry> report;
    JsonReportEntry entry;
    String line;
    StringBuffer buf;
    Path srcPath, destPath;
    ProcessBuilder processBuilder;
    Ticket ticket;
    String script, stdOut, stdErr;
    long tic, toc;
    JSONObject obj;
    Message msg;
    Charset cs;
    int trial;
    boolean suc;
    Exception ex;

    if (log.isDebugEnabled())
        log.debug("Starting up local thread for ticket " + invoc.getTicketId() + ".");

    if (invoc == null)
        throw new NullPointerException("Invocation must not be null.");

    ticket = invoc.getTicket();
    process = null;
    stdOut = null;
    stdErr = null;
    // lockMarker = null;
    script = null;
    successMarker = null;
    cs = Charset.forName("UTF-8");

    try {

        callLocation = Paths.get(System.getProperty("user.dir"));
        location = buildDir.resolve(String.valueOf(invoc.getTicketId()));
        // lockMarker = location.resolve( Invocation.LOCK_FILENAME );
        successMarker = location.resolve(Invocation.SUCCESS_FILENAME);
        reportFile = location.resolve(Invocation.REPORT_FILENAME);
        script = invoc.toScript();

        // if( Files.exists( lockMarker ) )
        //   throw new IOException( "Lock held on ticket "+invoc.getTicketId() );

        if (!Files.exists(successMarker)) {

            deleteIfExists(location);
            Files.createDirectories(location);

            // Files.createFile( lockMarker );

            scriptFile = invoc.getExecutablePath(location);

            Files.createFile(scriptFile,
                    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---")));

            // write executable script
            try (BufferedWriter writer = Files.newBufferedWriter(scriptFile, cs, StandardOpenOption.CREATE)) {
                writer.write(script);
            }

            // write executable log entry
            try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.CREATE)) {
                writer.write(ticket.getExecutableLogEntry().toString());
                writer.write('\n');
            }

            for (String filename : invoc.getStageInList()) {

                if (filename.charAt(0) == '/')
                    throw new UnsupportedOperationException("Absolute path encountered '" + filename + "'.");

                srcPath = centralRepo.resolve(filename);
                destPath = location.resolve(filename);

                if (!Files.exists(srcPath)) {

                    srcPath = callLocation.resolve(filename);
                    if (log.isTraceEnabled())
                        log.trace("Resolving relative path '" + srcPath + "'.");
                } else

                if (log.isTraceEnabled())
                    log.trace("Resolving path to central repository '" + srcPath + "'.");

                if (log.isTraceEnabled())
                    log.trace("Trying to create symbolic link from '" + srcPath + "' to '" + destPath + "'.");

                if (!Files.exists(destPath.getParent()))
                    Files.createDirectories(destPath.getParent());

                Files.createSymbolicLink(destPath, srcPath);

            }

            // run script
            processBuilder = new ProcessBuilder(invoc.getCmd());
            processBuilder.directory(location.toFile());

            stdOutFile = location.resolve(Invocation.STDOUT_FILENAME);
            stdErrFile = location.resolve(Invocation.STDERR_FILENAME);

            processBuilder.redirectOutput(stdOutFile.toFile());
            processBuilder.redirectError(stdErrFile.toFile());

            trial = 1;
            suc = false;
            ex = null;
            tic = System.currentTimeMillis();
            do {
                try {
                    process = processBuilder.start();

                    suc = true;
                } catch (IOException e) {

                    ex = e;
                    if (log.isWarnEnabled())
                        log.warn("Unable to start process on trial " + (trial++) + " Waiting " + WAIT_INTERVAL
                                + "ms: " + e.getMessage());
                    Thread.sleep(WAIT_INTERVAL);
                }
            } while (suc == false && trial <= MAX_TRIALS);

            if (process == null) {

                ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, ex, script, null, null));
                // Files.delete( lockMarker );
                return;
            }

            exitValue = process.waitFor();
            toc = System.currentTimeMillis();

            try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.APPEND)) {

                obj = new JSONObject();
                obj.put(JsonReportEntry.LABEL_REALTIME, toc - tic);
                entry = invoc.createJsonReportEntry(tic, JsonReportEntry.KEY_INVOC_TIME, obj);

                writer.write(entry.toString());
                writer.write('\n');

                try (BufferedReader reader = Files.newBufferedReader(stdOutFile, cs)) {

                    buf = new StringBuffer();
                    while ((line = reader.readLine()) != null)
                        buf.append(line).append('\n');

                    stdOut = buf.toString();

                    if (!stdOut.isEmpty()) {
                        entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDOUT, stdOut);
                        writer.write(entry.toString());
                        writer.write('\n');
                    }
                }

                try (BufferedReader reader = Files.newBufferedReader(stdErrFile, cs)) {

                    buf = new StringBuffer();
                    while ((line = reader.readLine()) != null)
                        buf.append(line).append('\n');

                    stdErr = buf.toString();
                    if (!stdErr.isEmpty()) {

                        entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDERR, stdErr);
                        writer.write(entry.toString());
                        writer.write('\n');
                    }
                }

                if (exitValue == 0)

                    Files.createFile(successMarker);

                else {

                    ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, null, script, stdOut, stdErr));
                    // Files.delete( lockMarker );
                    return;

                }
            }

        }

        // gather report
        report = new HashSet<>();
        try (BufferedReader reader = Files.newBufferedReader(reportFile, cs)) {

            while ((line = reader.readLine()) != null) {

                line = line.trim();

                if (line.isEmpty())
                    continue;

                entry = new JsonReportEntry(line);

                // If the report comes from the hard cache then the run id
                // is different from the run id of this invocation. This is
                // corrected here.
                entry.setRunId(invoc.getRunId());

                report.add(entry);
            }

        }

        invoc.evalReport(report);

        // create link in central data repository
        for (String f : invoc.getStageOutList()) {

            srcPath = location.resolve(f);
            destPath = centralRepo.resolve(f);

            if (Files.exists(destPath))
                continue;

            if (log.isTraceEnabled())
                log.trace("Creating link from " + srcPath + " to " + destPath + ".");

            Files.createSymbolicLink(destPath, srcPath);
        }

        ticketSrc.sendMsg(new TicketFinishedMsg(cre, invoc.getTicket(), report));

        if (log.isTraceEnabled())
            log.trace("Local thread ran through without exception.");

        // Files.deleteIfExists( lockMarker );

    } catch (InterruptedException e) {

        if (log.isTraceEnabled())
            log.trace("Local thread has been interrupted.");
    } catch (Exception e) {

        if (log.isTraceEnabled())
            log.trace("Something went wrong. Deleting success marker if present.");

        if (successMarker != null)
            try {
                Files.deleteIfExists(successMarker);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        msg = new TicketFailedMsg(cre, ticket, e, script, stdOut, stdErr);

        ticketSrc.sendMsg(msg);

    } finally {

        if (process != null) {

            if (log.isDebugEnabled())
                log.debug("Stopping local thread for ticket " + invoc.getTicketId() + ".");

            process.destroy();
        }
    }
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static void setupSolrCloudConfigsets(String zkHost) {
    // before anything else, try to get a zookeeper client
    CloudSolrClient zkClient = new CloudSolrClient(zkHost);

    // get resources and copy them to a temporary directory
    Path databaseDir = null;/*from   ww  w  . j  a v  a  2s.c o m*/
    Path tableDir = null;
    Path savedSearchesDir = null;
    try {
        final File jarFile = new File(
                SolrManager.class.getProtectionDomain().getCodeSource().getLocation().toURI());

        // if it is a directory the application in being run from an IDE
        // in that case do not setup (assuming setup is done)
        if (!jarFile.isDirectory()) {
            databaseDir = Files.createTempDirectory("dbv_db_");
            tableDir = Files.createTempDirectory("dbv_tab_");
            savedSearchesDir = Files.createTempDirectory("dbv_tab_");
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();

                String nameWithoutOriginPart = null;
                Path destination = null;
                if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE.length() + 1);
                    destination = databaseDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE.length() + 1);
                    destination = tableDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE.length() + 1);
                    destination = savedSearchesDir;
                } else {
                    continue;
                }

                Path output = destination.resolve(nameWithoutOriginPart);
                if (name.endsWith("/")) {
                    Files.createDirectories(output);
                } else {
                    InputStream inputStream = SolrManager.class.getResourceAsStream("/" + name);
                    output = Files.createFile(output);
                    OutputStream outputStream = Files.newOutputStream(output, StandardOpenOption.CREATE,
                            StandardOpenOption.WRITE);
                    IOUtils.copy(inputStream, outputStream);
                    inputStream.close();
                    outputStream.close();
                }
            }
            jar.close();
        }
    } catch (IOException | URISyntaxException e) {
        LOGGER.error("Could not extract Solr configset", e);
        if (databaseDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(databaseDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
            }
        }
        if (tableDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(tableDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
            }
        }
        databaseDir = null;
        tableDir = null;
    }

    // copy configurations to solr
    if (databaseDir != null && tableDir != null) {
        try {
            zkClient.uploadConfig(databaseDir, ViewerSafeConstants.SOLR_CONFIGSET_DATABASE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading database config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(tableDir, ViewerSafeConstants.SOLR_CONFIGSET_TABLE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading table config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(savedSearchesDir, ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading saved searches config to solr cloud", e);
        }

        try {
            FileUtils.deleteDirectoryRecursive(databaseDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(tableDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(savedSearchesDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + savedSearchesDir, e1);
        }
    }

    try {
        zkClient.close();
    } catch (IOException e) {
        LOGGER.debug("IO error closing connection to solr cloud", e);
    }
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

private String concatenateCss(ServletContext context, Path path, Path outFile)
        throws FileNotFoundException, IOException {
    DirectoryStream<Path> cssFiles = Files.newDirectoryStream(path, "*.css");
    if (Files.exists(outFile)) {
        Files.delete(outFile);//from   w w w. j a  v a2s .c  om
    }
    List<Path> sortedFiles = new ArrayList<>();
    for (Path cssFile : cssFiles) {
        sortedFiles.add(cssFile);
    }

    Collections.sort(sortedFiles, new PathByFileNameComparator());

    for (Path cssFile : sortedFiles) {
        Files.write(outFile, Files.readAllBytes(cssFile), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    byte[] cssData;
    if (Files.exists(outFile)) {
        cssData = Files.readAllBytes(outFile);
    } else {
        //read from classpath
        InputStream is = context.getResourceAsStream(ALL_MIN_CSS);
        cssData = IOUtils.toByteArray(is);
    }
    String css = new String(cssData, Constants.UTF8);
    return css;
}

From source file:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public synchronized void saveXMLConfigProperties(Properties xmlConfigProperties) throws IOException {

    if (xmlConfigProperties != null) {

        try (OutputStream xmlConfigPropertiesOutputStream = Files.newOutputStream(
                Paths.get(XMLConfig.getBaseConfigPath(), "XMLConfig.properties"), StandardOpenOption.WRITE,
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
            xmlConfigProperties.store(xmlConfigPropertiesOutputStream, null);
        }/*from w w  w.ja v a  2s .com*/
    }
}

From source file:org.apache.tika.parser.BouncyCastleDigestingParserTest.java

private void testMulti(Path tmp, int fileLength, int markLimit, boolean useTikaInputStream) throws IOException {

    OutputStream os = new BufferedOutputStream(Files.newOutputStream(tmp, StandardOpenOption.CREATE));

    for (int i = 0; i < fileLength; i++) {
        os.write(random.nextInt());/*from   www.j  av  a2s .co  m*/
    }
    os.flush();
    os.close();

    Metadata truth = new Metadata();
    addTruth(tmp, "MD5", truth);
    addTruth(tmp, "SHA1", truth);
    addTruth(tmp, "SHA512", truth);

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, "SHA512", "SHA1", "MD5");
    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, "MD5", "SHA1");

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, "SHA1", "SHA512", "MD5");
    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, "SHA1");

    checkMulti(truth, tmp, fileLength, markLimit, useTikaInputStream, "MD5");

}

From source file:org.bonitasoft.web.designer.workspace.WorkspaceTest.java

@Test
public void should_copy_widget_file_if_it_is_already_in_widget_repository_folder_with_a_former_version()
        throws Exception {
    mockWidgetsBasePath(Paths.get("src/test/resources/workspace/widgets"));

    //We create the widget files
    Path labelDir = temporaryFolder.newFolderPath("widgets", "pbLabel");
    Path labelFile = labelDir.resolve("pbLabel.json");
    byte[] fileContent = "{\"id\":\"pbLabel\", \"template\": \"<div>Hello</div>\", \"designerVersion\": \"1.0.1\"}"
            .getBytes(StandardCharsets.UTF_8);
    write(labelFile, fileContent, StandardOpenOption.CREATE);

    workspace.initialize();//from   w w w  .j a  v a2  s .c o  m

    String newLabelContent = new String(
            readAllBytes(pathResolver.getWidgetsRepositoryPath().resolve("pbLabel/pbLabel.json")));
    String oldLabelContent = new String(
            readAllBytes(Paths.get("src/test/resources/workspace/widgets/pbLabel/pbLabel.json")));
    assertThat(newLabelContent).isNotEqualTo(oldLabelContent);
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

/** {@inheritDoc} */
@Override//from w  ww . j a  v  a 2s  . co  m
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("Skipping type transformation!");
        return;
    }

    trackExecution("start");

    final ClassLoader classLoader = getClassloader();
    final List<ClassFileTransformer> transformers = getClassFileTransformers(classLoader);

    List<File> classFiles = FileUtils.getFiles(project.getBuild().getOutputDirectory(),
            f -> f.getAbsolutePath().endsWith(".class"));
    getLog().debug("Found class files for processing: "
            + classFiles.stream().map(f -> f.getName()).collect(Collectors.joining(", ")));

    if (CollectionUtils.isNotEmpty(transformers)) {
        if (CollectionUtils.isNotEmpty(classFiles)) {
            getLog().info(String.format("Transforming %s classes", classFiles.size()));

            for (final File f : classFiles) {
                if (f.getName().endsWith(Constants.CLASS_EXTENSION)) {
                    String relativeClassFilePath = StringUtils.remove(f.getPath(),
                            project.getBuild().getOutputDirectory());
                    relativeClassFilePath = StringUtils.removeStart(relativeClassFilePath, "/");
                    final String className = relativeClassFilePath.substring(0,
                            relativeClassFilePath.length() - Constants.CLASS_EXTENSION.length());

                    trackExecution("Loading class: " + f.getAbsolutePath());

                    byte[] byteCode;
                    try {
                        byteCode = Files.readAllBytes(f.toPath());
                    } catch (final IOException e) {
                        String message = String.format("Can't read bytecode for class %s", className);
                        buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                        throw new IllegalStateException(message, e);
                    }

                    trackExecution("Loaded class: " + f.getAbsolutePath());

                    for (final ClassFileTransformer t : transformers) {
                        try {

                            // log exceptions into separate folder, to be able to inspect them even if Eclipse swallows them ...
                            if (t instanceof AbstractBaseClassTransformer) {
                                ((AbstractBaseClassTransformer) t).setErrorLogger(this::logError);
                            }

                            // returns null if nothing has been transformed
                            byteCode = t.transform(classLoader, className, null, null, byteCode);
                        } catch (final Exception e) {
                            String exception = "Exception during transformation of class: "
                                    + f.getAbsolutePath() + "\n" + e.getMessage();
                            trackExecution(exception);
                            String message = String.format("Can't transform class %s, transformer %s: %s",
                                    className, t.getClass().getSimpleName(), ExceptionUtils.getStackTrace(e));
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new MojoExecutionException(exception, e);
                        }
                    }

                    if (byteCode != null && byteCode.length > 0) {
                        try {
                            Files.write(f.toPath(), byteCode, StandardOpenOption.CREATE,
                                    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

                            trackExecution("Saved transformed class: " + f.getAbsolutePath());
                        } catch (final IOException e) {
                            String message = "Could not write modified class: " + relativeClassFilePath;
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new IllegalStateException(message);
                        } finally {
                            buildContext.refresh(f);
                            getLog().info("Applied transformation to type: " + f.getAbsolutePath());
                        }
                    } else {
                        trackExecution("No changes made for class: " + f.getAbsolutePath());
                        getLog().debug("No transformation was applied to type: " + f.getAbsolutePath());
                    }
                }
            }
        } else {
            getLog().info("No class files found");
        }

        trackExecution("All classes in build output folder transformed");

        if (includeJars) {
            final String packaging = project.getPackaging();
            final Artifact artifact = project.getArtifact();

            if ("jar".equals(packaging) && artifact != null) {
                try {
                    final File source = artifact.getFile();

                    if (source.isFile()) {
                        final File destination = new File(source.getParent(), "instrument.jar");

                        final JarTransformer transformer = new JarTransformer(getLog(), classLoader,
                                Arrays.asList(source), transformers);
                        transformer.transform(destination);

                        final File sourceRename = new File(source.getParent(),
                                "notransform-" + source.getName());

                        if (source.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    source.toString(), sourceRename.toString()));
                        }

                        if (destination.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    destination.toString(), sourceRename.toString()));
                        }

                        buildContext.refresh(destination);
                    }
                } catch (final Exception e) {
                    buildContext.addMessage(artifact.getFile(), 0, 0, e.getMessage(),
                            BuildContext.SEVERITY_ERROR, e);
                    throw new MojoExecutionException(e.getMessage(), e);
                }
            } else {
                getLog().debug(String.format("Artifact %s not a jar file",
                        artifact != null ? (artifact.getGroupId() + ":" + artifact.getArtifactId())
                                : "<null>"));
            }
        }
    } else {
        getLog().info("No class transformers configured");
    }
}

From source file:org.jboss.pull.player.LabelProcessor.java

/**
 * Processes the pull requests {@link #add(org.jboss.dmr.ModelNode) added}.
 * <p/>//from ww w  . jav  a 2s  .  c om
 * This should normally only be invoked once as it makes API calls to GitHub.
 */
void process() {
    try {
        // Get all the open issues to lessen the hits to the API
        final ModelNode openIssues = getIssues();

        // Process each issue in the model
        for (Property property : issuesModel.asPropertyList()) {
            final ModelNode value = property.getValue();
            // Get the PR url
            final String prUrl = value.get("pull_request_url").asString();
            if (openIssues.hasDefined(prUrl)) {
                final ModelNode openIssue = openIssues.get(prUrl);

                // Get the current labels
                final List<String> currentLabels = getLabels(openIssue);
                // If no labels are present, we can delete the issue
                if (currentLabels.isEmpty()) {
                    issuesModel.remove(property.getName());
                } else {
                    boolean changeRequired = false;

                    // Process the labels only requiring a change if the label was defined in the configuration
                    final List<String> newLabels = new ArrayList<>();
                    for (String label : currentLabels) {
                        if (labels.isRemovable(label)) {
                            final String newLabel = labels.getReplacement(label);
                            if (newLabel != null) {
                                newLabels.add(newLabel);
                            }
                            changeRequired = true;
                        } else {
                            newLabels.add(label);
                        }
                    }
                    // Check that the PR has been changed and a change is required
                    if (changeRequired && value.hasDefined("new-sha")) {
                        final String issueUrl = value.get("issue_url").asString();
                        // Set the new labels
                        setLabels(issueUrl, newLabels);
                        // Node needs to be removed
                        issuesModel.remove(property.getName());
                    } else if (!changeRequired) {
                        // No change in labels has been required, remove the issue
                        issuesModel.remove(property.getName());
                    }
                }
            } else {
                // The issue/PR may be closed, we can just delete it
                issuesModel.remove(property.getName());
            }
        }

        // Write the issues out to a file
        try (final PrintWriter writer = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.SYNC,
                StandardOpenOption.CREATE))) {
            issuesModel.writeJSONString(writer, false);
        }
    } catch (IOException e) {
        e.printStackTrace(err);
    }
}