List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:com.liferay.sync.engine.util.FileUtilTest.java
@Test public void testRenameFile() throws Exception { Path sourceFilePath = Files.createTempFile("test", null); Path parentFilePath = sourceFilePath.getParent(); String sourceFilePathFileName = String.valueOf(sourceFilePath.getFileName()); Path targetFilePath = parentFilePath.resolve(sourceFilePathFileName.toUpperCase()); FileUtil.moveFile(sourceFilePath, targetFilePath); Path realFilePath = targetFilePath.toRealPath(); Path realFilePathFileName = realFilePath.getFileName(); Assert.assertFalse(sourceFilePath.endsWith(realFilePathFileName)); Assert.assertTrue(targetFilePath.endsWith(realFilePathFileName)); }
From source file:org.opentestsystem.ap.ivs.service.ValidationUtilityTest.java
@Test public void itShouldParseValidationErrorReport() { final String errorReportFileName = testHelper.getIvsProperties().getErrorReportFileName(); final URL errorFileUrl = Thread.currentThread().getContextClassLoader().getResource(errorReportFileName); final Path errorFilePath = Paths.get(errorFileUrl.getPath()); final List<ErrorReport> errorReportList = utility.parseErrorReport(errorFilePath.getParent()); assertThat(errorReportList).hasSize(23); final List<ValidationResult> validationResults = service.generateResults(errorFilePath.getParent()); assertThat(validationResults).hasSize(21); }
From source file:io.undertow.server.handlers.file.FileHandlerTestCase.java
@Test public void testHeadRequest() throws IOException, URISyntaxException { TestHttpClient client = new TestHttpClient(); Path file = Paths.get(getClass().getResource("page.html").toURI()); Path rootPath = file.getParent(); try {/* w w w . ja v a2 s . co m*/ DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path", new ResourceHandler(new PathResourceManager(rootPath, 10485760)) .setDirectoryListingEnabled(true)))); HttpHead get = new HttpHead(DefaultServer.getDefaultServerURL() + "/path/page.html"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(Long.toString(Files.size(file)), result.getHeaders(Headers.CONTENT_LENGTH_STRING)[0].getValue()); Header[] headers = result.getHeaders("Content-Type"); Assert.assertEquals("text/html", headers[0].getValue()); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.google.devtools.build.android.PackedResourceTarExpander.java
private void unTarPackedResources(final Path tarOut, final Path packedResources) throws IOException { LOGGER.fine(String.format("Found packed resources: %s", packedResources)); try (InputStream inputStream = Files.newInputStream(packedResources); TarArchiveInputStream tarStream = new TarArchiveInputStream(inputStream)) { byte[] temp = new byte[4 * 1024]; for (TarArchiveEntry entry = tarStream.getNextTarEntry(); entry != null; entry = tarStream .getNextTarEntry()) {/* w w w . j av a2 s. c o m*/ if (!entry.isFile()) { continue; } int read = tarStream.read(temp); // packed tars can start with a ./. This can cause issues, so remove it. final Path entryPath = tarOut.resolve(entry.getName().replace("^\\./", "")); Files.createDirectories(entryPath.getParent()); final OutputStream entryOutStream = Files.newOutputStream(entryPath); while (read > -1) { entryOutStream.write(temp, 0, read); read = tarStream.read(temp); } entryOutStream.flush(); entryOutStream.close(); } } }
From source file:org.openhab.tools.analysis.checkstyle.PackageExportsNameCheck.java
/** * Filter and return the packages from the source directory. Only not excluded packages will be returned. * * @param sourcePath - The full path of the source directory * @return {@link Set } of {@link String }s with the package names. * @throws IOException if an I/O error is thrown while visiting files *///from w w w. ja v a2s .co m private Set<String> getFilteredPackagesFromSourceDirectory(Path sourcePath) throws IOException { Set<String> packages = new HashSet<>(); // No symbolic links are expected in the source directory if (Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) { Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) { Path packageRelativePath = sourcePath.relativize(path.getParent()); String packageName = packageRelativePath.toString() .replaceAll(Matcher.quoteReplacement(File.separator), "."); if (!isExcluded(packageName)) { packages.add(packageName); } return FileVisitResult.CONTINUE; } }); } return packages; }
From source file:com.netease.hearttouch.hthotfix.HashFileGenerator.java
public void generate() throws IOException { if (hashMap.isEmpty()) { return;/*from w ww. ja va 2 s . c o m*/ } try { Path relativePath = Paths.get(outputPath); if (relativePath.toFile().exists()) relativePath.toFile().delete(); if (!relativePath.getParent().toFile().exists()) { Files.createDirectories(relativePath.getParent()); } Files.createFile(relativePath); FileOutputStream outputStream = null; outputStream = new FileOutputStream(relativePath.toFile()); sink = Okio.buffer(Okio.sink(outputStream)); Set<Map.Entry<String, String>> set = hashMap.entrySet(); Iterator<Map.Entry<String, String>> iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); String className = entry.getKey(); String sha1Hex = entry.getValue(); sink.writeUtf8(String.format("%s,%s", className, sha1Hex)); sink.writeByte(newLine); } } catch (IOException e) { e.printStackTrace(); logger.error("HashFileGenerator generate error:\t" + e.getMessage()); throw e; } finally { if (sink != null) { sink.close(); sink = null; } } }
From source file:com.tascape.qa.th.AbstractTestRunner.java
protected void generateHtml(Path logFile) { Pattern http = Pattern.compile("((http|https)://\\S+)"); Path html = logFile.getParent().resolve("log.html"); LOG.trace("creating file {}", html); try (PrintWriter pw = new PrintWriter(html.toFile())) { pw.println("<html><body><pre>"); pw.println("<a href='../'>Suite Log Directory</a><br /><a href='./'>Test Log Directory</a>"); pw.println();/* w ww . j a va2 s . c o m*/ pw.println(logFile); pw.println(); List<String> lines = FileUtils.readLines(logFile.toFile()); List<File> files = new ArrayList<>(Arrays.asList(logFile.getParent().toFile().listFiles())); for (String line : lines) { String newline = line.replaceAll(">", ">"); newline = newline.replaceAll("<", "<"); if (newline.contains(" WARN ")) { newline = "<b>" + newline + "</b> "; } else if (newline.contains(" ERROR ") || newline.contains("Failure in test") || newline.contains("AssertionError")) { newline = "<font color='red'><b>" + newline + "</b></font> "; } else { Matcher m = http.matcher(line); if (m.find()) { String url = m.group(1); String a = String.format("<a href='%s'>%s</a>", url, url); newline = newline.replace(url, a); } } pw.println(newline); for (File file : files) { String path = file.getAbsolutePath(); String name = file.getName(); if (newline.contains(path)) { if (name.endsWith(".png")) { pw.printf("<a href=\"%s\" target=\"_blank\"><img src=\"%s\" width=\"360px\"/></a>", name, name); } String a = String.format("<a href=\"%s\" target=\"_blank\">%s</a>", name, name); int len = newline.indexOf(" "); pw.printf((len > 0 ? newline.substring(0, len + 5) : "") + a); pw.println(); files.remove(file); break; } } } pw.println("</pre></body></html>"); logFile.toFile().delete(); } catch (IOException ex) { LOG.warn(ex.getMessage()); } }
From source file:org.roda_project.commons_ip.model.impl.eark.EARKUtils.java
protected static IPInterface processRepresentations(MetsWrapper metsWrapper, IPInterface ip, Logger logger) throws IPException { if (metsWrapper.getRepresentationsDiv() != null && metsWrapper.getRepresentationsDiv().getDiv() != null) { for (DivType representationDiv : metsWrapper.getRepresentationsDiv().getDiv()) { if (representationDiv.getMptr() != null && !representationDiv.getMptr().isEmpty()) { // we can assume one and only one mets for each representation div Mptr mptr = representationDiv.getMptr().get(0); String href = Utils.extractedRelativePathFromHref(mptr.getHref()); Path metsFilePath = ip.getBasePath().resolve(href); IPRepresentation representation = new IPRepresentation(representationDiv.getLABEL()); MetsWrapper representationMetsWrapper = processRepresentationMets(ip, metsFilePath, representation); if (representationMetsWrapper.getMets() != null) { Path representationBasePath = metsFilePath.getParent(); StructMapType representationStructMap = getEARKStructMap(representationMetsWrapper, ip, false);/*from w w w .j av a 2s .co m*/ if (representationStructMap != null) { preProcessStructMap(representationMetsWrapper, representationStructMap); representation.setStatus( new RepresentationStatus(representationMetsWrapper.getMainDiv().getTYPE())); ip.addRepresentation(representation); // process representation agents processRepresentationAgents(representationMetsWrapper, representation); // process files processRepresentationFiles(ip, representationMetsWrapper, representation, representationBasePath); // process descriptive metadata processDescriptiveMetadata(representationMetsWrapper, ip, logger, representation, representationBasePath); // process preservation metadata processPreservationMetadata(representationMetsWrapper, ip, logger, representation, representationBasePath); // process other metadata processOtherMetadata(representationMetsWrapper, ip, logger, representation, representationBasePath); // process schemas processSchemasMetadata(representationMetsWrapper, ip, representationBasePath); // process documentation processDocumentationMetadata(representationMetsWrapper, ip, representationBasePath); } } } } // post-process validations if (ip.getRepresentations().isEmpty()) { ValidationUtils.addIssue(ip.getValidationReport(), ValidationConstants.MAIN_METS_NO_REPRESENTATIONS_FOUND, ValidationEntry.LEVEL.WARN, metsWrapper.getRepresentationsDiv(), ip.getBasePath(), metsWrapper.getMetsPath()); } } return ip; }
From source file:org.cryptomator.cryptofs.CryptoFileSystemProviderIntegrationTest.java
@Test public void testCopyFileFromOneCryptoFileSystemToAnother() throws IOException { byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; Path fs1Location = tmpPath.resolve("foo"); Path fs2Location = tmpPath.resolve("bar"); Files.createDirectories(fs1Location); Files.createDirectories(fs2Location); FileSystem fs1 = CryptoFileSystemProvider.newFileSystem(fs1Location, cryptoFileSystemProperties().withPassphrase("asd").build()); FileSystem fs2 = CryptoFileSystemProvider.newFileSystem(fs2Location, cryptoFileSystemProperties().withPassphrase("qwe").build()); Path file1 = fs1.getPath("/foo/bar"); Path file2 = fs2.getPath("/bar/baz"); Files.createDirectories(file1.getParent()); Files.createDirectories(file2.getParent()); Files.write(file1, data);/* ww w. java 2 s . c o m*/ Files.copy(file1, file2); assertThat(readAllBytes(file1), is(data)); assertThat(readAllBytes(file2), is(data)); }
From source file:org.cryptomator.cryptofs.CryptoFileSystemProviderIntegrationTest.java
@Test public void testMoveFileFromOneCryptoFileSystemToAnother() throws IOException { byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; Path fs1Location = tmpPath.resolve("foo"); Path fs2Location = tmpPath.resolve("bar"); Files.createDirectories(fs1Location); Files.createDirectories(fs2Location); FileSystem fs1 = CryptoFileSystemProvider.newFileSystem(fs1Location, cryptoFileSystemProperties().withPassphrase("asd").build()); FileSystem fs2 = CryptoFileSystemProvider.newFileSystem(fs2Location, cryptoFileSystemProperties().withPassphrase("qwe").build()); Path file1 = fs1.getPath("/foo/bar"); Path file2 = fs2.getPath("/bar/baz"); Files.createDirectories(file1.getParent()); Files.createDirectories(file2.getParent()); Files.write(file1, data);//from ww w .j av a 2 s .c o m Files.move(file1, file2); assertThat(Files.exists(file1), is(false)); assertThat(readAllBytes(file2), is(data)); }