List of usage examples for java.nio.file Path relativize
Path relativize(Path other);
From source file:io.redlink.solrlib.embedded.EmbeddedCoreContainer.java
@Override @SuppressWarnings({ "squid:S3725", "squid:S3776" }) protected synchronized void init(ExecutorService executorService) throws IOException { Preconditions.checkState(Objects.isNull(coreContainer), "Already initialized!"); if (solrHome == null) { solrHome = Files.createTempDirectory("solr-home"); log.debug("No solr-home set, using temp directory {}", solrHome); deleteOnShutdown = true;/* w w w . j ava 2 s . com*/ } final Path absoluteSolrHome = this.solrHome.toAbsolutePath(); if (Files.isDirectory(absoluteSolrHome)) { log.trace("solr-home exists: {}", absoluteSolrHome); } else { Files.createDirectories(absoluteSolrHome); log.debug("Created solr-home: {}", absoluteSolrHome); } final Path lib = absoluteSolrHome.resolve("lib"); if (Files.isDirectory(lib)) { log.trace("lib-directory exists: {}", lib); } else { Files.createDirectories(lib); log.debug("Created solr-lib directory: {}", lib); } final Path solrXml = absoluteSolrHome.resolve("solr.xml"); if (!Files.exists(solrXml)) { log.info("no solr.xml found, creating new at {}", solrXml); try (PrintStream writer = new PrintStream(Files.newOutputStream(solrXml, StandardOpenOption.CREATE))) { writer.printf("<!-- Generated by %s on %tF %<tT -->%n", getClass().getSimpleName(), new Date()); writer.println("<solr>"); writer.printf(" <str name=\"%s\">%s</str>%n", "sharedLib", absoluteSolrHome.relativize(lib)); writer.println("</solr>"); } } else { log.trace("found solr.xml: {}", solrXml); } for (SolrCoreDescriptor coreDescriptor : coreDescriptors) { final String coreName = coreDescriptor.getCoreName(); if (availableCores.containsKey(coreName)) { log.warn("CoreName-Clash: {} already initialized. Skipping {}", coreName, coreDescriptor.getClass()); continue; } final Path coreDir = absoluteSolrHome.resolve(coreName); Files.createDirectories(coreDir); coreDescriptor.initCoreDirectory(coreDir, lib); final Properties coreProperties = new Properties(); final Path corePropertiesFile = coreDir.resolve("core.properties"); if (Files.exists(corePropertiesFile)) { try (InputStream inStream = Files.newInputStream(corePropertiesFile, StandardOpenOption.CREATE)) { coreProperties.load(inStream); } log.debug("core.properties for {} found, updating", coreName); } else { log.debug("Creating new core {} in {}", coreName, coreDir); } coreProperties.setProperty("name", coreName); try (OutputStream outputStream = Files.newOutputStream(corePropertiesFile)) { coreProperties.store(outputStream, null); } if (coreDescriptor.getNumShards() > 1 || coreDescriptor.getReplicationFactor() > 1) { log.warn("Deploying {} to EmbeddedCoreContainer, ignoring config of shards={},replication={}", coreName, coreDescriptor.getNumShards(), coreDescriptor.getReplicationFactor()); } availableCores.put(coreName, coreDescriptor); } log.info("Starting {} in solr-home '{}'", getClass().getSimpleName(), absoluteSolrHome); coreContainer = CoreContainer.createAndLoad(absoluteSolrHome, solrXml); availableCores.values().forEach(coreDescriptor -> { final String coreName = coreDescriptor.getCoreName(); try (SolrClient solrClient = createSolrClient(coreName)) { final NamedList<Object> coreStatus = CoreAdminRequest.getStatus(coreName, solrClient) .getCoreStatus(coreName); final NamedList<Object> indexStatus = coreStatus == null ? null : (NamedList<Object>) coreStatus.get("index"); final Object lastModified = indexStatus == null ? null : indexStatus.get("lastModified"); // lastModified is null if there was never a update scheduleCoreInit(executorService, coreDescriptor, lastModified == null); } catch (SolrServerException | IOException e) { if (log.isDebugEnabled()) { log.error("Error initializing core {}", coreName, e); } //noinspection ThrowableResultOfMethodCallIgnored coreInitExceptions.put(coreName, e); } }); }
From source file:org.fao.geonet.kernel.harvest.harvester.geonet.Aligner.java
private Element extractValidMetadataForImport(DirectoryStream<Path> files, Element info) throws IOException, JDOMException { Element metadataValidForImport; final String finalPreferredSchema = preferredSchema; String infoSchema = "_none_"; if (info != null && info.getContentSize() != 0) { Element general = info.getChild("general"); if (general != null && general.getContentSize() != 0) { if (general.getChildText("schema") != null) { infoSchema = general.getChildText("schema"); }// w w w. ja v a 2 s.com } } Path lastUnknownMetadataFolderName = null; if (Log.isDebugEnabled(Geonet.MEF)) Log.debug(Geonet.MEF, "Multiple metadata files"); Map<String, Pair<String, Element>> mdFiles = new HashMap<String, Pair<String, Element>>(); for (Path file : files) { if (Files.isRegularFile(file)) { Element metadata = Xml.loadFile(file); try { Path parent = file.getParent(); Path parent2 = parent.getParent(); String metadataSchema = dataMan.autodetectSchema(metadata, null); // If local node doesn't know metadata // schema try to load next xml file. if (metadataSchema == null) { continue; } String currFile = "Found metadata file " + parent2.relativize(file); mdFiles.put(metadataSchema, Pair.read(currFile, metadata)); } catch (NoSchemaMatchesException e) { // Important folder name to identify metadata should be ../../ Path parent = file.getParent(); if (parent != null) { Path parent2 = parent.getParent(); if (parent2 != null) { lastUnknownMetadataFolderName = parent2.relativize(parent); } } log.debug("No schema match for " + lastUnknownMetadataFolderName + file.getFileName() + "."); } catch (NullPointerException e) { log.error("Check the schema directory"); log.error(e); } } } if (mdFiles.size() == 0) { log.debug("No valid metadata file found" + ((lastUnknownMetadataFolderName == null) ? "" : (" in " + lastUnknownMetadataFolderName)) + "."); return null; } // 1st: Select metadata with schema in info file Pair<String, Element> mdInform = mdFiles.get(infoSchema); if (mdInform != null) { log.debug(mdInform.one() + " with info.xml schema (" + infoSchema + ")."); metadataValidForImport = mdInform.two(); return metadataValidForImport; } // 2nd: Select metadata with preferredSchema mdInform = mdFiles.get(finalPreferredSchema); if (mdInform != null) { log.debug(mdInform.one() + " with preferred schema (" + finalPreferredSchema + ")."); metadataValidForImport = mdInform.two(); return metadataValidForImport; } // Lastly: Select the first metadata in the map String metadataSchema = (String) mdFiles.keySet().toArray()[0]; mdInform = mdFiles.get(metadataSchema); log.debug(mdInform.one() + " with known schema (" + metadataSchema + ")."); metadataValidForImport = mdInform.two(); return metadataValidForImport; }
From source file:processing.app.debug.Compiler.java
private boolean isPathInASubfolder(Path sketchPath, Path path) { return sketchPath.relativize(path).getNameCount() > 1; }
From source file:com.android.repository.util.InstallerUtilTest.java
public void testUnzip() throws Exception { if (new MockFileOp().isWindows()) { // can't run on windows. return;// w ww .j a va 2 s. c om } // zip needs a real file, so no MockFileOp for us. FileOp fop = FileOpUtils.create(); Path root = Files.createTempDirectory("InstallerUtilTest"); Path outRoot = Files.createTempDirectory("InstallerUtilTest"); try { Path file1 = root.resolve("foo"); Files.write(file1, "content".getBytes()); Path dir1 = root.resolve("bar"); Files.createDirectories(dir1); Path file2 = dir1.resolve("baz"); Files.write(file2, "content2".getBytes()); Files.createSymbolicLink(root.resolve("link1"), dir1); Files.createSymbolicLink(root.resolve("link2"), file2); Path outZip = outRoot.resolve("out.zip"); try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(outZip.toFile()); Stream<Path> listing = Files.walk(root)) { listing.forEach(path -> { try { ZipArchiveEntry archiveEntry = (ZipArchiveEntry) out.createArchiveEntry(path.toFile(), root.relativize(path).toString()); out.putArchiveEntry(archiveEntry); if (Files.isSymbolicLink(path)) { archiveEntry.setUnixMode(UnixStat.LINK_FLAG | archiveEntry.getUnixMode()); out.write(path.getParent().relativize(Files.readSymbolicLink(path)).toString() .getBytes()); } else if (!Files.isDirectory(path)) { out.write(Files.readAllBytes(path)); } out.closeArchiveEntry(); } catch (Exception e) { fail(); } }); } Path unzipped = outRoot.resolve("unzipped"); Files.createDirectories(unzipped); InstallerUtil.unzip(outZip.toFile(), unzipped.toFile(), fop, 1, new FakeProgressIndicator()); assertEquals("content", new String(Files.readAllBytes(unzipped.resolve("foo")))); Path resultDir = unzipped.resolve("bar"); Path resultFile2 = resultDir.resolve("baz"); assertEquals("content2", new String(Files.readAllBytes(resultFile2))); Path resultLink = unzipped.resolve("link1"); assertTrue(Files.isDirectory(resultLink)); assertTrue(Files.isSymbolicLink(resultLink)); assertTrue(Files.isSameFile(resultLink, resultDir)); Path resultLink2 = unzipped.resolve("link2"); assertEquals("content2", new String(Files.readAllBytes(resultLink2))); assertTrue(Files.isSymbolicLink(resultLink2)); assertTrue(Files.isSameFile(resultLink2, resultFile2)); } finally { fop.deleteFileOrFolder(root.toFile()); fop.deleteFileOrFolder(outRoot.toFile()); } }
From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java
private S3Element parse(Path elem, Path bucket) throws IOException { S3Object object = new S3Object(); String bucketName = bucket.getFileName().toString(); object.setBucketName(bucketName);/*w w w .java 2 s .c om*/ String key = bucket.relativize(elem).toString().replaceAll("%2F", "/"); boolean dir = key.endsWith("/") || key.isEmpty(); object.setKey(key); ObjectMetadata metadata = new ObjectMetadata(); BasicFileAttributes attr = Files.readAttributes(elem, BasicFileAttributes.class); metadata.setLastModified(new Date(attr.lastAccessTime().toMillis())); if (dir) { metadata.setContentLength(0); object.setObjectContent(null); } else { metadata.setContentLength(attr.size()); object.setObjectContent(new ByteArrayInputStream(Files.readAllBytes(elem))); } object.setObjectMetadata(metadata); AccessControlList permission = createAclPermission(elem, bucketName); return new S3Element(object, permission, dir); }
From source file:org.eclipse.winery.repository.importing.CSARImporter.java
/** * Imports a file from the filesystem to the repository * /*from www. j a v a2 s . com*/ * @param p the file to read from * @param fref the "file" to put the content to * @param tmf the TOSCAMetaFile object used to determine the mimetype. Must not be null. * @param rootPath used to relativize p to determine the mime type * @throws InvalidCSARException */ private void importFile(Path p, RepositoryFileReference fref, TOSCAMetaFile tmf, Path rootPath, final List<String> errors) { if (tmf == null) { throw new IllegalStateException("tmf must not be null"); } try (InputStream is = Files.newInputStream(p); BufferedInputStream bis = new BufferedInputStream(is)) { String mediaType = tmf.getMimeType(p.relativize(rootPath).toString()); if (mediaType == null) { // Manually find out mime type try { mediaType = Utils.getMimeType(bis, p.getFileName().toString()); } catch (IOException e) { errors.add(String.format("No MimeType given for %1$s (%2$s)", p.getFileName(), e.getMessage())); return; } if (mediaType == null) { errors.add(String.format("No MimeType given for %1$s", p.getFileName())); return; } } try { Repository.INSTANCE.putContentToFile(fref, bis, MediaType.valueOf(mediaType)); } catch (IllegalArgumentException | IOException e) { throw new IllegalStateException(e); } } catch (IOException e1) { throw new IllegalStateException("Could not work on generated temporary files", e1); } }
From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java
/** * for SingleMovie or DiscFolders/*from w ww .j a va2s .c o m*/ * * @param dataSource * the data source * @param movieDir * the movie folder * @param isDiscFolder * is the movie in a disc folder? */ private void createSingleMovieFromDir(Path dataSource, Path movieDir, boolean isDiscFolder) { LOGGER.info( "Parsing single movie directory: " + movieDir + " (are we a disc folder? " + isDiscFolder + ")"); Path relative = dataSource.relativize(movieDir); // STACKED FOLDERS - go up ONE level (only when the stacked folder == // stacking marker) // movie/CD1/ & /movie/CD2 -> go up // movie CD1/ & /movie CD2 -> NO - there could be other files/folders there // if (!Utils.getFolderStackingMarker(relative.toString()).isEmpty() && // level > 1) { if (!Utils.getFolderStackingMarker(relative.toString()).isEmpty() && Utils.getFolderStackingMarker(relative.toString()).equals(movieDir.getFileName().toString())) { movieDir = movieDir.getParent(); } Movie movie = movieList.getMovieByPath(movieDir); HashSet<Path> allFiles = getAllFilesRecursive(movieDir, 3); // need 3 (was // 2) because // extracted BD filesFound.add(movieDir.toAbsolutePath()); // our global cache filesFound.addAll(allFiles); // our global cache // convert to MFs (we need it anyways at the end) ArrayList<MediaFile> mfs = new ArrayList<>(); for (Path file : allFiles) { mfs.add(new MediaFile(file)); } allFiles.clear(); if (movie == null) { LOGGER.debug("| movie not found; looking for NFOs"); movie = new Movie(); String bdinfoTitle = ""; // title parsed out of BDInfo String videoName = ""; // title from file // *************************************************************** // first round - try to parse NFO(s) first // *************************************************************** // TODO: add movie.addMissingMetaData(otherMovie) to get merged movie from // multiple NFOs ;) for (MediaFile mf : mfs) { if (mf.getType().equals(MediaFileType.NFO)) { // PathMatcher matcher = // FileSystems.getDefault().getPathMatcher("glob:*.[nN][fF][oO]"); LOGGER.info("| parsing NFO " + mf.getFileAsPath()); Movie nfo = null; switch (MovieModuleManager.MOVIE_SETTINGS.getMovieConnector()) { case XBMC: nfo = MovieToXbmcNfoConnector.getData(mf.getFileAsPath()); if (nfo == null) { // try the other nfo = MovieToKodiNfoConnector.getData(mf.getFileAsPath()); } if (nfo == null) { // try the other nfo = MovieToMpNfoConnector.getData(mf.getFileAsPath()); } break; case KODI: nfo = MovieToKodiNfoConnector.getData(mf.getFileAsPath()); // not needed at the moment since kodi is downwards compatible // if (nfo == null) { // // try the other // nfo = MovieToXbmcNfoConnector.getData(mf.getFileAsPath()); // } if (nfo == null) { // try the other nfo = MovieToMpNfoConnector.getData(mf.getFileAsPath()); } break; case MP: nfo = MovieToMpNfoConnector.getData(mf.getFileAsPath()); if (nfo == null) { // try the other nfo = MovieToKodiNfoConnector.getData(mf.getFileAsPath()); } // not needed at the moment since kodi is downwards compatible // if (nfo == null) { // // try the other // nfo = MovieToXbmcNfoConnector.getData(mf.getFileAsPath()); // } break; } if (nfo != null) { movie = nfo; } // was NFO, but parsing exception. try to find at least imdb id within if (movie.getImdbId().isEmpty()) { try { String imdb = Utils.readFileToString(mf.getFileAsPath()); imdb = ParserUtils.detectImdbId(imdb); if (!imdb.isEmpty()) { LOGGER.debug("| Found IMDB id: " + imdb); movie.setImdbId(imdb); } } catch (IOException e) { LOGGER.warn("| couldn't read NFO " + mf); } } } // end NFO else if (mf.getType().equals(MediaFileType.TEXT)) { try { String txtFile = Utils.readFileToString(mf.getFileAsPath()); String bdinfo = StrgUtils.substr(txtFile, ".*Disc Title:\\s+(.*?)[\\n\\r]"); if (!bdinfo.isEmpty()) { LOGGER.debug("| Found Disc Title in BDInfo.txt: " + bdinfo); bdinfoTitle = WordUtils.capitalizeFully(bdinfo); } String imdb = ParserUtils.detectImdbId(txtFile); if (!imdb.isEmpty()) { LOGGER.debug("| Found IMDB id: " + imdb); movie.setImdbId(imdb); } } catch (Exception e) { LOGGER.warn("| couldn't read TXT " + mf.getFilename()); } } else if (mf.getType().equals(MediaFileType.VIDEO)) { videoName = mf.getBasename(); } } // end NFO MF loop movie.setNewlyAdded(true); movie.setDateAdded(new Date()); } // end first round - we might have a filled movie if (movie.getTitle().isEmpty()) { // get the "cleaner" name/year combo // ParserUtils.ParserInfo video = ParserUtils.getCleanerString(new // String[] { videoName, movieDir.getName(), bdinfoTitle }); // does not work reliable yet - user folder name String[] video = ParserUtils.detectCleanMovienameAndYear(movieDir.getFileName().toString()); movie.setTitle(video[0]); if (!video[1].isEmpty()) { movie.setYear(video[1]); } } // if the String 3D is in the movie dir, assume it is a 3D movie Matcher matcher = video3DPattern.matcher(movieDir.getFileName().toString()); if (matcher.find()) { movie.setVideoIn3D(true); } // get edition from name movie.setEdition(MovieEdition.getMovieEditionFromString(movieDir.getFileName().toString())); movie.setPath(movieDir.toAbsolutePath().toString()); movie.setDataSource(dataSource.toString()); // movie.findActorImages(); // TODO: find as MediaFiles LOGGER.debug("| store movie into DB as: " + movie.getTitle()); movieList.addMovie(movie); if (movie.getMovieSet() != null) { LOGGER.debug("| movie is part of a movieset"); // movie.getMovieSet().addMovie(movie); movie.getMovieSet().insertMovie(movie); movieList.sortMoviesInMovieSet(movie.getMovieSet()); movie.getMovieSet().saveToDb(); } // *************************************************************** // second round - now add all the other known files // *************************************************************** addMediafilesToMovie(movie, mfs); // *************************************************************** // third round - try to match unknown graphics like title.ext or // filename.ext as poster // *************************************************************** if (movie.getArtworkFilename(MediaFileType.POSTER).isEmpty()) { for (MediaFile mf : mfs) { if (mf.getType().equals(MediaFileType.GRAPHIC)) { LOGGER.debug("| parsing unknown graphic " + mf.getFilename()); List<MediaFile> vid = movie.getMediaFiles(MediaFileType.VIDEO); if (vid != null && !vid.isEmpty()) { String vfilename = vid.get(0).getFilename(); if (FilenameUtils.getBaseName(vfilename).equals(FilenameUtils.getBaseName(mf.getFilename())) // basename // match || FilenameUtils.getBaseName(Utils.cleanStackingMarkers(vfilename)).trim() .equals(FilenameUtils.getBaseName(mf.getFilename())) // basename // w/o // stacking || movie.getTitle().equals(FilenameUtils.getBaseName(mf.getFilename()))) { // title // match mf.setType(MediaFileType.POSTER); movie.addToMediaFiles(mf); } } } } } // *************************************************************** // check if that movie is an offline movie // *************************************************************** boolean isOffline = false; for (MediaFile mf : movie.getMediaFiles(MediaFileType.VIDEO)) { if ("disc".equalsIgnoreCase(mf.getExtension())) { isOffline = true; } } movie.setOffline(isOffline); movie.reEvaluateStacking(); movie.saveToDb(); }
From source file:org.eclipse.winery.repository.importing.CSARImporter.java
/** * Modifies given allFiles object to include all files given by the incl pattern * /*from www .ja va 2s.c om*/ * Semantics: Add all files from localRoot to allFiles matching the pattern */ private void handleInclude(final Include incl, final Path localRoot, final Set<Path> allFiles) { final PathMatcher pathMatcher = localRoot.getFileSystem().getPathMatcher("glob:" + incl.getPattern()); try { Files.walkFileTree(localRoot, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relFile = localRoot.relativize(file); if (pathMatcher.matches(relFile)) { allFiles.add(file); } return CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (pathMatcher.matches(dir)) { Set<Path> filesToAdd = CSARImporter.this.getAllFiles(dir); allFiles.addAll(filesToAdd); return SKIP_SUBTREE; } else { return CONTINUE; } } }); } catch (IOException e) { throw new IllegalStateException(e); } }
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
protected void openPolicyTab(File policy, boolean readOnly) { ////from w w w .jav a 2s. co m // Sanity check // assert policy != null; assert policy.isFile(); if (policy == null || !policy.isFile()) { throw new IllegalArgumentException("You must specify a file."); } Status status; Path relativePath; String base; try { // // Grab our working repository // Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath(); final Git git = Git.open(repoPath.toFile()); // // Get our status // relativePath = repoPath.relativize(Paths.get(policy.getPath())); base = relativePath.toString(); if (logger.isDebugEnabled()) { logger.debug("Status on base: " + base); } status = git.status().addPath(base).call(); } catch (NoWorkTreeException | IOException | GitAPIException e) { logger.error("Failed to get status on " + policy + " " + e); AdminNotification.error("Could not get Git status on the file."); return; } // // Check if its clean // if (status.isClean() == false) { // // Check if its conflicting // for (String conflict : status.getConflicting()) { if (conflict.equals(base)) { // // Yes - we won't be able to edit it // AdminNotification.error("Policy has conflicts with master, please synchronize the repository."); return; } } } // // Check to see if there already is a tab open // Iterator<Component> iter = self.tabSheet.iterator(); while (iter.hasNext()) { Component c = iter.next(); if (c instanceof PolicyEditor) { Object data = ((PolicyEditor) c).getData(); if (data != null && data instanceof File && ((File) data).equals(policy)) { self.tabSheet.setSelectedTab(c); return; } } } // // No tab is open, create a new one // PolicyEditor editor = null; try { editor = new PolicyEditor(policy, this.treeContainer, readOnly); } catch (IOException e) { logger.error("Failed to open policy"); editor = null; } if (editor != null) { editor.setWidth("100%"); Tab tab = self.tabSheet.addTab(editor); editor.setTab(tab); tab.setClosable(true); self.tabSheet.setSelectedTab(editor); } else { AdminNotification.error("The Policy File is not a Xacml 3.0 policy."); } }
From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java
private Path find(String bucketName, final String key) { final Path bucket = find(bucketName); if (bucket == null || !Files.exists(bucket)) { return null; }// w ww . ja v a2 s . c om try { final String fileKey = key.replaceAll("/", "%2F"); final List<Path> matches = new ArrayList<Path>(); Files.walkFileTree(bucket, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { String relativize = bucket.relativize(dir).toString(); if (relativize.equals(fileKey)) { matches.add(dir); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String relativize = bucket.relativize(file).toString(); if (relativize.equals(fileKey)) { matches.add(file); } return FileVisitResult.CONTINUE; } }); if (!matches.isEmpty()) return matches.iterator().next(); } catch (IOException e) { throw new AmazonServiceException("Problem getting mock S3Element: ", e); } return null; }