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:com.bc.fiduceo.post.PostProcessingToolMain_IO_Test.java

@Test
public void acceptanceTest() throws IOException, URISyntaxException, ParseException {
    configDir.mkdirs();/*from   www. jav a 2  s . co m*/
    final File systemConfigFile = new File(configDir, "system-config.xml");
    Files.write(systemConfigFile.toPath(), "<system-config></system-config>".getBytes());

    final Element rootElement = new Element("post-processing-config")
            .addContent(
                    Arrays.asList(new Element("overwrite"),
                            new Element("post-processings").addContent(
                                    new Element("spherical-distance").addContent(Arrays.asList(
                                            new Element("target").addContent(Arrays.asList(
                                                    new Element("data-type").addContent("Float"),
                                                    new Element("var-name").addContent("post_dist"),
                                                    new Element("dim-name").addContent("matchup_count"))),
                                            new Element("primary-lat-variable")
                                                    .setAttribute("scaleAttrName", "Scale")
                                                    .addContent("amsub-n16_Latitude"),
                                            new Element("primary-lon-variable")
                                                    .setAttribute("scaleAttrName", "Scale")
                                                    .addContent("amsub-n16_Longitude"),
                                            new Element("secondary-lat-variable").addContent("ssmt2-f14_lat"),
                                            new Element("secondary-lon-variable")
                                                    .addContent("ssmt2-f14_lon"))))));

    final Document document = new Document(rootElement);
    final String processingConfigFileName = "processing-config.xml";
    final File file = new File(configDir, processingConfigFileName);
    try (OutputStream stream = Files.newOutputStream(file.toPath())) {
        new XMLOutputter(Format.getPrettyFormat()).output(document, stream);
    }

    dataDir.mkdirs();
    final String filename = "mmd22_amsub-n16_ssmt2-f14_2000-306_2000-312.nc";
    final File src = new File(new File(TestUtil.getTestDataDirectory(), "post-processing"), filename);
    final File target = new File(dataDir, filename);
    Files.copy(src.toPath(), target.toPath());

    final String[] args = { "-c", configDir.getAbsolutePath(), "-i", dataDir.getAbsolutePath(), "-start",
            "2000-306", "-end", "2000-312", "-j", processingConfigFileName };

    PostProcessingToolMain.main(args);

    NetcdfFile netcdfFile = null;
    try {
        netcdfFile = NetcdfFile.open(target.getAbsolutePath());
        final Variable postDistVar = netcdfFile.findVariable("post_dist");
        final Variable matchupDistVar = netcdfFile.findVariable("matchup_spherical_distance");

        assertNotNull(postDistVar);
        assertNotNull(matchupDistVar);

        final Array pDistArr = postDistVar.read();
        final Array mDistArr = matchupDistVar.read();

        final float[] pStorage = (float[]) pDistArr.getStorage();
        final float[] mStorage = (float[]) mDistArr.getStorage();

        assertEquals(4, pStorage.length);
        assertEquals(4, mStorage.length);

        for (int i = 0; i < pStorage.length; i++) {
            assertEquals(pStorage[i], mStorage[i], 1e-3);
        }
    } finally {
        if (netcdfFile != null) {
            netcdfFile.close();
        }
    }
}

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

/**
 * Validates a single log file path and resolves it to a file handle.
 *
 * @param filePath//w  w w. j  a v  a  2 s.com
 *            the file path to validate
 * @return the resolved file handle if the file path is valid and allowed to be accessed
 *
 * @throws WebScriptException
 *             if access to the log file is prohibited
 */
protected File validateFilePath(final String filePath) {
    ParameterCheck.mandatoryString("filePath", filePath);

    final Path path = Paths.get(filePath);
    boolean pathAllowed = false;
    final List<Logger> allLoggers = this.getAllLoggers();

    for (final Logger logger : allLoggers) {
        @SuppressWarnings("unchecked")
        final Enumeration<Appender> allAppenders = logger.getAllAppenders();
        while (allAppenders.hasMoreElements() && !pathAllowed) {
            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();
                pathAllowed = pathAllowed || (path.startsWith(configuredFilePath)
                        && path.getFileName().toString().startsWith(configuredFile.getName()));
            }
        }
    }

    if (!pathAllowed) {
        throw new WebScriptException(Status.STATUS_FORBIDDEN, "The log file path " + filePath
                + " 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 " + filePath + " could not be resolved to an existing log file");
    }

    return file;
}

From source file:org.wte4j.examples.showcase.server.config.DatabaseConfig.java

@Bean
public HsqlServerBean hsqlServer() {
    boolean overwrite = env.getProperty(RESET_DATABSE_ENV_PROPERTY, Boolean.class, Boolean.FALSE);
    File directory = env.getProperty(DATABASE_DIRECTORY_ENV_PROPERTY, File.class, DEFAULT_DATABASE_DIRECTORY);
    ShowCaseDbInitializer dbInitializer = new ShowCaseDbInitializer(resourceloader);
    return dbInitializer.createDatabase(directory.toPath(), overwrite);
}

From source file:com.linkedin.pinot.core.segment.index.converter.SegmentV1V2ToV3FormatConverter.java

@VisibleForTesting
public File v3ConversionTempDirectory(File v2SegmentDirectory) throws IOException {
    File v3TempDirectory = Files
            .createTempDirectory(v2SegmentDirectory.toPath(), v2SegmentDirectory.getName() + V3_TEMP_DIR_SUFFIX)
            .toFile();/*  www.j  a va  2 s  .c om*/
    return v3TempDirectory;

}

From source file:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java

@Override
public FileStatus getFileStatus(File file) {
    Path path = file.toPath();
    File parent = path.getParent().toFile();
    if (Files.exists(path)) {
        if (parent.equals(captureDirectory)) {
            if (Files.isSymbolicLink(path)) {
                return FileStatus.CAPTURED_SYMLINK;
            } else {
                return FileStatus.CAPTURED_FILE;
            }/*from w  w  w. j a  v  a  2  s. c  o  m*/
        } else if (parent.equals(archiveDirectory)) {
            if (Files.isSymbolicLink(path)) {
                return FileStatus.ARCHIVED_SYMLINK;
            } else {
                return FileStatus.ARCHIVED_FILE;
            }
        } else {
            return FileStatus.NOT_OURS;
        }
    } else {
        if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
            if (parent.equals(captureDirectory)) {
                return FileStatus.BROKEN_CAPTURED_SYMLINK;
            } else if (parent.equals(archiveDirectory)) {
                return FileStatus.BROKEN_ARCHIVED_SYMLINK;
            } else {
                return FileStatus.NOT_OURS;
            }
        } else {
            return FileStatus.NON_EXISTENT;
        }
    }
}

From source file:io.github.zlika.reproducible.ZipStripper.java

@Override
public void strip(File in, File out) throws IOException {
    try (final ZipFile zip = new ZipFile(in);
            final ZipArchiveOutputStream zout = new ZipArchiveOutputStream(out)) {
        final List<String> sortedNames = sortEntriesByName(zip.getEntries());
        for (String name : sortedNames) {
            final ZipArchiveEntry entry = zip.getEntry(name);
            // Strip Zip entry
            final ZipArchiveEntry strippedEntry = filterZipEntry(entry);
            // Strip file if required
            final Stripper stripper = getSubFilter(name);
            if (stripper != null) {
                // Unzip entry to temp file
                final File tmp = File.createTempFile("tmp", null);
                tmp.deleteOnExit();/*  w  ww.j  a  va  2s  .  com*/
                Files.copy(zip.getInputStream(entry), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
                final File tmp2 = File.createTempFile("tmp", null);
                tmp2.deleteOnExit();
                stripper.strip(tmp, tmp2);
                final byte[] fileContent = Files.readAllBytes(tmp2.toPath());
                strippedEntry.setSize(fileContent.length);
                zout.putArchiveEntry(strippedEntry);
                zout.write(fileContent);
                zout.closeArchiveEntry();
            } else {
                // Copy the Zip entry as-is
                zout.addRawArchiveEntry(strippedEntry, getRawInputStream(zip, entry));
            }
        }
    }
}

From source file:edu.chalmers.dat076.moviefinder.controller.AdminController.java

@RequestMapping(value = "/addPath", method = RequestMethod.POST)
public ResponseEntity<ListeningPath> addPath(@RequestBody ListeningPath path) {
    File f = new File(path.getListeningPath().toLowerCase());
    if (f.exists() && f.isDirectory()) {
        try {/*from   w ww .  java  2s.  com*/
            ListeningPath savedPath = databaseHelper.addPath(f.toPath());
            fileThreadService.addListeningPath(f.toPath());
            return new ResponseEntity<>(savedPath, HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    } else {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
}

From source file:com.skynetcomputing.skynetclient.WorkManagerTest.java

/**
 * Test of start method, of class WorkManager.
 *
 * @throws java.io.IOException//w w w  .  j  av  a 2 s.c o  m
 * @throws java.lang.InterruptedException
 */
@Test
public void testStart() throws IOException, InterruptedException {
    IConnectionMgr conn = new IConnectionMgr() {
        @Override
        public void sendFile(File aFile) {
            try {
                Files.copy(aFile.toPath(), new File(LOCAL_INPUT_DIR + aFile.getName()).toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(WorkManagerTest.class.getName()).log(Level.SEVERE, "Error sending file", ex);
            }
        }

        @Override
        public void notifyJarOKNOK(boolean isOK) throws IOException {
            assertTrue("Checking Jar presence", isOK);
        }

        @Override
        public void notifyTaskCompleted() throws IOException {
            Logger.getLogger(WorkManagerTest.class.getName()).log(Level.INFO, "Task Completed");
            synchronized (isRunning) {
                isRunning.set(false);
                isRunning.notifyAll();
            }
        }

        @Override
        public void start(InetSocketAddress serverAddress) {
            System.out.println("Fake start listening..");
        }

        @Override
        public boolean isSendingFiles() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void notifyTaskStarting() throws IOException {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };

    WorkManager workMgr = new WorkManager(conn, ROOT_DIR);
    // Read only, should not be used for saving files
    PersistenceManager persistMgr = new PersistenceManager(ROOT_DIR);

    File testDir = new File(MANDELTASK_DIR);
    File jobJar = FileUtils.listFiles(testDir, new String[] { "jar" }, false).iterator().next();
    workMgr.onJarReceived(jobJar);
    File localDir = new File(LOCAL_INPUT_DIR);
    FileUtils.deleteDirectory(localDir);
    localDir.mkdirs();
    for (File f : testDir.listFiles()) {
        Files.copy(f.toPath(), new File(LOCAL_INPUT_DIR + f.getName()).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    }

    for (int i = 1; i <= 4; i++) {
        isRunning.getAndSet(true);
        File taskJson = new File(localDir, i + ".task");
        File jobData = new File(localDir, i + ".data");

        workMgr.onTaskReceived(taskJson);
        workMgr.onDataReceived(jobData);

        synchronized (isRunning) {
            while (isRunning.get()) {
                isRunning.wait();
            }
        }
    }

    isRunning.getAndSet(true);

    File combineTaskFile = new File(localDir, "20" + SrzTask.EXT);
    workMgr.onTaskReceived(combineTaskFile);

    SrzTask combineTask = persistMgr.readTaskFile(combineTaskFile);
    for (int id : combineTask.getDependencies()) {
        workMgr.onDataReceived(new File(localDir, id + SrzData.EXT));
    }

    synchronized (isRunning) {
        while (isRunning.get()) {
            isRunning.wait();
        }
    }

    Logger.getLogger(WorkManagerTest.class.getName()).log(Level.INFO, "Test Finished");
}

From source file:com.arpnetworking.configuration.jackson.JsonNodeDirectorySourceTest.java

@Test
public void testDirectoryNotDirectory() throws IOException {
    final File directory = new File(
            "./target/tmp/filter/JsonNodeDirectorySourceTest/testDirectoryNotDirectory");
    Files.deleteIfExists(directory.toPath());
    Files.createFile(directory.toPath());
    final JsonNodeDirectorySource source = new JsonNodeDirectorySource.Builder().setDirectory(directory)
            .build();/*from w  w  w. java 2  s  .c  o m*/
    Assert.assertFalse(source.getJsonNode().isPresent());
}

From source file:com.ethlo.geodata.util.ResourceUtil.java

private Map.Entry<Date, File> fetchZip(DataType dataType, String url, String zipEntry) throws IOException {
    final Resource resource = openConnection(url);
    return downloadIfNewer(dataType, resource, f -> {
        final File unzipDir = new File(tmpDir, dataType.name().toLowerCase() + "_unzip");
        ZipUtil.unpack(f.toFile(), unzipDir, name -> name.endsWith(zipEntry) ? zipEntry : null,
                StandardCharsets.UTF_8);
        final File file = new File(unzipDir, zipEntry);
        Assert.isTrue(file.exists(), "File " + file + " does not exist");
        return file.toPath();
    });//from w  ww .  j  a  v  a 2s  .c  om
}