List of usage examples for java.nio.file Path getNameCount
int getNameCount();
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 ww w . ja va 2s . c om*/ 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.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 *///www . ja v a2 s . c o 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.apache.ofbiz.pricat.PricatEvents.java
/** * Upload a pricat.//from www . j a va 2s .co 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.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); }// w w w .jav a 2 s .co 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 */// w w w. j a va2s . 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:com.facebook.buck.util.Escaper.java
/** * Escapes forward slashes in a Path as a String that is safe to consume with other tools (such * as gcc). On Unix systems, this is equivalent to {@link java.nio.file.Path Path.toString()}. * @param path the Path to escape//w ww . j av a 2 s . co m * @return the escaped Path */ public static String escapePathForCIncludeString(Path path) { if (File.separatorChar != '\\') { return path.toString(); } StringBuilder result = new StringBuilder(); if (path.startsWith(File.separator)) { result.append("\\\\"); } for (Iterator<Path> iterator = path.iterator(); iterator.hasNext();) { result.append(iterator.next()); if (iterator.hasNext()) { result.append("\\\\"); } } if (path.getNameCount() > 0 && path.endsWith(File.separator)) { result.append("\\\\"); } return result.toString(); }
From source file:misc.FileHandler.java
/** * Returns the upper-most directory of the given file path. * /* ww w. ja v a 2s. co m*/ * @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:misc.FileHandler.java
/** * Returns whether the given file name is a valid file name indeed. In order * to be a valid file name, the file can be in an arbitrary level * sub-directory of the current folder. The file can also be in the current * directory. The name must not contain navigation elements like '..'. * //from w w w .j av a 2 s. c o m * @param fileName * the file name to check. * @return <code>true</code>, if the file name is valid. Otherwise, * <code>false</code> is returned. */ public static boolean isFileName(Path fileName) { if ((fileName == null) || FILE_NAME_BLACKLIST_PATTERN.matcher(fileName.toString()).matches()) { return false; } Path relativePath = Paths.get("./").resolve(fileName).normalize(); return (relativePath.getNameCount() >= 2) || !"".equals(relativePath.toString().trim()); }
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)); }//from w w w . j a va 2s .c o m return DefaultStoragePath.parse(pathPartials); }
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()); }