Example usage for java.io File toPath

List of usage examples for java.io File toPath

Introduction

In this page you can find the example usage for java.io File toPath.

Prototype

public Path toPath() 

Source Link

Document

Returns a Path java.nio.file.Path object constructed from this abstract path.

Usage

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

public static JSONObject createThumbnail(File projectDir, File pyramidDir, String imageName,
        BufferedImage refImage) throws IOException, JSONException {
    final Path projectScope = projectDir.toPath();
    final BufferedImage tmbImage = toThumbnailSize(refImage);

    final File thumbnailDir = new File(pyramidDir.getParentFile(), ".thumbnail");
    thumbnailDir.mkdir();/*w ww.  j a  v a2  s  .c  o m*/
    final File refFile = File.createTempFile(imageName + ".", ".jpg", thumbnailDir);
    final File tmbFile = tmbImage != refImage ? File.createTempFile(imageName + ".tmb.", ".jpg", thumbnailDir)
            : refFile;

    final JSONObject thumbnail = new JSONObject();
    thumbnail.put("scope", "Project");
    thumbnail.put("width", tmbImage.getWidth());
    thumbnail.put("height", tmbImage.getHeight());
    thumbnail.put("src", toRef(projectScope, tmbFile.toPath()));
    ImageIO.write(refImage, "JPEG", refFile);
    if (tmbFile != refFile) {
        thumbnail.put("ref", toRef(projectScope, refFile.toPath()));
        ImageIO.write(tmbImage, "JPEG", tmbFile);
    }
    return thumbnail;
}

From source file:com.ejisto.util.IOUtils.java

public static boolean emptyDir(File file) {
    Path directory = file.toPath();
    if (!Files.isDirectory(directory)) {
        return true;
    }// www  . jav a2s.co  m
    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
                return FileVisitResult.TERMINATE;
            }
        });
    } catch (IOException e) {
        IOUtils.log.error(format("error while trying to empty the directory %s", directory.toString()), e);
        return false;
    }
    return true;
}

From source file:com.ejisto.util.IOUtils.java

public static byte[] readFile(File file) throws IOException {
    return Files.readAllBytes(file.toPath());
}

From source file:hudson.Main.java

/**
 * Run command and send result to {@code ExternalJob} in the {@code external-monitor-job} plugin.
 * Obsoleted by {@code SetExternalBuildResultCommand} but kept here for compatibility.
 *///from  www  .  jav a2s.  c  o m
public static int remotePost(String[] args) throws Exception {
    String projectName = args[0];

    String home = getHudsonHome();
    if (!home.endsWith("/"))
        home = home + '/'; // make sure it ends with '/'

    // check for authentication info
    String auth = new URL(home).getUserInfo();
    if (auth != null)
        auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8"));

    {// check if the home is set correctly
        HttpURLConnection con = open(new URL(home));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200 || con.getHeaderField("X-Hudson") == null) {
            System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")");
            return -1;
        }
    }

    URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");

    {// check if the job name is correct
        HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200) {
            System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " "
                    + con.getResponseMessage() + ")");
            return -1;
        }
    }

    // get a crumb to pass the csrf check
    String crumbField = null, crumbValue = null;
    try {
        HttpURLConnection con = open(
                new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
        String[] components = line.split(":");
        if (components.length == 2) {
            crumbField = components[0];
            crumbValue = components[1];
        }
    } catch (IOException e) {
        // presumably this Hudson doesn't use CSRF protection
    }

    // write the output to a temporary file first.
    File tmpFile = File.createTempFile("jenkins", "log");
    try {
        int ret;
        try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
                Writer w = new OutputStreamWriter(os, "UTF-8")) {
            w.write("<?xml version='1.1' encoding='UTF-8'?>");
            w.write("<run><log encoding='hexBinary' content-encoding='" + Charset.defaultCharset().name()
                    + "'>");
            w.flush();

            // run the command
            long start = System.currentTimeMillis();

            List<String> cmd = new ArrayList<String>();
            for (int i = 1; i < args.length; i++)
                cmd.add(args[i]);
            Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in,
                    new DualOutputStream(System.out, new EncodingStream(os)));

            ret = proc.join();

            w.write("</log><result>" + ret + "</result><duration>" + (System.currentTimeMillis() - start)
                    + "</duration></run>");
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }

        URL location = new URL(jobURL, "postBuildResult");
        while (true) {
            try {
                // start a remote connection
                HttpURLConnection con = open(location);
                if (auth != null)
                    con.setRequestProperty("Authorization", auth);
                if (crumbField != null && crumbValue != null) {
                    con.setRequestProperty(crumbField, crumbValue);
                }
                con.setDoOutput(true);
                // this tells HttpURLConnection not to buffer the whole thing
                con.setFixedLengthStreamingMode((int) tmpFile.length());
                con.connect();
                // send the data
                try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
                    org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }

                if (con.getResponseCode() != 200) {
                    org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
                }

                return ret;
            } catch (HttpRetryException e) {
                if (e.getLocation() != null) {
                    // retry with the new location
                    location = new URL(e.getLocation());
                    continue;
                }
                // otherwise failed for reasons beyond us.
                throw e;
            }
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:lc.kra.servlet.FileManagerServlet.java

private static void downloadFile(HttpServletResponse response, File file, String name) throws IOException {
    String contentType = java.nio.file.Files.probeContentType(file.toPath());
    downloadFile(response, file, name, contentType != null ? contentType : "application/octet-stream");
}

From source file:com.arpnetworking.metrics.impl.StenoLogSinkTest.java

private static File createDirectory(final String path) throws IOException {
    final File directory = new File(path);
    Files.createDirectories(directory.toPath());
    return directory;
}

From source file:edu.odu.cs.cs350.yellow1.ui.cli.Main.java

/**
 * Main program function. Creates and runs mutants as well as logging and output files
 * /*from   w  w  w .  j  a  v  a  2 s  .c o  m*/
 * @param srcFolder Source folder for project to be mutated
 * @param fileToBeMutated Source file for project to be mutated
 * @param testSuitePath Path for test suite
 * @param goldOutput Original version output file
 * @throws BuildFileNotFoundException
 * @throws IOException
 */
@SuppressWarnings("static-access")
public static void mutate(String srcFolder, String fileToBeMutated, String testSuitePath, String goldOutput)
        throws BuildFileNotFoundException, IOException {

    //Step 1: Set up file directory paths for antRunner, jarExecutor, and fileMover

    logger = LogManager.getLogger(Main.class);
    mutLog = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs"
            + File.separator + "mutationsApplied.txt");
    aliveLog = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs"
            + File.separator + "mutationsAlive.txt");
    logFolder = new File(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs");
    // ok because of the output on jenkins sanitize the logs directory
    if (logFolder.exists())
        if (logFolder.isDirectory())
            for (File f : logFolder.listFiles())
                f.delete();
    //give ant runer the project location
    ant = new AntRunner(srcFolder);
    ant.requiresInit(true);
    //call setup
    ant.setUp();
    a = new JavaFile();

    //give the jarUtil the  directory where to expect the jar   the directory where to put the jar
    jar = new JarUtil((srcFolder + File.separator + "bin"), (srcFolder + File.separator + "mutantDir"));

    //get a file object to the original file
    File goldFile = new File(fileToBeMutated);
    goldPath = goldFile.toPath();
    //get the bytes from it for checking if applying mutation and restore works
    goldOrgContent = Files.readAllBytes(goldPath);

    File script = new File(srcFolder + File.separator + "compare.sh");
    //build the JarExecutor using the JarExecutor
    jarExecutor = JarExecutorBuilder.pathToJarDirectory(srcFolder + File.separator + "mutantDir")
            .pathToCompareScript(script.getAbsolutePath())
            .pathToLogDir(srcFolder + File.separator + "mutantDir" + File.separator + "logs")
            .pathToGold(goldOutput.toString()).withExecutionState(ExecutionState.multiFile)
            .withTestSuitePath(testSuitePath).create();
    File tDir = new File(srcFolder + File.separator + "mutantDir");
    if (!tDir.exists())
        tDir.mkdir();
    //Create a fileMover object give it the directory where mutations will be placed   the directory of the original file location
    fMover = new FileMover(srcFolder + File.separator + "mutantDir", fileToBeMutated);
    fMover.setNoDelete(true);
    try {

        fMover.setUp();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();

    }

    //Step2: Create and run mutants

    try {
        a.readFile(fileToBeMutated);
    } catch (IOException e) {
        e.printStackTrace();
    }

    a.executeAll();
    int mutantsCreated = a.getMutantCaseVector().getSize();
    logger.info("Created " + mutantsCreated + " Mutants");
    for (int i = 0; i < a.getMutantCaseVector().getSize(); i++) {
        a.getMutantCaseOperations(i).writeMutation(srcFolder + File.separator + "mutantDir" + File.separator
                + "Mutation" + Integer.toString(i + 1) + ".java");
    }

    //get the files into the file mover object
    fMover.pullFiles();

    //check to see if the filemover got all the files
    //assertEquals(fMover.getFileToBeMovedCount(),mutantsCreated);

    int moved = 0;
    int failed = 0;
    //move through each file moving them one by one
    while (fMover.hasMoreFiles()) {
        try {
            //move next file
            fMover.moveNextFile();

            //build the new executable
            ant.build();
            //move the created jar with correct number corresponding to the mutation created 
            jar.moveJarToDestNumbered();
            //clean the project
            ant.clean();
            //check to see if the mutation was applied
            //assertThat(additionOrgContent, IsNot.not(IsEqual.equalTo(Files.readAllBytes(additionPath))));

        } catch (FileMovingException | BuildException | TargetNotFoundException | IOException e) {

            //build failed
            if (e instanceof BuildException) {
                logger.error("Build exception " + e.getMessage());

                //restore the file back since compilation was not successful 
                fMover.restorTarget();
                //try {
                //   //check to see if the file was restored
                //   assertArrayEquals(goldOrgContent, Files.readAllBytes(goldPath));
                //} catch (IOException e1) {
                //   
                //}
                //clean the project
                try {
                    ant.clean();
                } catch (BuildException e1) {

                } catch (TargetNotFoundException e1) {

                }
                //indicate compile failure
                ++failed;
            }
            //fail();
        }

        //restore the file back to its original state
        fMover.restorTarget();
        //check to see if the file was restored
        //try {
        //   assertArrayEquals(goldOrgContent, Files.readAllBytes(goldPath));
        //} catch (IOException e) {
        //   
        //}

        //increment move count
        ++moved;
        //see if the file mover has the correct amount of mutatants still to be moved
        //assertEquals(fMover.getFileToBeMovedCount(), mutantsCreated - moved);
    }

    //set up for execution
    jarExecutor.setUp();
    //start execution of jars
    jarExecutor.start();

    //get the number of successful and failed runs
    int succesful = jarExecutor.getNumberOfMutantsKilled();
    int failurs = jarExecutor.getNumberOfMutantsNotKilled();
    int numTests = jarExecutor.getNumberOfTests();
    int total = succesful + failurs;
    String aliveFile = null;
    String newLine = System.lineSeparator();

    //Find any test jars that remain alive and write them to the log file
    List<ExecutionResults> testResults = jarExecutor.getMutationTestingResults();
    for (ExecutionResults result : testResults) {
        if (!result.isKilled()) {
            aliveFile = result.getJarName();
            FileUtils.writeStringToFile(aliveLog, aliveFile + newLine, true);
        }
    }

    //moved - failed = number of jars actually created
    moved = moved - failed;
    //see if the total number of executions equals the total amount of jars created
    //assertEquals(succesful+failurs,moved);
    logger.debug("Compilation failurs= " + failed + " total files moved= " + moved);
    logger.debug("Execution succesful=" + succesful + " Execution failurs= " + failurs);

    EOL eol = System.getProperty("os.name").toLowerCase().contains("windows") ? EOL.DOS : EOL.NIX;
    try {
        a.writeMutationsLog(srcFolder.toString() + File.separator + "mutantDir" + File.separator + "logs"
                + File.separator + "mutationsApplied.txt", eol);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    String finalOutput = "Number of tests: " + numTests + " " + "Number of mutants: " + total + " "
            + "Mutants killed: " + succesful;
    FileUtils.writeStringToFile(mutLog, newLine + finalOutput, true);

    System.out.println(finalOutput + "\n");
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * Read public key./* www  .j a v a 2 s  .co  m*/
 *
 * @param file
 *            the file
 * @return the public key
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PublicKey readPublicKey(final File file)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    return readPublicKey(keyBytes, "BC");
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * Read private key.//from www .  ja v  a 2  s .c o  m
 *
 * @param file
 *            the file
 * @return the private key
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PrivateKey readPrivateKey(final File file)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    return readPrivateKey(keyBytes, "BC");
}

From source file:de.fatalix.book.importer.BookMigrator.java

private static BookEntry parseOPF(File pathToOPF, BookEntry bmd) throws IOException {
    List<String> lines = Files.readAllLines(pathToOPF.toPath(), Charset.forName("UTF-8"));
    boolean multiLineDescription = false;
    String description = "";
    for (String line : lines) {
        if (multiLineDescription) {
            multiLineDescription = false;
            if (line.split("<").length == 1) {
                multiLineDescription = true;
                description = description + line;
            } else {
                description = description + line.split("<")[0];
                description = StringEscapeUtils.unescapeXml(description);
                bmd.setDescription(description);
            }//from  w w w . j  a v a 2s  .c  om
        } else if (line.contains("dc:title")) {
            String title = line.split(">")[1].split("<")[0];
            bmd.setTitle(title);
        } else if (line.contains("dc:creator")) {
            String creator = line.split(">")[1].split("<")[0];
            bmd.setAuthor(creator);
        } else if (line.contains("dc:description")) {
            String value = line.split(">")[1];
            if (value.split("<").length == 1) {
                multiLineDescription = true;
                description = value;
            } else {
                value = value.split("<")[0];
                value = StringEscapeUtils.unescapeXml(value);
                bmd.setDescription(value);
            }
        } else if (line.contains("dc:publisher")) {
            String value = line.split(">")[1].split("<")[0];
            bmd.setPublisher(value);
        } else if (line.contains("dc:date")) {
            String value = line.split(">")[1].split("<")[0];
            DateTime dtReleaseDate = new DateTime(value, DateTimeZone.UTC);
            if (dtReleaseDate.getYear() != 101) {
                bmd.setReleaseDate(dtReleaseDate.toDate());
            }
        } else if (line.contains("dc:language")) {
            String value = line.split(">")[1].split("<")[0];
            bmd.setLanguage(value);
        } else if (line.contains("opf:scheme=\"ISBN\"")) {
            String value = line.split(">")[1].split("<")[0];
            bmd.setIsbn(value);
        }
    }
    return bmd;
}