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:com.joyent.manta.util.MantaUtils.java

/**
 * Extracts the last file or directory from the path provided.
 *
 * @param path URL or Unix-style file path
 * @return the last file or directory in path
 *///from  ww  w .  j a v  a2  s  .com
public static String lastItemInPath(final String path) {
    Validate.notEmpty(path, "Path must not be null nor empty");

    final Path asNioPath = Paths.get(path);
    final int count = asNioPath.getNameCount();

    if (count < 1) {
        throw new IllegalArgumentException("Path doesn't have a single element to parse");
    }

    final Path lastPart = asNioPath.getName(count - 1);
    return lastPart.toString();
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Create an access point for a version, for a file. Don't duplicate it,
 * if it already exists./*from w ww.  jav  a 2s  .c  o m*/
 * @param version The version for which the access point is to be created.
 * @param format The format of the access point. If null, attempt
 * to deduce a format from the filename.
 * @param targetPath The path to the existing file.
 */
public static void createFileAccessPoint(final Version version, final String format, final Path targetPath) {
    String targetPathString;
    try {
        targetPathString = targetPath.toRealPath().toString();
    } catch (IOException e) {
        LOGGER.error("createFileAccessPoint failed calling " + "toRealPath() on file: " + targetPath.toString(),
                e);
        // Try toAbsolutePath() instead.
        targetPathString = targetPath.toAbsolutePath().toString();
    }
    List<AccessPoint> aps = getAccessPointsForVersionAndType(version, AccessPoint.FILE_TYPE);
    for (AccessPoint ap : aps) {
        if (targetPathString.equals(getToolkitPath(ap))) {
            // Already exists. Check the format.
            if (format != null && !format.equals(getFormat(ap))) {
                // Format changed.
                updateFormat(ap, format);
            }
            return;
        }
    }
    // No existing access point for this file, so create a new one.
    AccessPoint ap = new AccessPoint();
    ap.setVersionId(version.getId());
    ap.setType(AccessPoint.FILE_TYPE);
    JsonObjectBuilder jobPortal = Json.createObjectBuilder();
    JsonObjectBuilder jobToolkit = Json.createObjectBuilder();
    jobToolkit.add("path", targetPathString);
    // toolkitData is now done.
    ap.setToolkitData(jobToolkit.build().toString());
    ap.setPortalData("");
    // Persist what we have ...
    AccessPointUtils.saveAccessPoint(ap);
    // ... so that now we can get access to the
    // ID of the persisted object with ap.getId().
    String baseFilename = targetPath.getFileName().toString();
    jobPortal.add("uri", downloadPrefixProperty + ap.getId() + "/" + baseFilename);
    // Now work on the format. The following is messy. It's really very
    // much for the best if the portal provides the format.
    String deducedFormat;
    if (format == null) {
        // The format was not provided to us, so try to deduce it.
        // First, try the extension.
        String extension = FilenameUtils.getExtension(baseFilename);
        deducedFormat = EXTENSION_TO_FILE_FORMAT_MAP.get(extension);
        if (deducedFormat == null) {
            // No luck with the extension, so try probing.
            try {
                String mimeType = Files.probeContentType(targetPath);
                if (mimeType == null) {
                    // Give up.
                    deducedFormat = "Unknown";
                } else {
                    deducedFormat = MIMETYPE_TO_FILE_FORMAT_MAP.get(mimeType);
                    if (deducedFormat == null) {
                        // Give up.
                        deducedFormat = "Unknown";
                    }
                }
            } catch (IOException e) {
                LOGGER.error("createFileAccessPoint failed to get " + "MIME type of file: " + targetPathString,
                        e);
                // Give up.
                deducedFormat = "Unknown";
            }
        }
    } else {
        // The format was provided to us, so use that. Much easier.
        deducedFormat = format;
    }
    jobPortal.add("format", deducedFormat);
    // portalData is now complete.
    ap.setPortalData(jobPortal.build().toString());
    AccessPointUtils.updateAccessPoint(ap);
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Get the full path of the directory used to store all
 * the files referred to by the task./*from  w w  w .j  av  a 2  s.c  o  m*/
 * @param taskInfo The TaskInfo object representing the task.
 * @param extraPath An optional additional path component to be added
 * at the end. If not required, pass in null or an empty string.
 * @return The full path of the directory used to store the
 * vocabulary data.
 */
public static String getTaskOutputPath(final TaskInfo taskInfo, final String extraPath) {
    // NB: We call makeSlug() on the vocabulary slug, which should
    // (as of ANDS-Registry-Core commit e365392831ae)
    // not really be necessary.
    Path path = Paths.get(ToolkitConfig.DATA_FILES_PATH).resolve(makeSlug(taskInfo.getVocabulary().getOwner()))
            .resolve(makeSlug(taskInfo.getVocabulary().getSlug()))
            .resolve(makeSlug(taskInfo.getVersion().getTitle()));
    if (extraPath != null && (!extraPath.isEmpty())) {
        path = path.resolve(extraPath);
    }
    return path.toString();
}

From source file:org.apache.taverna.databundle.DataBundles.java

public static Path setError(Path errorPath, String message, String trace, Path... causedBy) throws IOException {
    errorPath = withExtension(errorPath, DOT_ERR);
    // Silly \n-based format
    List<String> errorDoc = new ArrayList<>();
    for (Path cause : causedBy) {
        Path relCause = errorPath.getParent().relativize(cause);
        errorDoc.add(relCause.toString());
    }/*  www . j a v a2s  .c o m*/
    errorDoc.add(""); // Our magic separator
    errorDoc.add(message);
    errorDoc.add(trace);
    checkExistingAnyExtension(errorPath);
    write(errorPath, errorDoc, UTF8, TRUNCATE_EXISTING, CREATE);
    return errorPath;
}

From source file:org.apache.taverna.databundle.DataBundles.java

private static void checkExistingAnyExtension(Path path) throws IOException, FileAlreadyExistsException {
    Path existing = anyExtension(path);
    if (!path.equals(existing))
        throw new FileAlreadyExistsException(existing.toString());
}

From source file:com.amazonaws.codepipeline.jenkinsplugin.CompressionTools.java

public static List<File> addFilesToCompress(final Path pathToCompress, final BuildListener listener)
        throws IOException {
    final List<File> files = new ArrayList<>();

    if (pathToCompress != null) {
        Files.walkFileTree(pathToCompress, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override//from ww w  .j ava2  s . c  om
                    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                            throws IOException {
                        files.add(file.toFile());
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFileFailed(final Path file, final IOException e)
                            throws IOException {
                        if (e != null) {
                            LoggingHelper.log(listener, "Failed to visit file '%s'. Error: %s.",
                                    file.toString(), e.getMessage());
                            LoggingHelper.log(listener, e);
                            throw e;
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    }

    return files;
}

From source file:de.teamgrit.grit.report.PdfConcatenator.java

/**
 * Write the pdfs to the file.//from w  w  w.j  a  v a2s  .co m
 *
 * @param outFile
 *            the out file
 * @param folderWithPdfs
 *            the folder with pdfs
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static void writeFiles(File outFile, Path folderWithPdfs) throws IOException {

    FileWriterWithEncoding writer = new FileWriterWithEncoding(outFile, "UTF-8", true);

    File[] files = folderWithPdfs.toFile().listFiles();
    if (files.length > 0) {
        for (File file : files) {

            // We only want the the PDFs as input
            if ("pdf".equals(FilenameUtils.getExtension(file.getName()))) {
                writer.append("\\includepdf[pages={1-}]{").append(file.getAbsolutePath()).append("} \n");
            }
        }
    } else {
        LOGGER.warning("No Reports available in the specified folder: " + folderWithPdfs.toString());
    }
    writer.close();
}

From source file:io.uploader.drive.drive.DriveOperations.java

private static String findMineType(Path path) {
    if (path == null) {
        return null;
    }/* w w  w.ja v  a2s. co m*/
    try {
        //return Files.probeContentType(path) ;
        return tika.detect(new FileInputStream(path.toFile()));
    } catch (IOException e) {
        logger.error("Error occurred while attempting to determine the mine type of " + path.toString(), e);
        return null;
    }
}

From source file:org.jetbrains.webdemo.backend.executor.ExecutorUtils.java

public static ExecutionResult executeCompiledFiles(Map<String, byte[]> files, String mainClass,
        List<Path> kotlinRuntimeJars, String arguments, Path executorsPolicy, boolean isJunit)
        throws Exception {
    Path codeDirectory = null;
    try {//from  w  ww .jav a 2s.co  m
        codeDirectory = storeFilesInTemporaryDirectory(files);
        JavaExecutorBuilder executorBuilder = new JavaExecutorBuilder().enableAssertions().setMemoryLimit(32)
                .enableSecurityManager().setPolicyFile(executorsPolicy).addToClasspath(kotlinRuntimeJars)
                .addToClasspath(jarFiles).addToClasspath(codeDirectory);
        if (isJunit) {
            executorBuilder.addToClasspath(junit);
            executorBuilder.addToClasspath(hamcrest);
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JunitExecutor");
            executorBuilder.addArgument(codeDirectory.toString());
        } else {
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JavaExecutor");
            executorBuilder.addArgument(mainClass);
        }

        for (String argument : arguments.split(" ")) {
            if (argument.trim().isEmpty())
                continue;
            executorBuilder.addArgument(argument);
        }

        ProgramOutput output = executorBuilder.build().execute();
        return parseOutput(output.getStandardOutput(), isJunit);
    } finally {
        try {
            if (codeDirectory != null) {
                Files.walkFileTree(codeDirectory, new FileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        return FileVisitResult.CONTINUE;
                    }

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

                    @Override
                    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                        return FileVisitResult.TERMINATE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        } catch (IOException e) {
            ErrorWriter.getInstance().writeExceptionToExceptionAnalyzer(e, "Can't delete code directory");
        }
    }
}

From source file:com.datazuul.iiif.presentation.api.ManifestGenerator.java

private static void addPage(String urlPrefix, String imageDirectoryName, List<Canvas> canvases, int pageCounter,
        Path file) throws IOException, URISyntaxException {
    Path fileName = file.getFileName();
    System.out.println(fileName.toAbsolutePath());

    BufferedImage bimg = ImageIO.read(file.toFile());
    int width = bimg.getWidth();
    int height = bimg.getHeight();

    // add a new page
    Canvas canvas1 = new Canvas(urlPrefix + imageDirectoryName + "/canvas/canvas-" + pageCounter,
            "p-" + pageCounter, height, width);
    canvases.add(canvas1);//  w ww  .j a  va 2s. c om

    List<Image> images = new ArrayList<>();
    canvas1.setImages(images);

    Image image1 = new Image();
    image1.setOn(canvas1.getId());
    images.add(image1);

    ImageResource imageResource1 = new ImageResource(
            urlPrefix + imageDirectoryName + "/" + fileName.toString());
    imageResource1.setHeight(height);
    imageResource1.setWidth(width);
    image1.setResource(imageResource1);

    Service service1 = new Service(urlPrefix + imageDirectoryName + "/" + fileName.toString() + "?");
    service1.setContext("http://iiif.io/api/image/2/context.json");
    service1.setProfile("http://iiif.io/api/image/2/level1.json");
    imageResource1.setService(service1);
}