List of usage examples for java.nio.file Path getName
Path getName(int index);
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPath.java
@Override public boolean startsWith(Path other) { if (other.isAbsolute() != isAbsolute()) { return false; } else if (other.getNameCount() > getNameCount()) { return false; } else {//from w w w.ja v a 2 s .c om for (int idx = 0; idx < other.getNameCount(); idx++) { Path otherElem = other.getName(idx); if (otherElem.getFileName().equals(this.elements.get(idx))) { return false; } } return true; } }
From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java
/*************************************************** * URL: /upload/jqueryUpload upload(): receives files * /* w w w.ja v a 2 s . c o m*/ * @param request * : MultipartHttpServletRequest auto passed * @param response * : HttpServletResponse auto passed * @return LinkedList<FileMeta> as json format ****************************************************/ @ResponseBody @RequestMapping(value = "/jqueryUpload", method = RequestMethod.POST) public FileMetaList jqueryUpload(@RequestParam final Long albumId, final MultipartHttpServletRequest request, final HttpServletResponse response) throws Exception { Assert.notNull(albumId, "No Album Id supplied !"); final FileMetaList files = new FileMetaList(); // 1. build an iterator final Iterator<String> itr = request.getFileNames(); // 2. get each file while (itr.hasNext()) { // 2.1 get next MultipartFile final MultipartFile mpf = request.getFile(itr.next()); // Here the file is uploaded final String originalFilename = mpf.getOriginalFilename(); final String contentType = mpf.getContentType(); final Matcher zipMatcher = UploadPicturesController.ZIP_CONTENT_TYPE_PATTERN.matcher(contentType); if (zipMatcher.find()) { // 2.3 create new fileMeta final FileMeta zipMeta = new FileMeta(); zipMeta.setFileName(originalFilename); zipMeta.setFileSize(mpf.getSize() / 1024 + " Kb"); zipMeta.setFileType(mpf.getContentType()); final List<Path> picturesPaths = this.processArchive(mpf); final Collection<Future<Void>> futures = new ArrayList<>(picturesPaths.size()); final ExecutorService executorService = Executors .newFixedThreadPool(Runtime.getRuntime().availableProcessors()); for (final Path picturePath : picturesPaths) { final Future<Void> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { final String pictureFileName = picturePath.getName(picturePath.getNameCount() - 1) .toString(); final byte[] pictureContents = Files.readAllBytes(picturePath); final FileMeta pictureMeta = new FileMeta(); try { final Picture picture = UploadPicturesController.this.createPicture(albumId, pictureFileName.toString(), pictureContents); final Long imageId = picture.getImage().getId(); final Long thumbnailId = picture.getThumbnail().getId(); pictureMeta.setFileName(pictureFileName); pictureMeta.setFileSize(pictureContents.length / 1024 + " Kb"); pictureMeta.setFileType(Files.probeContentType(picturePath)); pictureMeta.setUrl( response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId)); pictureMeta.setThumbnailUrl(response .encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId)); } catch (final PictureAlreadyExistsException e) { // Picture already exists ! pictureMeta.setError( UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG + e.getFilename()); } catch (final UnsupportedPictureTypeException e) { // Picture already exists ! pictureMeta.setError( UploadPicturesController.UNSUPPORTED_PICTURE_TYPE_MSG + e.getFilename()); } files.add(pictureMeta); return null; } }); futures.add(future); } for (final Future<Void> future : futures) { future.get(); } files.add(zipMeta); } final Matcher imgMatcher = UploadPicturesController.IMG_CONTENT_TYPE_PATTERN.matcher(contentType); if (imgMatcher.find()) { // 2.3 create new fileMeta final FileMeta fileMeta = new FileMeta(); try { final byte[] fileContents = mpf.getBytes(); final Picture picture = this.createPicture(albumId, originalFilename, fileContents); final Long imageId = picture.getImage().getId(); final Long thumbnailId = picture.getThumbnail().getId(); fileMeta.setFileName(originalFilename); fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb"); fileMeta.setFileType(mpf.getContentType()); fileMeta.setBytes(fileContents); fileMeta.setUrl(response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId)); fileMeta.setThumbnailUrl( response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId)); // 2.4 add to files files.add(fileMeta); } catch (final PictureAlreadyExistsException e) { // Picture already exists ! fileMeta.setError(UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG); } } } // result will be like this // {files:[{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]} return files; }
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPath.java
@Override public Path relativize(Path other) { if (other.isAbsolute() != isAbsolute() || other.getNameCount() < getNameCount()) { return other; } else if (other.getNameCount() == 0) { return this; } else {// ww w. j a v a 2s . c o m int idx = 0; for (; idx < getNameCount(); idx++) { if (!other.getName(idx).equals(getName(idx))) { return other; } } return other.subpath(idx - 1, other.getNameCount()); } }
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPath.java
@Override public Path resolve(Path other) { if (other.isAbsolute()) { return other; } else if (other.getNameCount() == 0) { return this; } else {//from ww w . java2 s.c o m List<String> elements = new ArrayList<>(this.elements); for (int idx = 0; idx < other.getNameCount(); idx++) { elements.add(other.getName(idx).toString()); } return new JcrPath(this.absolute, elements); } }
From source file:org.opennms.features.newts.converter.NewtsConverter.java
private ResourcePath buildResourcePath(final Path resourceDir) { final ResourcePath resourcePath; final Path relativeResourceDir = this.rrdDir.relativize(resourceDir); // Transform store-by-id path into store-by-foreign-source path if (relativeResourceDir.startsWith(Paths.get("snmp")) && !relativeResourceDir.startsWith(Paths.get("snmp", "fs"))) { // The part after snmp/ is considered the node ID final int nodeId = Integer.valueOf(relativeResourceDir.getName(1).toString()); // Get the foreign source for the node final ForeignId foreignId = foreignIds.get(nodeId); if (foreignId == null) { return null; }/*from ww w . j a v a2s . co m*/ // Make a store-by-foreign-source compatible path by using the found foreign ID and append the remaining path as-is resourcePath = ResourcePath.get( ResourcePath.get(ResourcePath.get("snmp", "fs"), foreignId.foreignSource, foreignId.foreignId), Iterables.transform(Iterables.skip(relativeResourceDir, 2), Path::toString)); } else { resourcePath = ResourcePath.get(relativeResourceDir); } return resourcePath; }
From source file:org.schedulesdirect.grabber.Grabber.java
private void removeUnusedPrograms(FileSystem vfs) throws IOException { final int[] i = new int[] { 0 }; final Path root = vfs.getPath("programs"); Files.walkFileTree(root, new FileVisitor<Path>() { @Override//ww w . j ava2 s .c o m public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String id = file.getName(file.getNameCount() - 1).toString(); id = id.substring(0, id.indexOf('.')); if (!activeProgIds.contains(id)) { if (LOG.isDebugEnabled()) LOG.debug(String.format("CacheCleaner: Unused '%s'", id)); Files.delete(file); ++i[0]; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); LOG.info(String.format("Removed %d unused program(s).", i[0])); }
From source file:org.schedulesdirect.grabber.Grabber.java
private void removeIgnoredStations(FileSystem vfs) throws IOException { final int[] i = new int[] { 0 }; final Path root = vfs.getPath("schedules"); Files.walkFileTree(root, new FileVisitor<Path>() { @Override/*from w w w . j a va 2 s. com*/ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String id = file.getName(file.getNameCount() - 1).toString(); id = id.substring(0, id.indexOf('.')); if (stationList != null && !stationList.contains(id)) { if (LOG.isDebugEnabled()) LOG.debug(String.format("CacheCleaner: Remove '%s'", id)); Files.delete(file); ++i[0]; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); LOG.info(String.format("Removed %d ignored station(s).", i[0])); }
From source file:org.apache.nifi.processors.standard.MergeContent.java
private String getPath(final FlowFile flowFile) { Path path = Paths.get(flowFile.getAttribute(CoreAttributes.PATH.key())); if (path.getNameCount() == 0) { return ""; }//w w w .jav a2s . co m if (".".equals(path.getName(0).toString())) { path = path.getNameCount() == 1 ? null : path.subpath(1, path.getNameCount()); } return path == null ? "" : path.toString() + "/"; }
From source file:org.esa.s2tbx.dataio.jp2.internal.JP2TileOpImage.java
private Path decompressTile(int tileIndex, int level) throws IOException { Path tileFile = PathUtils.get(cacheDir, PathUtils.getFileNameWithoutExtension(imageFile).toLowerCase() + "_tile_" + String.valueOf(tileIndex) + "_" + String.valueOf(level) + ".tif"); if ((!Files.exists(tileFile)) || (diffLastModifiedTimes(tileFile.toFile(), imageFile.toFile()) < 0L)) { final OpjExecutor decompress = new OpjExecutor(OpenJpegExecRetriever.getOpjDecompress()); final Map<String, String> params = new HashMap<String, String>() { {/* www.j av a 2 s .c o m*/ put("-i", GetIterativeShortPathNameW(imageFile.toString())); put("-r", String.valueOf(level)); put("-l", "20"); } }; String tileFileName; if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS && (tileFile.getParent() != null)) { tileFileName = Utils.GetIterativeShortPathNameW(tileFile.getParent().toString()) + File.separator + tileFile.getName(tileFile.getNameCount() - 1); } else { tileFileName = tileFile.toString(); } params.put("-o", tileFileName); params.put("-t", String.valueOf(tileIndex)); params.put("-p", String.valueOf(DataBuffer.getDataTypeSize(this.getSampleModel().getDataType()))); params.put("-threads", "ALL_CPUS"); if (decompress.execute(params) != 0) { logger.severe(decompress.getLastError()); tileFile = null; } else { logger.fine("Decompressed tile #" + String.valueOf(tileIndex) + " @ resolution " + String.valueOf(level)); } } return tileFile; }
From source file:edu.jhu.hlt.concrete.stanford.ConcreteStanfordRunner.java
public void run(Path inPath, Path outPath, Analytic<? extends TokenizedCommunication> analytic) { LOGGER.debug("Checking input and output directories."); try {//from w w w. j av a 2s .co m prepareInputOutput(inPath, outPath); } catch (IOException e) { LOGGER.error("Caught IOException when checking input and output directories.", e); } String lowerOutPathStr = inPath.toString().toLowerCase(); try { sed.disable(); // Outcomes of outPathStr ending: // No valid ending (program exit) // Ends with .concrete (first if) // Ends with .tar (else, first if) // Ends with .tar.gz (else, second if) boolean isTarExt = lowerOutPathStr.endsWith(".tar"); boolean isTarGzExt = lowerOutPathStr.endsWith(".tar.gz") || lowerOutPathStr.endsWith(".tgz"); boolean isConcreteExt = lowerOutPathStr.endsWith(".concrete") || lowerOutPathStr.endsWith(".comm"); int nElementsInitPath = inPath.getNameCount(); Path inputFileName = inPath.getName(nElementsInitPath - 1); // If no extention matches, exit. if (!isTarExt && !isTarGzExt && !isConcreteExt) { LOGGER.error("Input file extension was not '.concrete', '.comm', '.tar', or '.tar.gz'; exiting."); System.exit(1); } else if (isConcreteExt) { // IF .concrete, run single communication. LOGGER.info("Annotating single .concrete file at: {}", inPath.toString()); try (InputStream in = Files.newInputStream(inPath); BufferedInputStream bin = new BufferedInputStream(in, 1024 * 8 * 24);) { byte[] inputBytes = IOUtils.toByteArray(bin); Communication c = ser.fromBytes(inputBytes); WrappedCommunication annotated = analytic.annotate(c); Communication ar = annotated.getRoot(); WritableCommunication wc = new WritableCommunication(ar); if (Files.isDirectory(outPath)) wc.writeToFile(outPath.resolve(inputFileName), true); else wc.writeToFile(outPath, true); } catch (AnalyticException e) { LOGGER.error("Caught exception when running the analytic.", e); } } else { Path localOutPath; if (Files.isDirectory(outPath)) // if directory, use same extension as input. localOutPath = outPath.resolve(inputFileName); else localOutPath = outPath; // Iterate over the archive. AutoCloseableIterator<byte[]> iter; try (InputStream is = Files.newInputStream(inPath); BufferedInputStream bis = new BufferedInputStream(is, 1024 * 8 * 24);) { // open iterator based on file extension iter = isTarExt ? new TarArchiveEntryByteIterator(bis) : new TarGzArchiveEntryByteIterator(bis); try (OutputStream os = Files.newOutputStream(localOutPath); BufferedOutputStream bos = new BufferedOutputStream(os, 1024 * 8 * 24);) { TarArchiver archiver = isTarExt ? new TarArchiver(bos) : new TarArchiver(new GzipCompressorOutputStream(bos)); final StopWatch sw = new StopWatch(); sw.start(); int docCtr = 0; final AtomicInteger tokenCtr = new AtomicInteger(0); LOGGER.info("Iterating over archive: {}", inPath.toString()); while (iter.hasNext()) { Communication n = ser.fromBytes(iter.next()); LOGGER.info("Annotating communication: {}", n.getId()); try { TokenizedCommunication a = analytic.annotate(n); a.getTokenizations().parallelStream() .map(tkzToInt -> tkzToInt.getTokenList().getTokenListSize()) .forEach(ct -> tokenCtr.addAndGet(ct)); archiver.addEntry(new ArchivableCommunication(a.getRoot())); docCtr++; } catch (AnalyticException | IOException | StringIndexOutOfBoundsException e) { LOGGER.error("Caught exception processing document: " + n.getId(), e); } } try { archiver.close(); iter.close(); } catch (Exception e) { // unlikely. LOGGER.info("Caught exception closing iterator.", e); } sw.stop(); Duration rt = new Duration(sw.getTime()); Seconds st = rt.toStandardSeconds(); Minutes m = rt.toStandardMinutes(); int minutesInt = m.getMinutes(); LOGGER.info("Complete."); LOGGER.info("Runtime: approximately {} minutes.", minutesInt); LOGGER.info("Processed {} documents.", docCtr); final int tokens = tokenCtr.get(); LOGGER.info("Processed {} tokens.", tokens); if (docCtr > 0 && minutesInt > 0) { final float minutesFloat = minutesInt; float perMin = docCtr / minutesFloat; LOGGER.info("Processed approximately {} documents/minute.", perMin); LOGGER.info("Processed approximately {} tokens/second.", st.getSeconds() / minutesFloat); } } } } } catch (IOException | ConcreteException e) { LOGGER.error("Caught exception while running the analytic over archive.", e); } }