Example usage for java.nio.file Path toFile

List of usage examples for java.nio.file Path toFile

Introduction

In this page you can find the example usage for java.nio.file Path toFile.

Prototype

default File toFile() 

Source Link

Document

Returns a File object representing this path.

Usage

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java

@Test
public void onPluginMetadataLoad_shouldUpdateThePluginInfoWithAssetsPath() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);
    GoPluginDescriptor goPluginDescriptor = new GoPluginDescriptor(PLUGIN_ID, null, null, null, null, false);
    AnalyticsPluginInfo analyticsPluginInfo = new AnalyticsPluginInfo(goPluginDescriptor, null, null, null);

    metadataStore.setPluginInfo(analyticsPluginInfo);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());

    assetsService.onPluginMetadataCreate(PLUGIN_ID);

    assertThat(analyticsPluginInfo.getStaticAssetsPath(), is(assetsService.assetPathFor(PLUGIN_ID)));
}

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java

@Test
public void onPluginMetadataLoad_shouldCachePluginStaticAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    addAnalyticsPluginInfoToStore(PLUGIN_ID);
    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());

    assetsService.onPluginMetadataCreate(PLUGIN_ID);

    assertFalse(dirtyPath.toFile().exists());
    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(/*from  w  w w . j a  v a  2 s  .c o m*/
            Paths.get(railsRoot.getAbsolutePath(), "public", assetsService.assetPathFor(PLUGIN_ID), "test.txt")
                    .toFile().exists());
}

From source file:at.tfr.securefs.client.SecurefsClient.java

public void run() {
    DateTime start = new DateTime();
    try (FileSystem fs = FileSystems.newFileSystem(new URI(baseDir), null)) {

        for (Path path : files) {

            Path sec = fs.getPath(path.toString() + (asyncTest ? "." + Thread.currentThread().getId() : ""));

            if (write) {
                if (!path.toFile().exists()) {
                    System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir="
                            + Paths.get("./").toAbsolutePath());
                    continue;
                }/*from w  w w .j a va  2 s.  c o  m*/

                if (path.getParent() != null) {
                    fs.provider().createDirectory(fs.getPath(path.getParent().toString()));
                }
                final OutputStream secOs = Files.newOutputStream(sec);

                System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + sec);

                IOUtils.copyLarge(Files.newInputStream(path), secOs, new byte[128 * 1024]);
                secOs.close();
            }

            Path out = path.resolveSibling(
                    path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out");

            if (read) {
                System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out);
                if (out.getParent() != null) {
                    Files.createDirectories(out.getParent());
                }

                final InputStream secIs = Files.newInputStream(sec);
                IOUtils.copyLarge(secIs, Files.newOutputStream(out), new byte[128 * 1024]);
                secIs.close();
            }

            if (write && read) {
                long inputChk = FileUtils.checksumCRC32(path.toFile());
                long outputChk = FileUtils.checksumCRC32(out.toFile());

                if (inputChk != outputChk) {
                    throw new IOException(Thread.currentThread()
                            + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out);
                }
                System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : "
                        + inputChk + " / " + outputChk);
            }

            if (delete) {
                boolean deleted = fs.provider().deleteIfExists(sec);
                if (!deleted) {
                    throw new IOException(
                            Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path);
                } else {
                    System.out.println(Thread.currentThread() + ": Deleted File: in=" + path);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}

From source file:com.surevine.gateway.scm.model.LocalRepoBean.java

public void emptyRepoDirectory() {
    final Path localDirectory = getRepoDirectory();
    try {//from w  w w. j  a  va2s . c o  m
        FileUtils.cleanDirectory(localDirectory.toFile());
    } catch (final IOException e) {
        // drop the exception
    }
}

From source file:com.hortonworks.streamline.streams.actions.topology.service.TopologyActionsService.java

private void makeEmptyDir(Path path) throws IOException {
    if (path.toFile().exists()) {
        if (path.toFile().isDirectory()) {
            FileUtils.cleanDirectory(path.toFile());
        } else {//ww w.j  a va  2s  .c om
            final String errorMessage = String.format("Location '%s' must be a directory.", path);
            LOG.error(errorMessage);
            throw new IOException(errorMessage);
        }
    } else if (!path.toFile().mkdirs()) {
        LOG.error("Could not create dir {}", path);
        throw new IOException("Could not create dir: " + path);
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);//from w w w.  j  a  v  a 2s  . c  o m
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured kindlegen executable
        logger.info("Kindlegen will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Kindlegen will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());
    cmdLine.addArgument("-c0");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter stdoutWriter = new StringWriter();
    StringWriter stderrWriter = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8"));
    WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8"));

    ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream);
    executor.setStreamHandler(kindlegenStreamHandler);

    logger.debug("Launching kindlegen:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Kindlegen failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Kindlegen execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"kindlegen\"")) {
                logger.error("Kindlegen could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("Kindlegen's execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    try {
        String stderrOutput = stderrWriter.getBuffer().toString();
        stderrWriter.close();
        if (stderrOutput.isEmpty() == false) {
            logger.error("Kindlegen logged some errors:");
            logger.error(stderrOutput);
        }
    } catch (IOException e) {
        logger.error("Error closing kindlegen's stderr buffer");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += stdoutWriter.getBuffer().toString();
        stdoutWriter.close();

    } catch (IOException e) {
        logger.error("Error closing kindlegen's stdout buffer:");
        logger.error(e.getMessage(), e);
    }

    logger.debug("Kindlegen output: \n" + output);

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    logger.debug("Moving Kindlegen output file: " + mobiFilename);

    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);
    return tempMobiFilepath.toFile();
}

From source file:org.eclipse.vorto.remoterepository.internal.dao.FilesystemModelDAO.java

@Override
public ModelContent getModelById(ModelId id) {

    Objects.requireNonNull(id);//from   w ww .ja  va 2s . c o  m
    Objects.requireNonNull(id.getModelType(), "Model type shouldn't be Null.");
    Objects.requireNonNull(id.getName(), "Model name shouldn't be Null.");
    Objects.requireNonNull(id.getNamespace(), "Namespace shouldn't be Null.");
    Objects.requireNonNull(id.getVersion(), "Version shouldn't be Null.");

    ModelContent mc = new ModelContent(id, id.getModelType(), null);

    Path pathToModel = resolvePathToModel(id);

    log.info("pathToModel: " + pathToModel.toAbsolutePath().toString());
    if (pathToModel.toFile().exists()) {
        mc = this.getModelContent(pathToModel);
    }

    return mc;
}

From source file:com.boundlessgeo.geoserver.bundle.BundleImporter.java

public Path unzip(Path zip) throws IOException {
    try (InputStream in = new BufferedInputStream(new FileInputStream(zip.toFile()));) {
        IOUtils.decompress(in, root.toFile());
    }/* w  w w. j  a  va2s  . c  o m*/
    return root;
}

From source file:com.streamsets.pipeline.lib.io.LiveFile.java

String computeHash(Path path, int len) throws IOException {
    byte[] buffer = new byte[len];
    try (InputStream is = new FileInputStream(path.toFile())) {
        IOUtils.readFully(is, buffer);//from w  w  w  .  java2  s .  c o  m
    }
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        buffer = digest.digest(buffer);
        return Base64.encodeBase64String(buffer);
    } catch (NoSuchAlgorithmException ex) {
        throw new IOException(ex);
    }
}

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

private void applyCustomerCss(ServletContext context, List<CssAttribute> cssAttributes, String customerName)
        throws Exception {
    if (!cssAttributes.isEmpty()) {
        Path tempPath = Files.createTempDirectory(customerName);
        File tempDir = tempPath.toFile();

        //copy css sortedFiles to data directory
        copyResources(context, FOLDER_CSS, tempDir);

        //copy less sortedFiles
        copyResources(context, FOLDER_LESS, tempDir);

        //replace variables in variables.less, 90_project.less, 96_loader.less
        replaceVariables(context, cssAttributes, VARIABLES_LESS, tempDir);
        replaceVariables(context, cssAttributes, PROJECT_LESS, tempDir);
        replaceVariables(context, cssAttributes, LOADER_LESS, tempDir);

        //compile less and overwrite css sortedFiles in data directory
        if (lessCompiler == null) {
            lessCompiler = new LessCompiler();
        }/*from ww  w  . j  ava2  s  .  c om*/
        lessCompiler.compile(new File(tempDir, PROJECT_LESS), new File(tempDir, PROJECT_CSS));
        lessCompiler.compile(new File(tempDir, BOOTSTRAP_LESS), new File(tempDir, BOOTSTRAP_CSS));
        lessCompiler.compile(new File(tempDir, LOADER_LESS), new File(tempDir, LOADER_CSS));

        Path allMinCssPath = new File(tempDir, ALL_MIN_CSS).toPath();
        //concatenate all sortedFiles into all.min.css
        String css = concatenateCss(context, new File(tempDir, FOLDER_CSS).toPath(), allMinCssPath);

        //set content for css controller
        context.setAttribute(customerName, css);
    }
}