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:bjerne.gallery.service.impl.GalleryServiceImpl.java

private String getContentType(File file) throws IOException {
    return Files.probeContentType(file.toPath());
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithPlainTextFileUTF8RomanCharacters() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    File temp = File.createTempFile("upload", ".txt");
    FileUtils.forceDeleteOnExit(temp);/*from www .  ja v a  2s .com*/

    Files.write(temp.toPath(), TEST_DATA.getBytes(StandardCharsets.UTF_8));
    MantaObject response = mantaClient.put(path, temp);
    String contentType = response.getContentType();
    Assert.assertEquals(contentType, "text/plain", "Content type wasn't detected correctly");

    String actual = mantaClient.getAsString(path);
    Assert.assertEquals(actual, TEST_DATA, "Uploaded file didn't match expectation");
}

From source file:com.javacreed.api.secureproperties.spring.SpringPropertiesTest.java

@Test
public void test() throws IOException {

    final String[] configurations = { "test-configuration-1.xml", "test-configuration-2.xml",
            "test-configuration-3.xml", "test-configuration-4.xml", "test-configuration-5.xml",
            /* "test-configuration-6.xml" */ };

    /*//from  w ww . j a  v  a  2 s.  c o m
     * The source properties file that contains the plain text password and the target properties file from where the
     * configuration reads the properties
     */
    final File source = new File("src/test/resources/samples/properties/file.001.properties");
    final File target = new File("target/samples/properties/file.001.properties");
    target.getParentFile().mkdirs();

    for (final String configuration : configurations) {

        // Copy the properties file before the test
        Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);

        for (int i = 0; i < 3; i++) {
            try (ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    "/spring/" + configuration)) {
                // Check all three properties
                Assert.assertEquals("Albert",
                        applicationContext.getBeanFactory().resolveEmbeddedValue("${name}"));
                Assert.assertEquals("Somewhere in Malta",
                        applicationContext.getBeanFactory().resolveEmbeddedValue("${address}"));
                Assert.assertEquals("my long secret password",
                        applicationContext.getBeanFactory().resolveEmbeddedValue("${password}"));

                // Make sure that the password was encoded
                final List<String> lines = Files.readAllLines(target.toPath(), Charset.forName("UTF-8"));
                Assert.assertEquals(4, lines.size());
                Assert.assertEquals("# This is a simple properties file", lines.get(0));
                Assert.assertEquals("name=Albert", lines.get(1));
                Assert.assertEquals("address=Somewhere in Malta", lines.get(2));
                Assert.assertTrue(lines.get(3).startsWith("password={enc}"));
                Assert.assertFalse(lines.get(3).contains("my long secret password"));
            }
        }
    }
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithPlainTextFileWithErrorProneName() throws IOException {
    final String name = UUID.randomUUID().toString() + "- -~!@#$%^&*().txt";
    final String path = testPathPrefix + name;
    File temp = File.createTempFile("upload", ".txt");
    FileUtils.forceDeleteOnExit(temp);//w ww. j a  v  a 2s. c  om

    Files.write(temp.toPath(), TEST_DATA.getBytes(StandardCharsets.UTF_8));
    MantaObject response = mantaClient.put(path, temp);
    String contentType = response.getContentType();
    Assert.assertEquals(contentType, "text/plain", "Content type wasn't detected correctly");

    String actual = mantaClient.getAsString(path);
    Assert.assertEquals(actual, TEST_DATA, "Uploaded file didn't match expectation");
    Assert.assertEquals(response.getPath(), path, "path returned as written");
}

From source file:de.ks.text.AsciiDocParser.java

protected File createDataDir(File file) {
    String child = file.getName().contains(".") ? file.getName().substring(0, file.getName().lastIndexOf('.'))
            : file.getName();/*from ww  w  . jav  a 2 s .  c  om*/
    File dataDir = new File(file.getParent(), child + DATADIR_NAME);
    log.debug("using target data dir {}", dataDir);

    if (!dataDir.exists()) {
        try {
            java.nio.file.Files.createDirectories(dataDir.toPath());
        } catch (IOException e) {
            log.error("Could not create datadir {}", dataDir, e);
            throw new RuntimeException(e);
        }
    }
    return dataDir;
}

From source file:gob.dp.simco.registro.controller.VictimaViolenciaController.java

private void remonbrarArchivo() {
    if (file1.getSize() > 0) {
        DateFormat fechaHora = new SimpleDateFormat("yyyyMMddHHmmss");
        String formato = fechaHora.format(new Date());
        String ruta = formato + getFileExtension(getFilename(file1));
        File file = new File(ConstantesUtil.FILE_SYSTEM + ruta);
        try (InputStream input = file1.getInputStream()) {
            Files.copy(input, file.toPath());
        } catch (IOException ex) {
            log.error(ex);//  w  w w .  jav  a 2 s.com
        }
        actividadVictima.setRuta(ruta);
    }
}

From source file:com.diffplug.gradle.pde.PdeProductBuildConfig.java

void setup(File destinationDir, PdeBuildProperties props, List<SwtPlatform> platforms, List<File> pluginPaths)
        throws IOException {
    // make sure every required entry was set
    Objects.requireNonNull(id, "Must set `id`");
    Objects.requireNonNull(productPluginDir, "Must set `productPluginDir`");
    Objects.requireNonNull(productFileWithinPlugin, "Must set `productFileWithinPlugin`");
    Objects.requireNonNull(version, "Must set `version`");
    if (pluginPaths.isEmpty()) {
        throw new IllegalArgumentException("There should be at least one pluginPath");
    }//from   ww w. java  2 s.c  o m

    // create a PluginCatalog and validate the version policy / pluginPaths
    PluginCatalog catalog = new PluginCatalog(explicitVersionPolicy.getResult(), platforms, pluginPaths);

    // create a fake folder which will contain our sanitized product file
    File productPluginDir = project.file(this.productPluginDir);
    File tempProductDir = new File(destinationDir, productPluginDir.getName());

    // copy all images from original to the sanitized
    copyImages(productPluginDir, tempProductDir);

    // now create the sanitized product file
    File productFile = productPluginDir.toPath().resolve(productFileWithinPlugin).toFile();
    File tempProductFile = tempProductDir.toPath().resolve(productFileWithinPlugin).toFile();
    transformProductFile(productFile, tempProductFile, catalog, version);

    // finally setup the PdeBuildProperties to our temp product stuff
    props.setProp("topLevelElementType", "product");
    props.setProp("topLevelElementId", id);
    props.setProp("product", "/" + tempProductDir.getName() + "/" + productFileWithinPlugin);
}

From source file:com.ibm.util.merge.persistence.FilesystemPersistence.java

/**********************************************************************************
 * Cache JSON templates found in the template folder.
 * Note: The template folder is initialized from Merge.java from the web.xml value  for
 * merge-templates-folder, if it is not initilized the default value is /tmp/templates
 *
 * @param folder that contains template files
 */// w  w  w . j av  a 2  s . co m
@Override
public List<Template> loadAllTemplates() {
    List<Template> templates = new ArrayList<>();
    int count = 0;
    if (templateFolder.listFiles() == null) {
        throw new RuntimeException("Template Folder data was not found! " + templateFolder);
    }
    for (File file : templateFolder.listFiles()) {
        log.debug("Inspect potential template file: " + file);
        if (!file.isDirectory() && !file.getName().startsWith(".")) {
            try {
                String json = new String(Files.readAllBytes(file.toPath()));
                Template template = jsonProxy.fromJSON(json, Template.class);
                templates.add(template);
                log.info("Loaded template " + template.getFullName() + " : " + file.getAbsolutePath());
                count++;
            } catch (JsonSyntaxException e) {
                log.warn("Malformed JSON Template:" + file.getName(), e);
            } catch (FileNotFoundException e) {
                log.info("Moving on after file read error on " + file.getName(), e);
            } catch (IOException e) {
                log.warn("IOException Reading:" + file.getName(), e);
            }
        }

    }
    log.info("Loaded " + Integer.toString(count) + " templates from " + templateFolder);
    return templates;
}

From source file:co.marcin.novaguilds.manager.ConfigManager.java

public void backupFile() throws IOException {
    File backupFile = new File(getConfigFile().getParentFile(), "config.yml.backup");
    Files.copy(getConfigFile().toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:gov.vha.isaac.rf2.filter.RF2Filter.java

@Override
public void execute() throws MojoExecutionException {
    if (!inputDirectory.exists() || !inputDirectory.isDirectory()) {
        throw new MojoExecutionException("Path doesn't exist or isn't a folder: " + inputDirectory);
    }/*from www .ja v  a2 s.co  m*/

    if (module == null) {
        throw new MojoExecutionException("You must provide a module or namespace for filtering");
    }

    moduleStrings_.add(module + "");

    outputDirectory.mkdirs();
    File temp = new File(outputDirectory, inputDirectory.getName());
    temp.mkdirs();

    Path source = inputDirectory.toPath();
    Path target = temp.toPath();
    try {
        getLog().info("Reading from " + inputDirectory.getAbsolutePath());
        getLog().info("Writing to " + outputDirectory.getCanonicalPath());

        summary_.append("This content was filtered by an RF2 filter tool.  The parameters were module: "
                + module + " software version: " + converterVersion);
        summary_.append("\r\n\r\n");

        getLog().info("Checking for nested child modules");

        //look in sct2_Relationship_ files, find anything where the 6th column (destinationId) is the 
        //starting module ID concept - and add that sourceId (5th column) to our list of modules to extract
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().getName().startsWith("sct2_Relationship_")) {
                    //don't look for quotes, the data is bad, and has floating instances of '"' all by itself
                    CSVReader csvReader = new CSVReader(
                            new InputStreamReader(new FileInputStream(file.toFile())), '\t',
                            CSVParser.NULL_CHARACTER);
                    String[] line = csvReader.readNext();
                    if (!line[4].equals("sourceId") || !line[5].equals("destinationId")) {
                        csvReader.close();
                        throw new IOException("Unexpected error looking for nested modules");
                    }
                    line = csvReader.readNext();
                    while (line != null) {
                        if (line[5].equals(moduleStrings_.get(0))) {
                            moduleStrings_.add(line[4]);
                        }
                        line = csvReader.readNext();
                    }
                    csvReader.close();
                }
                return FileVisitResult.CONTINUE;
            }
        });

        log("Full module list (including detected nested modules: "
                + Arrays.toString(moduleStrings_.toArray(new String[moduleStrings_.size()])));

        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetdir = target.resolve(source.relativize(dir));
                try {
                    //this just creates the sub-directory in the target
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                handleFile(file, target.resolve(source.relativize(file)));
                return FileVisitResult.CONTINUE;
            }
        });

        Files.write(new File(temp, "FilterInfo.txt").toPath(), summary_.toString().getBytes(),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        throw new MojoExecutionException("Failure", e);
    }

    getLog().info("Filter Complete");

}