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:cz.etnetera.reesmo.writer.storage.FileSystemStorage.java

protected File createModelProjectKeyFile(File modelDir, Model model, String projectKey)
        throws StorageException {
    try {/*w w w  .  ja v  a  2  s  . com*/
        File projectFile = getModelProjectKeyFile(modelDir);
        Files.write(projectFile.toPath(), projectKey.getBytes());
        getLogger().info(getModelName(model) + " project key file created: " + projectFile);
        return projectFile;
    } catch (IOException e) {
        throw new StorageException("Unable to create " + getModelName(model) + " project key file", e);
    }
}

From source file:org.orderofthebee.addons.support.tools.repo.AbstractLogFileWebScript.java

/**
 * Validates a log file paths and resolves them to file handles.
 *
 * @param filePaths/*from w ww .j a v  a2s.c om*/
 *            the file paths to validate
 * @return the resolved file handles if the file paths are valid and allowed to be accessed
 *
 * @throws WebScriptException
 *             if access to any log file is prohibited
 */
protected List<File> validateFilePaths(final List<String> filePaths) {
    ParameterCheck.mandatoryCollection("filePaths", filePaths);

    final List<Path> paths = new ArrayList<>();
    for (final String filePath : filePaths) {
        paths.add(Paths.get(filePath));
    }

    boolean allPathsAllowed = true;
    final List<Logger> allLoggers = this.getAllLoggers();
    final List<File> files = new ArrayList<>();

    for (final Logger logger : allLoggers) {
        @SuppressWarnings("unchecked")
        final Enumeration<Appender> allAppenders = logger.getAllAppenders();
        while (allAppenders.hasMoreElements() && allPathsAllowed) {
            final Appender appender = allAppenders.nextElement();
            if (appender instanceof FileAppender) {
                final String appenderFile = ((FileAppender) appender).getFile();
                final File configuredFile = new File(appenderFile);
                final Path configuredFilePath = configuredFile.toPath().toAbsolutePath().getParent();

                for (final Path path : paths) {
                    allPathsAllowed = allPathsAllowed && path.startsWith(configuredFilePath)
                            && path.getFileName().toString().startsWith(configuredFile.getName());

                    if (!allPathsAllowed) {
                        throw new WebScriptException(Status.STATUS_FORBIDDEN, "The log file path " + path
                                + " could not be resolved to a valid log file - access to any other file system contents is forbidden via this web script");
                    }

                    final File file = path.toFile();
                    if (!file.exists()) {
                        throw new WebScriptException(Status.STATUS_NOT_FOUND,
                                "The log file path " + path + " could not be resolved to an existing log file");
                    }

                    files.add(file);
                }
            }
        }
    }

    return files;
}

From source file:com.nike.cerberus.operation.core.UploadCertFilesOperation.java

private String getFileContents(final Path path, final String filename) {
    Preconditions.checkNotNull(path);//  w  w  w .j a v a 2 s . c  o m
    Preconditions.checkNotNull(filename);

    File file = new File(path.toString(), filename);
    if (file.exists() && file.canRead()) {
        try {
            return new String(Files.readAllBytes(file.toPath()), Charset.forName("UTF-8"));
        } catch (IOException e) {
            throw new IllegalStateException("Failed to read the following file: " + file.getAbsolutePath());
        }
    } else {
        throw new IllegalArgumentException("The file is not readable: " + file.getAbsolutePath());
    }
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void canLoadKeyFromFilePath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);/*from w  ww .  ja v a  2  s . c o m*/
    FileUtils.writeByteArrayToFile(file, keyBytes);
    Path path = file.toPath();

    SecretKey expected = SecretKeyUtils.loadKey(keyBytes, AesGcmCipherDetails.INSTANCE_128_BIT);
    SecretKey actual = SecretKeyUtils.loadKeyFromPath(path, AesGcmCipherDetails.INSTANCE_128_BIT);

    Assert.assertEquals(actual.getAlgorithm(), expected.getAlgorithm());
    Assert.assertTrue(Arrays.equals(expected.getEncoded(), actual.getEncoded()),
            "Secret key loaded from URI doesn't match");
}

From source file:de.ks.file.FileStoreTest.java

@Before
public void setUp() throws Exception {
    controller.startOrResume(new ActivityHint(AddThoughtActivity.class));

    cleanup.cleanup();/*from   w w  w  .  j av a2 s. com*/
    fileStoreDir = TMPDIR + File.separator + "idnadrevTestStore";
    Options.store(fileStoreDir, FileOptions.class).getFileStoreDir();
    File file = new File(fileStoreDir);
    if (file.exists()) {
        Files.walkFileTree(file.toPath(), 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 {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:de.alexkamp.sandbox.ChrootSandboxFactory.java

@Override
public void deleteSandbox(final SandboxData sandbox) {
    File copyDir = sandbox.getBaseDir();

    try {/*w ww  .  j ava2 s  .c om*/
        final AtomicInteger depth = new AtomicInteger(0);
        Files.walkFileTree(copyDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                int d = depth.getAndIncrement();

                // see whether the mounts are gone
                if (1 == d) {
                    for (Mount m : sandbox) {
                        if (path.endsWith(m.getMountPoint().substring(1))) {
                            if (0 != path.toFile().listFiles().length) {
                                throw new IllegalArgumentException(
                                        path.getFileName() + " has not been unmounted.");
                            }
                        }
                    }
                }

                return FileVisitResult.CONTINUE;
            }

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

            @Override
            public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
                Files.delete(path);
                depth.decrementAndGet();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new SandboxException(e);
    }
}

From source file:com.movilizer.mds.webservice.services.MafManagementService.java

protected MafCliMetaFile readMetaFile(File sourceFile) throws FileNotFoundException {
    String metaFileName = sourceFile.getName().replace(GROOVY_EXTENSION, META_FILE_EXTENSION);
    Path metaFilePath = sourceFile.toPath().resolveSibling(metaFileName);
    if (logger.isDebugEnabled()) {
        logger.debug(String.format(Messages.LOADING_MAF_METADATA, metaFilePath.toString()));
    }/*from ww  w  .ja  va 2s  .  c  o  m*/
    return gson.fromJson(new FileReader(metaFilePath.toFile()), MafCliMetaFile.class);
}

From source file:de.fatalix.bookery.bl.background.importer.CalibriImporter.java

@Override
public void executeJob(Timer timer) {
    logger.debug("Starting batch job...");
    DateTimeZone.setDefault(DateTimeZone.UTC);
    BatchJobConfiguration jobConfig = (BatchJobConfiguration) timer.getInfo();
    Gson gson = new Gson();
    CalibriImporterConfiguration config = gson.fromJson(jobConfig.getConfigurationXML(),
            CalibriImporterConfiguration.class);

    File importFolder = new File(config.getImportFolder());
    if (importFolder.isDirectory()) {
        File[] zipFiles = importFolder.listFiles(new FilenameFilter() {

            @Override/*from  w w w.  j av  a 2 s. c  om*/
            public boolean accept(File dir, String name) {
                return name.endsWith(".zip");
            }
        });
        for (File zipFile : zipFiles) {
            try {
                processArchive(zipFile.toPath(), config.getBatchSize());
                logger.info("Processed file " + zipFile.getName());
            } catch (IOException ex) {
                logger.error("Cannot process " + zipFile.getName(), ex);

            }
        }
    } else {
        logger.error("Import folder: " + importFolder.getAbsolutePath() + " cannot be read!");
    }
}

From source file:com.digitalpetri.opcua.raspberrypi.PiServer.java

private void configureLogback() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {/*from  w w  w  .  j a  v  a2 s  .c  o  m*/
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();

        System.out.println(System.getProperty("user.dir"));

        File logbackXml = new File("../config/logback.xml");

        if (!logbackXml.exists()) {
            InputStream is = getClass().getClassLoader().getResourceAsStream("logback.xml");
            Files.copy(is, logbackXml.toPath());
        }

        configurator.doConfigure(logbackXml);
    } catch (Exception e) {
        System.err.println("Error configuring logback." + e);
    }

    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}

From source file:com.oneops.boo.ClientConfigInterpolator.java

/**
 * Take key/value pairs from a OneOps configuration profile and interpolate a Boo YAML template
 * with them.//  ww  w.  j  a v a 2 s.  c  o m
 * 
 * @param booYamlFile template to use
 * @param booConfigFile to use for key/value pairs
 * @param profile in configuration file to use for key/value pairs
 * @return Interpolate Boo YAML template
 * @throws IOException throw if there are errors interpolating the template
 */
public String interpolate(File booYamlFile, File booConfigFile, String profile) throws IOException {
    String booYaml = new String(Files.readAllBytes(booYamlFile.toPath()));
    return interpolate(booYaml, booConfigFile, profile);
}