List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java
private void commitUpdates(StorageRequest request) throws StorageException { try {//from w w w .j a va 2s . co m for (String contentUri : updateMap.get(request.getId())) { Path contentIdDir = getTempContentItemDir(request.getId(), new URI(contentUri)); Path target = getContentItemDir(new URI(contentUri)); try { if (Files.exists(contentIdDir)) { if (Files.exists(target)) { List<Path> files = listPaths(target); for (Path file : files) { if (!Files.isDirectory(file)) { Files.deleteIfExists(file); } } } Files.createDirectories(target.getParent()); Files.move(contentIdDir, target, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { LOGGER.debug( "Unable to move files by simple rename, resorting to copy. This will impact performance.", e); try { Path createdTarget = Files.createDirectories(target); List<Path> files = listPaths(contentIdDir); Files.copy(files.get(0), Paths.get(createdTarget.toAbsolutePath().toString(), files.get(0).getFileName().toString())); } catch (IOException e1) { throw new StorageException("Unable to commit changes for request: " + request.getId(), e1); } } } } catch (URISyntaxException e) { throw new StorageException(e); } finally { rollback(request); } }
From source file:com.liferay.sync.engine.file.system.SyncWatchEventProcessor.java
protected void addFile(SyncWatchEvent syncWatchEvent) throws Exception { final Path targetFilePath = Paths.get(syncWatchEvent.getFilePathName()); if (FileUtil.notExists(targetFilePath) || sanitizeFileName(targetFilePath) || isInErrorState(targetFilePath)) { return;//from w w w . ja v a 2 s. c o m } Path parentTargetFilePath = targetFilePath.getParent(); final SyncFile parentSyncFile = SyncFileService.fetchSyncFile(parentTargetFilePath.toString()); if ((parentSyncFile == null) || (!parentSyncFile.isSystem() && (parentSyncFile.getTypePK() == 0))) { queueSyncWatchEvent(parentTargetFilePath.toString(), syncWatchEvent); return; } SyncFile syncFile = SyncFileService.fetchSyncFile(targetFilePath.toString()); if (syncFile == null) { syncFile = SyncFileService.fetchSyncFile(FileKeyUtil.getFileKey(targetFilePath)); if (!verifySite(syncFile, parentSyncFile)) { syncFile = null; } } if (syncFile == null) { Runnable runnable = new Runnable() { @Override public void run() { try { SyncSite syncSite = SyncSiteService.fetchSyncSite(parentSyncFile.getRepositoryId(), _syncAccountId); if ((syncSite == null) || !syncSite.isActive() || !FileUtil.checkFilePath(targetFilePath)) { return; } SyncFileService.addFileSyncFile(targetFilePath, parentSyncFile.getTypePK(), parentSyncFile.getRepositoryId(), _syncAccountId); } catch (Exception e) { if (SyncFileService.fetchSyncFile(targetFilePath.toString()) == null) { _logger.error(e.getMessage(), e); } } } }; _executorService.execute(runnable); return; } Path sourceFilePath = Paths.get(syncFile.getFilePathName()); if (targetFilePath.equals(sourceFilePath)) { if (isPendingTypePK(syncFile) || (syncFile.getState() == SyncFile.STATE_IN_PROGRESS)) { queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent); return; } if (FileUtil.isModified(syncFile)) { SyncFileService.updateFileSyncFile(targetFilePath, _syncAccountId, syncFile); } } else if (FileUtil.exists(sourceFilePath)) { try { if ((Files.size(targetFilePath) == 0) || FileUtil.isModified(syncFile, targetFilePath) || isInErrorState(sourceFilePath)) { SyncFileService.addFileSyncFile(targetFilePath, parentSyncFile.getTypePK(), parentSyncFile.getRepositoryId(), _syncAccountId); } else { SyncFileService.copySyncFile(syncFile, targetFilePath, parentSyncFile.getTypePK(), parentSyncFile.getRepositoryId(), _syncAccountId); } } catch (Exception e) { if (SyncFileService.fetchSyncFile(targetFilePath.toString()) == null) { _logger.error(e.getMessage(), e); } } return; } else if (parentTargetFilePath.equals(sourceFilePath.getParent())) { if (isPendingTypePK(syncFile) || (syncFile.getState() == SyncFile.STATE_IN_PROGRESS)) { queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent); return; } SyncFileService.updateFileSyncFile(targetFilePath, _syncAccountId, syncFile); } else { if (isPendingTypePK(syncFile) || (syncFile.getState() == SyncFile.STATE_IN_PROGRESS)) { queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent); return; } SyncFileService.moveFileSyncFile(targetFilePath, parentSyncFile.getTypePK(), _syncAccountId, syncFile); Path sourceFileNameFilePath = sourceFilePath.getFileName(); if (!sourceFileNameFilePath.equals(targetFilePath.getFileName())) { SyncFileService.updateFileSyncFile(targetFilePath, _syncAccountId, syncFile); } } SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(_syncAccountId); if (syncAccount.getState() == SyncAccount.STATE_CONNECTED) { SyncWatchEvent relatedSyncWatchEvent = SyncWatchEventService.fetchSyncWatchEvent( SyncWatchEvent.EVENT_TYPE_DELETE, syncWatchEvent.getFilePathName(), syncWatchEvent.getTimestamp()); if (relatedSyncWatchEvent != null) { _processedSyncWatchEventIds.add(relatedSyncWatchEvent.getSyncWatchEventId()); } } }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void getPort() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path portIn1 = DataBundles.getPort(inputs, "in1"); assertFalse(Files.exists(portIn1)); assertEquals(inputs, portIn1.getParent()); }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java
public boolean deleteSiteGitRepo(String site) { boolean toReturn; // Get the Sandbox Path Path siteSandboxPath = buildRepoPath(GitRepositories.SANDBOX, site); // Get parent of that (since every site has two repos: Sandbox and Published) Path sitePath = siteSandboxPath.getParent(); // Get a file handle to the parent and delete it File siteFolder = sitePath.toFile(); try {// ww w . j a v a2 s. co m Repository sboxRepo = sandboxes.get(site); sboxRepo.close(); sandboxes.remove(site); RepositoryCache.close(sboxRepo); sboxRepo = null; Repository pubRepo = published.get(site); pubRepo.close(); published.remove(site); RepositoryCache.close(pubRepo); pubRepo = null; FileUtils.deleteDirectory(siteFolder); toReturn = true; logger.debug("Deleted site: " + site + " at path: " + sitePath); } catch (IOException e) { logger.error("Failed to delete site: " + site + " at path: " + sitePath + " exception " + e.toString()); toReturn = false; } return toReturn; }
From source file:com.liferay.sync.engine.file.system.SyncWatchEventProcessor.java
protected boolean sanitizeFileName(Path filePath) { if (OSDetector.isWindows()) { return false; }//www . j a va 2s. c o m String fileName = String.valueOf(filePath.getFileName()); String sanitizedFileName = FileUtil.getSanitizedFileName(fileName, FilenameUtils.getExtension(fileName)); if (!sanitizedFileName.equals(fileName)) { String sanitizedFilePathName = FileUtil.getFilePathName(String.valueOf(filePath.getParent()), sanitizedFileName); sanitizedFilePathName = FileUtil.getNextFilePathName(sanitizedFilePathName); FileUtil.checkFilePath(filePath); FileUtil.moveFile(filePath, Paths.get(sanitizedFilePathName)); return true; } return false; }
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>() { {/* w w w .ja va 2 s. c om*/ 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:info.novatec.inspectit.rcp.storage.util.DataRetriever.java
/** * Downloads and saves locally wanted files associated with given {@link StorageData}. Files * will be saved in passed directory. The caller can specify the type of the files to download * by passing the proper {@link StorageFileType}s to the method. * /* w w w .j a v a2 s. co m*/ * @param cmrRepositoryDefinition * {@link CmrRepositoryDefinition}. * @param storageData * {@link StorageData}. * @param directory * Directory to save objects. compressBefore Should data files be compressed on the * fly before sent. * @param compressBefore * Should data files be compressed on the fly before sent. * @param decompressContent * If the useGzipCompression is <code>true</code>, this parameter will define if the * received content will be de-compressed. If false is passed content will be saved * to file in the same format as received, but the path of the file will be altered * with additional '.gzip' extension at the end. * @param subMonitor * {@link SubMonitor} for process reporting. * @param fileTypes * Files that should be downloaded. * @throws BusinessException * If directory to save does not exists. If files wanted can not be found on the * server. * @throws IOException * If {@link IOException} occurs. */ public void downloadAndSaveStorageFiles(CmrRepositoryDefinition cmrRepositoryDefinition, StorageData storageData, final Path directory, boolean compressBefore, boolean decompressContent, SubMonitor subMonitor, StorageFileType... fileTypes) throws BusinessException, IOException { if (!Files.isDirectory(directory)) { throw new BusinessException("Download and save storage files for storage " + storageData + " to the path " + directory.toString() + ".", StorageErrorCodeEnum.FILE_DOES_NOT_EXIST); } Map<String, Long> allFiles = getFilesFromCmr(cmrRepositoryDefinition, storageData, fileTypes); if (MapUtils.isNotEmpty(allFiles)) { PostDownloadRunnable postDownloadRunnable = new PostDownloadRunnable() { @Override public void process(InputStream content, String fileName) throws IOException { String[] splittedFileName = fileName.split("/"); Path writePath = directory; // first part is empty, second is storage id, we don't need it for (int i = 2; i < splittedFileName.length; i++) { writePath = writePath.resolve(splittedFileName[i]); } // ensure all dirs are created if (Files.notExists(writePath.getParent())) { Files.createDirectories(writePath.getParent()); } Files.copy(content, writePath, StandardCopyOption.REPLACE_EXISTING); } }; this.downloadAndSaveObjects(cmrRepositoryDefinition, allFiles, postDownloadRunnable, compressBefore, decompressContent, subMonitor); } }
From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java
@Override public void forceDelete(RepositoryFileReference ref) throws IOException { Path relativePath = this.fileSystem.getPath(BackendUtils.getPathInsideRepo(ref)); Path fileToDelete = this.makeAbsolute(relativePath); try {/* w w w . j ava 2 s . c o m*/ this.provider.delete(fileToDelete); // Quick hack for deletion of the mime type information // Alternative: superclass: protected void // deleteMimeTypeInformation(RepositoryFileReference ref) throws IOException // However, this would again call this method, where we would have to check for the // extension, too. // Therefore, we directly delete the information file Path mimeTypeFile = fileToDelete.getParent().resolve(ref.getFileName() + Constants.SUFFIX_MIMETYPE); this.provider.delete(mimeTypeFile); } catch (IOException e) { if (!(e instanceof NoSuchFileException)) { // only if file did exist and something else went wrong: complain :) // (otherwise, silently ignore the error) FilebasedRepository.logger.debug("Could not delete file", e); throw e; } } }
From source file:org.olat.ims.qti.qpool.QTIImportProcessor.java
private List<DocInfos> traverseZip_nio(File file) throws IOException { List<DocInfos> docInfos = new ArrayList<>(); Path fPath = FileSystems.newFileSystem(file.toPath(), null).getPath("/"); if (fPath != null) { DocInfosVisitor visitor = new DocInfosVisitor(); Files.walkFileTree(fPath, visitor); List<Path> xmlFiles = visitor.getXmlFiles(); for (Path xmlFile : xmlFiles) { InputStream in = Files.newInputStream(xmlFile); Document doc = readXml(in); if (doc != null) { DocInfos d = new DocInfos(); d.setDocument(doc);// w ww . j a v a 2 s. c o m d.setRoot(xmlFile.getParent()); d.setFilename(xmlFile.getFileName().toString()); docInfos.add(d); } } } return docInfos; }
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"); }/*from www.j a v a 2 s.co m*/ } } 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; }