List of usage examples for java.nio.file Path resolve
default Path resolve(String other)
From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java
@Override public CopyObjectResult copyObject(String sourceBucketName, String sourceKey, String destinationBucketName, String destinationKey) throws AmazonClientException { Path src = find(sourceBucketName, sourceKey); if (src != null && Files.exists(src)) { Path bucket = find(destinationBucketName); Path dest = bucket.resolve(destinationKey.replaceAll("/", "%2F")); try {//w ww. ja va2 s . c o m Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new AmazonServiceException("Problem copying mock objects: ", e); } return new CopyObjectResult(); } throw new AmazonServiceException("object source not found"); }
From source file:com.nartex.RichFileManager.java
@Override public JSONObject moveItem() { String itemName = this.get.get("old"); boolean error = false; JSONObject array = null;/* w w w .java2 s.co m*/ String tmp[] = itemName.split("/"); String filename = tmp[tmp.length - 1]; int pos = itemName.lastIndexOf("/"); Path fileTo = null; if (pos > 0 && itemName.contains("..")) { String path = itemName.substring(0, pos + 1); fileTo = this.documentRoot.resolve(cleanPreview(path)); // from subfolder, folder could be .. check later in root } else { fileTo = this.documentRoot; } //String root = this.get.get("root"); // slash at beginning and end String folder = this.get.get("new"); if (folder.trim().startsWith("/")) { // absolute path is not allowed, this is then just root folder folder = folder.trim().replaceFirst("/", ""); } Path fileFrom = null; try { fileFrom = this.documentRoot.resolve(cleanPreview(itemName)); fileTo = fileTo.resolve(folder).resolve(filename).normalize(); if (!fileTo.toString().contains(this.documentRoot.toString())) { log.error("file is not in root folder " + this.documentRoot + " but " + fileTo); return this.error(sprintf(lang("ERROR_RENAMING_FILE"), filename + "#" + this.get.get("new"))); } log.info("moving file from " + this.documentRoot.resolve(cleanPreview(this.get.get("old"))) + " to " + this.documentRoot.resolve(folder).resolve(filename)); if (Files.exists(fileTo)) { if (Files.isDirectory(fileTo)) { this.error(sprintf(lang("DIRECTORY_ALREADY_EXISTS"), this.documentRoot.resolve(folder).resolve(filename).toString())); error = true; } else { // fileTo.isFile this.error(sprintf(lang("FILE_ALREADY_EXISTS"), filename)); error = true; } } else { Files.move(fileFrom, fileTo); } } catch (Exception e) { if (Files.isDirectory(fileFrom)) { this.error(sprintf(lang("ERROR_RENAMING_DIRECTORY"), filename + "#" + this.get.get("new"))); } else { this.error(sprintf(lang("ERROR_RENAMING_FILE"), filename + "#" + this.get.get("new"))); } error = true; } if (!error) { array = new JSONObject(); try { folder = folder.replace("..", "");// if its an allowed up mpvement array.put("Error", ""); array.put("Code", 0); array.put("Old Path", itemName); array.put("Old Name", filename); array.put("New Path", getPreviewFolder() + folder); array.put("New Name", filename); } catch (Exception e) { this.error("JSONObject error"); } } return array; }
From source file:com.qwazr.library.archiver.ArchiverTool.java
public void decompress_dir(final Path sourceDir, String sourceExtension, final Path destDir, final String destExtension) throws IOException, CompressorException { if (!Files.exists(sourceDir)) throw new FileNotFoundException("The source directory does not exist: " + sourceDir.toAbsolutePath()); if (!Files.exists(destDir)) throw new FileNotFoundException( "The destination directory does not exist: " + destDir.toAbsolutePath()); final Path[] sourceFiles; try (final Stream<Path> stream = Files.list(sourceDir)) { sourceFiles = stream.filter(p -> Files.isRegularFile(p)).toArray(Path[]::new); }/*from www. j a v a 2 s. c om*/ if (sourceFiles == null) return; for (Path sourceFile : sourceFiles) { final String fileName = sourceFile.getFileName().toString(); final String ext = FilenameUtils.getExtension(fileName); if (!sourceExtension.equals(ext)) continue; String newName = FilenameUtils.getBaseName(fileName); if (destExtension != null) newName += '.' + destExtension; final Path destFile = destDir.resolve(newName); if (Files.exists(destFile)) continue; decompress(sourceFile, destFile); } }
From source file:fll.web.FullTournamentTest.java
/** * @param testDataConn/* w w w. j av a2 s . c o m*/ * @param sourceTournament * @throws SQLException * @throws IOException * @throws InterruptedException */ private void uploadSchedule(final Connection testDataConn, final Tournament sourceTournament, final Path outputDirectory) throws SQLException, IOException, InterruptedException { if (TournamentSchedule.scheduleExistsInDatabase(testDataConn, sourceTournament.getTournamentID())) { final TournamentSchedule schedule = new TournamentSchedule(testDataConn, sourceTournament.getTournamentID()); final Path outputFile = outputDirectory .resolve(sanitizeFilename(sourceTournament.getName()) + "_schedule.csv"); schedule.writeToCSV(outputFile.toFile()); // upload the saved file IntegrationTestUtils.loadPage(selenium, TestUtils.URL_ROOT + "admin/index.jsp"); final WebElement fileInput = selenium.findElement(By.name("scheduleFile")); fileInput.sendKeys(outputFile.toAbsolutePath().toString()); selenium.findElement(By.id("upload-schedule")).click(); Assert.assertFalse(IntegrationTestUtils.isElementPresent(selenium, By.id("error"))); // check that we're on the choose headers page and set the header // mappings Assert.assertTrue(selenium.getCurrentUrl().contains("chooseSubjectiveHeaders")); final Collection<CategoryColumnMapping> mappings = CategoryColumnMapping.load(testDataConn, sourceTournament.getTournamentID()); for (final CategoryColumnMapping map : mappings) { final Select select = new Select(selenium.findElement(By.name(map.getCategoryName() + ":header"))); select.selectByVisibleText(map.getScheduleColumn()); } selenium.findElement(By.id("submit")).click(); Thread.sleep(IntegrationTestUtils.WAIT_FOR_PAGE_LOAD_MS); // check that we don't have hard violations and skip past soft // violations assertThat(selenium.getCurrentUrl(), not(containsString("displayHardViolations"))); if (selenium.getCurrentUrl().contains("displaySoftViolations")) { selenium.findElement(By.id("yes")).click(); Thread.sleep(IntegrationTestUtils.WAIT_FOR_PAGE_LOAD_MS); } // set event divisions if (selenium.getCurrentUrl().contains("promptForEventDivision")) { selenium.findElement(By.id("yes")).click(); Thread.sleep(IntegrationTestUtils.WAIT_FOR_PAGE_LOAD_MS); // assume the values are fine assertThat(selenium.getCurrentUrl(), containsString("displayEventDivisionConfirmation")); selenium.findElement(By.id("yes")).click(); Thread.sleep(IntegrationTestUtils.WAIT_FOR_PAGE_LOAD_MS); } // check that it all worked Assert.assertFalse(IntegrationTestUtils.isElementPresent(selenium, By.id("error"))); Assert.assertTrue(IntegrationTestUtils.isElementPresent(selenium, By.id("success"))); } }
From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java
/** * store in the memory map/*from ww w.j a v a 2s . c o m*/ * @param bucketName bucket where persist * @param elem */ private void persist(String bucketName, S3Element elem) { Path bucket = find(bucketName); String key = elem.getS3Object().getKey().replaceAll("/", "%2F"); Path resolve = bucket.resolve(key); if (Files.exists(resolve)) try { Files.delete(resolve); } catch (IOException e1) { // ignore } try { Files.createFile(resolve); S3ObjectInputStream objectContent = elem.getS3Object().getObjectContent(); if (objectContent != null) { byte[] byteArray = IOUtils.toByteArray(objectContent); Files.write(resolve, byteArray); } } catch (IOException e) { throw new AmazonServiceException("Problem creating mock element: ", e); } }
From source file:org.apache.solr.SolrTestCaseJ4.java
/** * Call this from @BeforeClass to set up the test harness and update handler with no cores. * * @param solrHome The solr home directory. * @param xmlStr - the text of an XML file to use. If null, use the what's the absolute minimal file. * @throws Exception Lost of file-type things can go wrong. *///from w w w . ja v a 2s.c om public static void setupNoCoreTest(Path solrHome, String xmlStr) throws Exception { if (xmlStr == null) xmlStr = "<solr></solr>"; Files.write(solrHome.resolve(SolrXmlConfig.SOLR_XML_FILE), xmlStr.getBytes(StandardCharsets.UTF_8)); h = new TestHarness(SolrXmlConfig.fromSolrHome(solrHome)); lrf = h.getRequestFactory("standard", 0, 20, CommonParams.VERSION, "2.2"); }
From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java
public void addDirectory(Path bucket, String directoryName) throws IOException { if (!directoryName.endsWith("/")) directoryName += "/"; Files.createFile(bucket.resolve(directoryName.replaceAll("/", "%2F"))); }
From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java
@Override public void run() { try {//w w w . j av a 2 s.c o m log.info("Watcher started."); initialize(); while (true) { checkInterrupted(); WatchKey watchKey = watcher.poll(CHECK_TIMEOUT, TimeUnit.MILLISECONDS); if (watchKey != null) { try { log.debug("Received watchKey: {} - {}", watchKey, watchKey.watchable()); Path parentPath = (Path) watchKey.watchable(); for (WatchEvent<?> event : watchKey.pollEvents()) { checkInterrupted(); log.debug("Received event: {} - {}", event.kind(), event.context()); if (event.kind() == StandardWatchEventKinds.OVERFLOW) { log.warn("Performing a full scan due loss of native FileSystem tracking data."); // Canceling the old watcher. IOUtils.closeQuietly(watcher); // Clean any pending unaccessible path. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); // Re-initialize the monitoring. initialize(); } else { Path eventPath = parentPath.resolve((Path) event.context()); if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { checkNewPath(eventPath); } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { if (!unaccessiblePaths.contains(eventPath)) { if (isPathFullyAccessible(eventPath)) { handlePathChanged(eventPath); } else { unaccessiblePaths.add(eventPath); modifyingPaths.add(eventPath); log.debug( "File unacessible upon modification. Starting monitoring for '{}'.", eventPath); } } } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { if (unaccessiblePaths.contains(eventPath)) { unaccessiblePaths.remove(eventPath); log.debug("Monitored file removed. Canceling monitoring for '{}'.", eventPath); if (modifyingPaths.contains(eventPath)) { modifyingPaths.remove(eventPath); handlePathRemoved(eventPath); } else { creatingPaths.remove(eventPath); } } else { handlePathRemoved(eventPath); } } } } } finally { watchKey.reset(); } } if (!unaccessiblePaths.isEmpty()) { checkAccessiblePaths(); } else if ((updateNotificationTimestamp != -1) && ((System.currentTimeMillis() - updateNotificationTimestamp) > CHECK_TIMEOUT)) { // Nothing happened since last update. Resetting the updateTimestamp and requesting a library update on // Serviio. updateNotificationTimestamp = -1; updateServiioReposotories(); } else if (updateNotificationTimestamp == -1) { // No pending path to checks and no pending updates to notify. Check external configuration changes. Object newFlagValue = getFieldValue(LibraryManager.getInstance(), "libraryAdditionsCheckerThread"); if ((configChangeFlag != null) && (newFlagValue != configChangeFlag)) { log.info("Detected configuration change. Restart monitoring."); configChangeFlag = newFlagValue; // Canceling the old watcher. IOUtils.closeQuietly(watcher); // Clean any pending unaccessible path. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); // Re-initialize the monitoring. initialize(); } } } } catch (InterruptedException e) { // This thread has been interrupted. Just exit. return; } finally { // Release any bounded resource. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); IOUtils.closeQuietly(watcher); log.info("Watcher stopped."); } }
From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java
public void addFile(Path bucket, String fileName) throws IOException { if (fileName.endsWith("/")) fileName.substring(0, fileName.length() - 1); Files.createFile(bucket.resolve(fileName.replaceAll("/", "%2F"))); }
From source file:com.nartex.RichFileManager.java
@Override public JSONObject getFolder(HttpServletRequest request) throws JSONException, IOException { JSONObject array = null;/*from w w w . jav a 2 s.c om*/ boolean showThumbs = false; String paramshowThumbs = request.getParameter("showThumbs"); if (paramshowThumbs != null) { showThumbs = true; } Path root = documentRoot.resolve(this.get.get("path")); log.debug("path absolute:" + root.toAbsolutePath()); Path docDir = documentRoot.resolve(this.get.get("path")).toRealPath(LinkOption.NOFOLLOW_LINKS); File dir = docDir.toFile(); //new File(documentRoot + this.get.get("path")); File file = null; if (!dir.isDirectory()) { this.error(sprintf(lang("DIRECTORY_NOT_EXIST"), this.get.get("path"))); } else { if (!dir.canRead()) { this.error(sprintf(lang("UNABLE_TO_OPEN_DIRECTORY"), this.get.get("path"))); } else { array = new JSONObject(); String[] files = dir.list(); JSONObject data = null; JSONObject props = null; for (int i = 0; i < files.length; i++) { data = new JSONObject(); props = new JSONObject(); file = docDir.resolve(files[i]).toFile(); //new File(documentRoot + this.get.get("path") + files[i]); if (file.isDirectory() && !contains(config.getProperty("unallowed_dirs"), files[i])) { try { props.put("Date Created", (String) null); props.put("Date Modified", (String) null); props.put("Height", (String) null); props.put("Width", (String) null); props.put("Size", (String) null); data.put("Path", this.get.get("path") + files[i] + "/"); data.put("Filename", files[i]); data.put("File Type", "dir"); data.put("Thumbnail", config.getProperty("icons-path") + config.getProperty("icons-directory")); data.put("Error", ""); data.put("Code", 0); data.put("Properties", props); array.put(this.get.get("path") + files[i] + "/", data); } catch (Exception e) { this.error("JSONObject error"); } } else if (file.canRead() && (!contains(config.getProperty("unallowed_files"), files[i]))) { this.item = new HashMap<String, Object>(); this.item.put("properties", this.properties); this.getFileInfo(this.get.get("path") + files[i], showThumbs); //if (this.params.get("type") == null || (this.params.get("type") != null && (!this.params.get("type").equals("Image") || checkImageType()))) { if (this.params.get("type") == null || (this.params.get("type") != null && ((!this.params.get("type").equals("Image") && !this.params.get("type").equals("Flash")) || checkImageType() || checkFlashType()))) { try { //data.put("Path", this.get.get("path") + files[i]); data.put("Path", this.item.get("path")); data.put("Filename", this.item.get("filename")); data.put("File Type", this.item.get("filetype")); data.put("Properties", this.item.get("properties")); data.put("Error", ""); data.put("Code", 0); log.debug("data now :" + data.toString()); array.put(this.get.get("path") + files[i], data); } catch (Exception e) { this.error("JSONObject error"); } } } else { log.warn("not allowed file or dir:" + files[i]); } } } } log.debug("array size ready:" + ((array != null) ? array.toString() : "")); return array; }