Example usage for java.nio.file Path getName

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

Introduction

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

Prototype

Path getName(int index);

Source Link

Document

Returns a name element of this path as a Path object.

Usage

From source file:org.dataconservancy.dcs.util.FilePathUtil.java

/**
 * This method checks whether a file path contains any illegal characters.
 * @param file the file to check/*from w w  w  .j a  v  a2 s .c om*/
 * @return boolean true if the path is OK, false otherwise
 */
public static boolean hasValidFilePath(File file) {
    Path path = file.toPath();
    for (int i = 0; i < path.getNameCount(); i++) {
        if (StringUtils.containsAny(path.getName(i).toString(), getCharacterBlackList())) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.ofbiz.pricat.PricatEvents.java

/**
 * Upload a pricat./*from w ww. j  av  a 2 s.  c o  m*/
 */
public static String pricatUpload(HttpServletRequest request, HttpServletResponse response) {
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        return "parse_pricat";
    } else {
        String action = request.getParameter("action");
        if (UtilValidate.isNotEmpty(action) && "downloadPricat".equals(action)) {
            String sequenceNumString = (String) request.getParameter("sequenceNum");
            long sequenceNum = -1;
            if (UtilValidate.isNotEmpty(sequenceNumString)) {
                try {
                    sequenceNum = Long.valueOf(sequenceNumString);
                } catch (NumberFormatException e) {
                    // do nothing
                }
            }
            String originalPricatFileName = (String) request.getSession()
                    .getAttribute(PricatParseExcelHtmlThread.PRICAT_FILE);
            String pricatFileName = originalPricatFileName;
            if (sequenceNum > 0 && AbstractPricatParser.isCommentedExcelExists(request, sequenceNum)) {
                GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
                String userLoginId = userLogin.getString("userLoginId");
                pricatFileName = InterfacePricatParser.tempFilesFolder + userLoginId + "/" + sequenceNum
                        + ".xlsx";
            }
            if (UtilValidate.isNotEmpty(pricatFileName) && UtilValidate.isNotEmpty(originalPricatFileName)) {
                try {
                    Path path = Paths.get(pricatFileName);
                    byte[] bytes = Files.readAllBytes(path);
                    path = Paths.get(originalPricatFileName);
                    UtilHttp.streamContentToBrowser(response, bytes, "application/octet-stream",
                            URLEncoder.encode(path.getName(path.getNameCount() - 1).toString(), "UTF-8"));
                } catch (MalformedURLException e) {
                    Debug.logError(e.getMessage(), module);
                    return "error";
                } catch (IOException e) {
                    Debug.logError(e.getMessage(), module);
                    return "error";
                }
                request.getSession().removeAttribute(PricatParseExcelHtmlThread.PRICAT_FILE);
                return "download";
            }
        }
    }
    return "success";
}

From source file:org.dataconservancy.dcs.util.UriUtility.java

/**
* Create a URI string for a file in a BagIt bag,
* @param file The file to check.  This doesn't have to be an actual existing file
* @param basedir The directory to make the file URI relative to.  Can be null.  If not null, the basedir must be
*                in the path of the file parameter, or an exception will be thrown
* @return A string representing the URI to the file on the local disk.
* @throws URISyntaxException if there is an error in the URI syntax
*//*ww  w . j  a  v a2 s . co  m*/
public static URI makeBagUriString(File file, File basedir) throws URISyntaxException {
    if (basedir == null) {
        basedir = new File(".");
    }

    Path relativePath = file.toPath();

    if (relativePath.startsWith(basedir.toPath())) {
        relativePath = basedir.toPath().relativize(file.toPath());
    }

    String path = FilenameUtils.separatorsToUnix(relativePath.toString());
    if (relativePath.getNameCount() > 1) {

        Path uriAuthority = relativePath.getName(0);
        Path uriPath = relativePath.subpath(1, relativePath.getNameCount());
        path = FilenameUtils.separatorsToUnix(uriPath.toString());
        if (!uriPath.isAbsolute()) {
            path = "/" + path;
        }

        return new URI(BAG_URI_SCHEME, uriAuthority.toString(), path, null, null);
    }

    return new URI(BAG_URI_SCHEME, path, null, null, null);
}

From source file:org.dataconservancy.packaging.impl.UriUtility.java

/**
 * Create a URI string for a file in a BagIt bag,
 *
 * @param file The file to check. This doesn't have to be an actual existing file
 * @param basedir The directory to make the file URI relative to. Can be null. If not null, the basedir must be in
 *        the path of the file parameter, or an exception will be thrown
 * @return A string representing the URI to the file on the local disk.
 * @throws URISyntaxException if there is an error in the URI syntax
 *///from w w w .ja v  a  2 s .c o  m
public static URI makeBagUriString(final File file, final File basedir) throws URISyntaxException {
    final File dir = basedir == null ? new File(".") : basedir;

    Path relativePath = file.toPath();

    if (relativePath.startsWith(dir.toPath())) {
        relativePath = dir.toPath().relativize(file.toPath());
    }

    String path = FilenameUtils.separatorsToUnix(relativePath.toString());
    if (relativePath.getNameCount() > 1) {

        final Path uriAuthority = relativePath.getName(0);
        final Path uriPath = relativePath.subpath(1, relativePath.getNameCount());
        path = FilenameUtils.separatorsToUnix(uriPath.toString());
        if (!uriPath.isAbsolute()) {
            path = "/" + path;
        }

        return new URI(BAG_URI_SCHEME, uriAuthority.toString(), path, null, null);
    }

    return new URI(BAG_URI_SCHEME, path, null, null, null);
}

From source file:org.roda.core.plugins.plugins.characterization.SiegfriedPluginUtils.java

private static <T extends IsRODAObject> List<LinkingIdentifier> runSiegfriedOnRepresentationOrFile(
        Plugin<T> plugin, ModelService model, String aipId, String representationId,
        List<String> fileDirectoryPath, String fileId, Path path) throws RequestNotValidException,
        GenericException, NotFoundException, AuthorizationDeniedException, PluginException {
    List<LinkingIdentifier> sources = new ArrayList<>();

    if (FSUtils.exists(path)) {
        String siegfriedOutput = SiegfriedPluginUtils.runSiegfriedOnPath(path);

        final JsonNode jsonObject = JsonUtils.parseJson(siegfriedOutput);
        final JsonNode files = jsonObject.get("files");

        for (JsonNode file : files) {
            Path fullFsPath = Paths.get(file.get("filename").asText());
            Path relativeFsPath = path.relativize(fullFsPath);

            String jsonFileId = fullFsPath.getFileName().toString();

            List<String> jsonFilePath = new ArrayList<>(fileDirectoryPath);
            if (fileId != null) {
                jsonFilePath.add(fileId);
            }/*from   w ww. j av  a 2s.c  o m*/
            for (int j = 0; j < relativeFsPath.getNameCount()
                    && StringUtils.isNotBlank(relativeFsPath.getName(j).toString()); j++) {
                jsonFilePath.add(relativeFsPath.getName(j).toString());
            }
            jsonFilePath.remove(jsonFilePath.size() - 1);

            ContentPayload payload = new StringContentPayload(file.toString());
            model.createOrUpdateOtherMetadata(aipId, representationId, jsonFilePath, jsonFileId,
                    SiegfriedPlugin.FILE_SUFFIX, RodaConstants.OTHER_METADATA_TYPE_SIEGFRIED, payload, false);

            sources.add(PluginHelper.getLinkingIdentifier(aipId, representationId, jsonFilePath, jsonFileId,
                    RodaConstants.PRESERVATION_LINKING_OBJECT_SOURCE));

            // Update PREMIS files
            final JsonNode matches = file.get("matches");
            for (JsonNode match : matches) {
                String format = null;
                String version = null;
                String pronom = null;
                String mime = null;
                String[] pluginVersion = plugin.getVersion().split("\\.");

                if ("1".equals(pluginVersion[0])) {
                    if (Integer.parseInt(pluginVersion[1]) > 4) {
                        if ("pronom".equalsIgnoreCase(match.get("ns").textValue())) {
                            format = match.get("format").textValue();
                            version = match.get("version").textValue();
                            pronom = match.get("id").textValue();
                            mime = match.get("mime").textValue();
                        }
                    } else {
                        if ("pronom".equalsIgnoreCase(match.get("id").textValue())) {
                            format = match.get("format").textValue();
                            version = match.get("version").textValue();
                            pronom = match.get("puid").textValue();
                            mime = match.get("mime").textValue();
                        }
                    }
                }

                PremisV3Utils.updateFormatPreservationMetadata(model, aipId, representationId, jsonFilePath,
                        jsonFileId, format, version, pronom, mime, true);
            }
        }
    }

    return sources;
}

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 w  w  w  .  j  ava  2 s  .c  om*/
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:misc.FileHandler.java

/**
 * Returns the upper-most directory of the given file path.
 * /*from   w  w w .jav a 2 s  . c om*/
 * @param fileName
 *            the file path to check. Must be a valid path to a file or just
 *            the name of a file (can be inexistent).
 * @return the possibly inexistent upper-most directory of the given file
 *         path. If the file path consists only of the file name, then the
 *         path <code>.</code> is returned.
 */
public static Path getUpperMostDirectory(Path fileName) {
    if (!isFileName(fileName)) {
        throw new IllegalArgumentException("fileName must be a valid file name!");
    }

    Path relativePath = ROOT_PATH.resolve(fileName).normalize();
    if (relativePath.getNameCount() >= 2) {
        return relativePath.getName(0);
    } else {
        return ROOT_PATH;
    }
}

From source file:org.roda.core.storage.fs.FSUtils.java

public static StoragePath getStoragePath(Path relativePath) throws RequestNotValidException {
    List<String> pathPartials = new ArrayList<>();

    for (int i = 0; i < relativePath.getNameCount(); i++) {
        String pathPartial = relativePath.getName(i).toString();
        pathPartials.add(decodePathPartial(pathPartial));
    }// ww w.j  av a  2s  . co  m

    return DefaultStoragePath.parse(pathPartials);
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public static void downloadAndInstall(String url, String archiveFileName, Path installPath,
        IProgressMonitor monitor) throws IOException {
    Exception error = null;/*from   ww  w.java2s.  c  o  m*/
    for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) {
        try {
            URL dl = new URL(url);
            Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$
            Files.createDirectories(dlDir);
            Path archivePath = dlDir.resolve(archiveFileName);
            URLConnection conn = dl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING);

            boolean isWin = Platform.getOS().equals(Platform.OS_WIN32);

            // extract
            ArchiveInputStream archiveIn = null;
            try {
                String compressor = null;
                String archiver = null;
                if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.BZIP2;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                    compressor = CompressorStreamFactory.GZIP;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.XZ;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                    archiver = ArchiveStreamFactory.ZIP;
                }

                InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                if (compressor != null) {
                    in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                }
                archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                        .getNextEntry()) {
                    if (entry.isDirectory()) {
                        continue;
                    }

                    // Magic file for git tarballs
                    Path path = Paths.get(entry.getName());
                    if (path.endsWith("pax_global_header")) { //$NON-NLS-1$
                        continue;
                    }

                    // Strip the first directory of the path
                    Path entryPath;
                    switch (path.getName(0).toString()) {
                    case "i586":
                    case "i686":
                        // Cheat for Intel
                        entryPath = installPath.resolve(path);
                        break;
                    default:
                        entryPath = installPath.resolve(path.subpath(1, path.getNameCount()));
                    }

                    Files.createDirectories(entryPath.getParent());

                    if (entry instanceof TarArchiveEntry) {
                        TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                        if (tarEntry.isLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount()));
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath));
                        } else if (tarEntry.isSymbolicLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, linkPath);
                        } else {
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                        if (!isWin && !tarEntry.isSymbolicLink()) {
                            int mode = tarEntry.getMode();
                            Files.setPosixFilePermissions(entryPath, toPerms(mode));
                        }
                    } else {
                        Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } finally {
                if (archiveIn != null) {
                    archiveIn.close();
                }
            }
            return;
        } catch (IOException | CompressorException | ArchiveException e) {
            error = e;
            // retry
        }
    }

    // out of retries
    if (error instanceof IOException) {
        throw (IOException) error;
    } else {
        throw new IOException(error);
    }
}

From source file:org.kie.workbench.common.migration.cli.ToolConfigTest.java

@Test
public void testGetTarget() throws ParseException {
    final String[] args = { "-t", "/fake/dir" };

    CommandLine cl = new CLIManager().parse(args);
    Path path = new ToolConfig(cl).getTarget();
    assertEquals(2, path.getNameCount());
    assertEquals("fake", path.getName(0).toString());
}