Example usage for java.nio.file Path toString

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

Introduction

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

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:au.org.ands.vocabs.toolkit.provider.transform.GetMetadataTransformProvider.java

/**
 * Parse the files harvested from PoolParty and extract the
 * metadata.//  w w  w .  j  a va 2s . c  o  m
 * @param pPprojectId The PoolParty project id.
 * @return The results of the metadata extraction.
 */
public final HashMap<String, Object> extractMetadata(final String pPprojectId) {
    Path dir = Paths.get(ToolkitFileUtils.getMetadataOutputPath(pPprojectId));
    HashMap<String, Object> results = new HashMap<String, Object>();
    ConceptHandler conceptHandler = new ConceptHandler();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry : stream) {
            conceptHandler.setSource(entry.getFileName().toString());
            RDFFormat format = Rio.getParserFormatForFileName(entry.toString());
            RDFParser rdfParser = Rio.createParser(format);
            rdfParser.setRDFHandler(conceptHandler);
            FileInputStream is = new FileInputStream(entry.toString());
            logger.debug("Reading RDF:" + entry.toString());
            rdfParser.parse(is, entry.toString());
        }
    } catch (DirectoryIteratorException | IOException | RDFParseException | RDFHandlerException ex) {
        results.put(TaskStatus.EXCEPTION, "Exception in extractMetadata while Parsing RDF");
        logger.error("Exception in extractMetadata while Parsing RDF:", ex);
        return results;
    }
    results.putAll(conceptHandler.getMetadata());
    results.put("concept_count", Integer.toString(conceptHandler.getCountedConcepts()));
    return results;
}

From source file:ch.bender.evacuate.RunnerTest.java

/**
 * assertBackupChain//from   www  .  j a v a 2  s .  c o  m
 * <p>
 * @param aOrigFile1
 * @param aI
 */
private void assertBackupChain(Path aPath, int aTimes) {
    Path subDirToBackupRoot = myOrigDir.relativize(aPath);
    Path dst = myEvacuateDir.resolve(subDirToBackupRoot);
    Assert.assertTrue("Dst '" + dst.toString() + "' not exists", Files.exists(dst));

    for (int i = 1; i < aTimes; i++) {
        Path chained = Helper.appendNumberSuffix(dst, i);
        Assert.assertTrue("chained '" + chained.toString() + "' not exists", Files.exists(chained));
    }

    Path chained = Helper.appendNumberSuffix(dst, aTimes);
    Assert.assertTrue("chained '" + chained.toString() + "' should not exist", Files.notExists(chained));

}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRelativeSymlink() throws IOException, URISyntaxException {
    assumeFalse(Platform.isWindows());//from  w  ww .  ja v a  2 s .  co  m
    final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString());

        LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString());

        Files.createSymbolicLink(symLinkPath, relPath);
        getFileWithPutter(tempDir, symLinkPath);

    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:com.stereokrauts.stereoscope.webgui.messaging.handler.protocol.HttpServerRequestHandler.java

public Path createInvalidPath(Path other) {
    URL resource = this.getClass().getClassLoader().getResource(".");
    //URL resource = this.getClass().getClassLoader().getResource("index.html");
    if (resource != null) {
        try {/*ww w.j ava  2  s. c o  m*/
            URI uri = resource.toURI();
            return Paths.get(uri + other.toString());
        } catch (URISyntaxException e) {
            LOG.error("HTTP request handler: Desired resource not found.");
        }
    }
    // If all else fails, return null, but beware that this can cause PathAdjuster to NPE.
    return null;
}

From source file:org.bonitasoft.web.designer.studio.workspace.StudioWorkspaceResourceHandler.java

private void handleResourceException(Path filePath, Exception e) throws ResourceNotFoundException {
    if (e instanceof HttpClientErrorException) {
        if (HttpStatus.NOT_FOUND.equals(((HttpClientErrorException) e).getStatusCode())) {
            throw new ResourceNotFoundException(filePath.toString(), e);
        }// w  w w.  j av  a2  s .co  m
    }
    throw new RuntimeException("Unhandled exception", e);
}

From source file:com.romeikat.datamessie.core.base.util.FileUtil.java

public String createSubDir(final String parentDir, final String dir) {
    try {//w w  w.  jav a2  s  .  c om
        final Path subDir = Paths.get(parentDir, dir);
        Files.createDirectories(subDir);
        return subDir.toString();
    } catch (final Exception e) {
        LOG.error("Could not create subdirectory", e);
        return null;
    }
}

From source file:com.spectralogic.ds3client.metadata.MetadataAccessImpl_Test.java

@Test
public void testGettingMetadata() throws IOException, InterruptedException {
    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    try {/*ww w .  j  a va  2s  .c  o  m*/
        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        if (!Platform.isWindows()) {
            final PosixFileAttributes attributes = Files.readAttributes(filePath, PosixFileAttributes.class);
            final Set<PosixFilePermission> permissions = attributes.permissions();
            permissions.clear();
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.OWNER_WRITE);
            Files.setPosixFilePermissions(filePath, permissions);
        }

        final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();
        fileMapper.put(filePath.toString(), filePath);
        final Map<String, String> metadata = new MetadataAccessImpl(fileMapper.build())
                .getMetadataValue(filePath.toString());

        if (Platform.isWindows()) {
            assertEquals(metadata.size(), 13);
        } else {
            assertEquals(metadata.size(), 10);
        }

        if (Platform.isMac()) {
            assertTrue(metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_OS)
                    .toLowerCase().startsWith(Platform.MAC_SYSTEM_NAME));
        } else if (Platform.isLinux()) {
            assertTrue(metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_OS)
                    .toLowerCase().startsWith(Platform.LINUX_SYSTEM_NAME));
        } else if (Platform.isWindows()) {
            assertTrue(metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_OS)
                    .toLowerCase().startsWith(Platform.WINDOWS_SYSTEM_NAME));
        }

        if (Platform.isWindows()) {
            assertEquals("A",
                    metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_FLAGS));
        } else {
            assertEquals("100600",
                    metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_MODE));
            assertEquals("600(rw-------)",
                    metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_PERMISSION));
        }
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:io.stallion.dataAccess.file.FilePersisterBase.java

@Override
public List<T> fetchAll() {
    File target = new File(Settings.instance().getTargetFolder());
    if (!target.isDirectory()) {
        if (getItemController().isWritable()) {
            target.mkdirs();//ww  w. java 2  s .co m
        } else {
            throw new ConfigException(String.format(
                    "The JSON bucket %s (path %s) is read-only, but does not exist in the file system. Either create the folder, make it writable, or remove it from the configuration.",
                    getItemController().getBucket(), getBucketFolderPath()));
        }
    }
    TreeVisitor visitor = new TreeVisitor();
    Path folderPath = FileSystems.getDefault().getPath(getBucketFolderPath());
    try {
        Files.walkFileTree(folderPath, visitor);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    List<T> objects = new ArrayList<>();
    for (Path path : visitor.getPaths()) {
        if (!matchesExtension(path.toString())) {
            continue;
        }

        if (path.toString().contains(".#")) {
            continue;
        }
        if (path.getFileName().startsWith(".")) {
            continue;
        }
        T o = fetchOne(path.toString());
        if (o != null) {
            objects.add(o);
        }

    }
    objects.sort(new PropertyComparator<T>(sortField));
    if (sortDirection.toLowerCase().equals("desc")) {
        Collections.reverse(objects);
    }

    return objects;
}

From source file:de.ncoder.studipsync.storage.StandardPathResolver.java

@Override
public Path resolve(Path root, Download download, Path srcFile) {
    if (srcFile.isAbsolute()) {
        srcFile = srcFile.getRoot().relativize(srcFile);
    }//from   w  w w  .  ja v a  2s  .c  o  m
    Path dstRoot = resolve(root, download).getParent(); //only dir in root of src == dir of download ("Hauptordner")
    Path dstPath = dstRoot.resolve(srcFile.toString());
    log.debug(dstPath + " = " + dstRoot + " <~ " + srcFile);
    return dstPath;
}

From source file:de.decoit.visa.http.ajax.handlers.ExportRDFHandler.java

@Override
public void handle(HttpExchange he) throws IOException {
    log.info(he.getRequestURI().toString());

    // Get the URI of the request and extract the query string from it
    QueryString queryParameters = new QueryString(he.getRequestURI());

    // Create StringBuilder for the response
    String response = null;//from  ww  w  .  j av a  2 s.  c o m

    // Check if the query parameters are valid for this handler
    if (this.checkQueryParameters(queryParameters)) {
        try {
            Path outFile = TEBackend.getExportPath().resolve(queryParameters.get("file").get());

            TEBackend.RDF_MANAGER.writeRDF(outFile);

            JSONObject rv = new JSONObject();
            rv.put("status", AJAXServer.AJAX_SUCCESS);
            rv.put("file", outFile.toString());
            response = rv.toString();
        } catch (Throwable ex) {
            TEBackend.logException(ex, log);

            // Exception was thrown during cable removal
            JSONObject rv = new JSONObject();
            try {
                rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION);
                rv.put("type", ex.getClass().getSimpleName());
                rv.put("message", ex.getMessage());
                rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON());
            } catch (JSONException e) {
                /* Ignore */
            }

            response = rv.toString();
        }
    } else {
        // Missing or malformed query string, set response to error code
        JSONObject rv = new JSONObject();
        try {
            rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS);
        } catch (JSONException exc) {
            /* Ignore */
        }

        response = rv.toString();
    }

    // Send the response
    sendResponse(he, response);
}