List of usage examples for java.nio.file Path resolve
default Path resolve(String other)
From source file:com.liferay.blade.cli.command.InstallExtensionCommandTest.java
@Test public void testInstallCustomExtensionTwiceDontOverwrite() throws Exception { String jarName = _sampleCommandJarFile.getName(); File extensionJar = new File(_extensionsDir, jarName); String[] args = { "extension", "install", _sampleCommandJarFile.getAbsolutePath() }; Path extensionPath = extensionJar.toPath(); BladeTestResults bladeTestResults = TestUtil.runBlade(_rootDir, _extensionsDir, args); String output = bladeTestResults.getOutput(); _testJarsDiff(_sampleCommandJarFile, extensionJar); Assert.assertTrue("Expected output to contain \"successful\"\n" + output, output.contains(" successful")); Assert.assertTrue(output.contains(jarName)); File tempDir = temporaryFolder.newFolder("overwrite"); Path tempPath = tempDir.toPath(); Path sampleCommandPath = tempPath.resolve(_sampleCommandJarFile.getName()); Files.copy(_sampleCommandJarFile.toPath(), sampleCommandPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); File sampleCommandFile = sampleCommandPath.toFile(); sampleCommandFile.setLastModified(0); args = new String[] { "extension", "install", sampleCommandFile.getAbsolutePath() }; output = _testBladeWithInteractive(_rootDir, _extensionsDir, args, "n"); Assert.assertTrue("Expected output to contain \"already exists\"\n" + output, output.contains(" already exists")); Assert.assertFalse("Expected output to not contain \"installed successfully\"\n" + output, output.contains(" installed successfully")); Assert.assertTrue(sampleCommandFile.lastModified() == 0); File extensionFile = extensionPath.toFile(); Assert.assertFalse(extensionFile.lastModified() == 0); output = _testBladeWithInteractive(_rootDir, _extensionsDir, args, "defaultShouldBeNo"); Assert.assertFalse(extensionFile.lastModified() == 0); Assert.assertTrue("Expected output to contain \"already exists\"\n" + output, output.contains(" already exists")); Assert.assertFalse("Expected output to not contain \"Overwriting\"\n" + output, output.contains("Overwriting")); Assert.assertFalse("Expected output to not contain \"installed successfully\"\n" + output, output.contains(" installed successfully")); }
From source file:deepschema.ExtractingTool.java
/** * Opens output file./*from w w w .j a v a 2 s . c o m*/ * * @param filename * @return FileOutputStream */ FileOutputStream openOutput(String filename) throws IOException { Path directoryPath = Paths.get("results"); try { Files.createDirectory(directoryPath); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(directoryPath)) { throw e; } } Path filePath = directoryPath.resolve(filename); return new FileOutputStream(filePath.toFile()); }
From source file:io.fabric8.docker.client.impl.BuildImage.java
@Override public OutputHandle fromFolder(String path) { try {/*from w ww . ja va2s . c o m*/ final Path root = Paths.get(path); final Path dockerIgnore = root.resolve(DOCKER_IGNORE); final List<String> ignorePatterns = new ArrayList<>(); if (dockerIgnore.toFile().exists()) { for (String p : Files.readAllLines(dockerIgnore, UTF_8)) { ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p); } } final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns); File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile(); try (FileOutputStream fout = new FileOutputStream(tempFile); BufferedOutputStream bout = new BufferedOutputStream(fout); BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout); final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) { Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dockerIgnorePathMatcher.matches(dir)) { return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (dockerIgnorePathMatcher.matches(file)) { return FileVisitResult.SKIP_SUBTREE; } final Path relativePath = root.relativize(file); final TarArchiveEntry entry = new TarArchiveEntry(file.toFile()); entry.setName(relativePath.toString()); entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE); entry.setSize(attrs.size()); tout.putArchiveEntry(entry); Files.copy(file, tout); tout.closeArchiveEntry(); return FileVisitResult.CONTINUE; } }); fout.flush(); } return fromTar(tempFile.getAbsolutePath()); } catch (IOException e) { throw DockerClientException.launderThrowable(e); } }
From source file:cn.edu.zjnu.acm.judge.core.Judger.java
private boolean runProcess(RunRecord runRecord) throws IOException { Path dataPath = runRecord.getDataPath(); Objects.requireNonNull(dataPath, "dataPath"); Path specialFile = dataPath.resolve(JudgeConfiguration.VALIDATE_FILE_NAME); boolean isspecial = Files.exists(specialFile); if (!Files.isDirectory(dataPath)) { log.error("{} not exists", runRecord.getDataPath()); return false; }//from ww w.j a v a2 s . c o m List<Path[]> files = new ArrayList<>(20); try (DirectoryStream<Path> listFiles = Files.newDirectoryStream(dataPath)) { log.debug("dataPath = {}", dataPath); for (Path inFile : listFiles) { String inFileName = inFile.getFileName().toString(); if (!inFileName.toLowerCase().endsWith(".in")) { continue; } Path outFile = dataPath.resolve(inFileName.substring(0, inFileName.length() - 3) + ".out"); if (!Files.exists(outFile)) { continue; } files.add(new Path[] { inFile, outFile });//, } } int casenum = files.size(); log.debug("casenum = {}", casenum); if (casenum == 0) { return false; } int accept = 0; //? ArrayList<String> details = new ArrayList<>(casenum << 2); long time = 0; // long memory = 0; // String command = runRecord.getLanguage().getExecuteCommand(); Path work = judgeConfiguration.getWorkDirectory(runRecord.getSubmissionId()); // command = !StringUtils.isEmptyOrWhitespace(command) ? command : work.resolve("Main." + runRecord.getLanguage().getExecutableExtension()).toString(); long extTime = runRecord.getLanguage().getExtTime(); long castTimeLimit = runRecord.getTimeLimit() * runRecord.getLanguage().getTimeFactor() + extTime; long extraMemory = runRecord.getLanguage().getExtMemory(); // long caseMemoryLimit = (runRecord.getMemoryLimit() + extraMemory) * 1024; Options[] optionses = new Options[casenum]; for (int cas = 0; cas < casenum; cas++) { Path[] entry = files.get(cas); Path in = entry[0]; Path standard = entry[1]; Path progOutput = work.resolve(standard.getFileName()); optionses[cas] = Options.builder().timeLimit(castTimeLimit) // time limit .memoryLimit(caseMemoryLimit) // memory in bytes .outputLimit(16 * 1024 * 1024) // 16M .command(command).workDirectory(work).inputFile(in).outputFile(progOutput) .standardOutput(standard).errFile(getNull(work)).build(); } String detailMessageStr = null; String scorePerCase = new DecimalFormat("0.#").format(100.0 / casenum); final Validator validator = isspecial ? new SpecialValidator(specialFile.toString(), work) : new SimpleValidator(); try { ExecuteResult[] ers = JudgeBridge.INSTANCE.judge(optionses, false, validator); for (ExecuteResult er : ers) { long tim1 = er.getTime() - extTime; tim1 = Math.max(0, tim1); long mem1 = er.getMemory() / 1024 - extraMemory; mem1 = Math.max(0, mem1); String message = er.getMessage(); int caseResult = getResultFromExecuteResult(er); time = Math.max(time, tim1); memory = Math.max(memory, mem1); log.debug("message = {}, time = {}, memory = {}", message, time, memory); details.add(String.valueOf(caseResult)); if (caseResult == 0) { details.add(scorePerCase); } else { details.add("0"); } details.add(String.valueOf(tim1)); details.add(String.valueOf(mem1)); if (caseResult == 0) { ++accept; } } } catch (JudgeException | RuntimeException | Error ex) { log.error("", ex); accept = ResultType.SYSTEM_ERROR; detailMessageStr = ex.getMessage(); } log.debug("{}", details); int score = accept >= 0 ? (int) Math.round(accept * 100.0 / casenum) : accept; if (score == 0 && accept != 0) { ++score; } else if (score == 100 && accept != casenum) { --score; } submissionMapper.updateResult(runRecord.getSubmissionId(), score, time, memory); submissionMapper.saveDetail(runRecord.getSubmissionId(), detailMessageStr != null ? detailMessageStr : details.stream().map(String::valueOf).collect(Collectors.joining(","))); updateSubmissionStatus(runRecord); return score == 100; }
From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java
private static Path pack(final Path folder, JsonObject graph, String tkName) throws IOException, URISyntaxException { String namespace = splAppNamespace(graph); String name = splAppName(graph); Path zipFilePath = Paths.get(folder.toAbsolutePath().toString() + ".zip"); String workingDir = zipFilePath.getParent().toString(); Path topologyToolkit = TkInfo.getTopologyToolkitRoot().getAbsoluteFile().toPath(); // Paths to copy into the toolkit Map<Path, String> paths = new HashMap<>(); // tkManifest is the list of toolkits contained in the archive try (PrintWriter tkManifest = new PrintWriter("manifest_tk.txt", "UTF-8")) { tkManifest.println(tkName);/*from w w w. ja va 2s . c o m*/ tkManifest.println("com.ibm.streamsx.topology"); JsonObject configSpl = object(graph, CONFIG, "spl"); if (configSpl != null) { objectArray(configSpl, "toolkits", tk -> { File tkRoot = new File(jstring(tk, "root")); String tkRootName = tkRoot.getName(); tkManifest.println(tkRootName); paths.put(tkRoot.toPath(), tkRootName); }); } } // mainComposite is a string of the namespace and the main composite. // This is used by the Makefile try (PrintWriter mainComposite = new PrintWriter("main_composite.txt", "UTF-8")) { mainComposite.print(namespace + "::" + name); } Path manifest = Paths.get(workingDir, "manifest_tk.txt"); Path mainComp = Paths.get(workingDir, "main_composite.txt"); Path makefile = topologyToolkit .resolve(Paths.get("opt", "python", "templates", "common", "Makefile.template")); paths.put(topologyToolkit, topologyToolkit.getFileName().toString()); paths.put(manifest, "manifest_tk.txt"); paths.put(mainComp, "main_composite.txt"); paths.put(makefile, "Makefile"); paths.put(folder, folder.getFileName().toString()); addAllToZippedArchive(paths, zipFilePath); manifest.toFile().delete(); mainComp.toFile().delete(); return zipFilePath; }
From source file:cool.pandora.modeller.ui.handlers.iiif.PatchResourceHandler.java
@Override public void execute() { final String message = ApplicationContextUtil.getMessage("bag.message.resourcepatched"); final DefaultBag bag = bagView.getBag(); final List<String> payload = bag.getPayloadPaths(); final Map<String, BagInfoField> map = bag.getInfo().getFieldMap(); final URI resourceContainer = IIIFObjectURI.getResourceContainerURI(map); final String basePath = AbstractBagConstants.DATA_DIRECTORY; final Path rootDir = bagView.getBagRootPath().toPath(); for (final String filePath : payload) { final String filename = BaggerFileEntity.removeBasePath(basePath, filePath); final String destinationURI = getDestinationURI(resourceContainer, filename); final Path absoluteFilePath = rootDir.resolve(filePath); final File resourceFile = absoluteFilePath.toFile(); String formatName = null; Dimension dim = null;/*from w ww . j a v a 2s. c o m*/ InputStream rdfBody = null; final URI uri = URI.create(destinationURI); try { formatName = ImageIOUtil.getImageMIMEType(resourceFile); } catch (final Exception e) { e.printStackTrace(); } try { dim = ImageIOUtil.getImageDimensions(resourceFile); } catch (final Exception e) { e.printStackTrace(); } if (dim != null) { final double imgWidth = dim.getWidth(); final int iw = (int) imgWidth; final double imgHeight = dim.getHeight(); final int ih = (int) imgHeight; try { rdfBody = getResourceMetadata(map, filename, formatName, iw, ih); } catch (final Exception e) { e.printStackTrace(); } } try { ModellerClient.doPatch(uri, rdfBody); ApplicationContextUtil.addConsoleMessage(message + " " + destinationURI); } catch (final ModellerClientFailedException e) { ApplicationContextUtil.addConsoleMessage(getMessage(e)); } } bagView.getControl().invalidate(); }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries) throws IOException { // Create a jar with a manifest we'd expect to see merged. Path originalJar = folder.newFile("unexpected.jar"); JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar); ignored.close();//from w w w . j a va 2 s . com // Now create the actual manifest Path manifestFile = folder.newFile("actual_manfiest.mf"); try (OutputStream os = Files.newOutputStream(manifestFile)) { fromUser.write(os); } Path tmp = folder.newFolder(); Path output = tmp.resolve("example.jar"); JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output, ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries, /* blacklist */ ImmutableSet.of()); ExecutionContext context = TestExecutionContext.newInstance(); step.execute(context); // Now verify that the created manifest matches the expected one. try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) { return jis.getManifest(); } }
From source file:com.commander4j.util.JUtility.java
public static String diskFree() { String result = ""; long free = 0; File f = new File(System.getProperty("user.dir")); String root = ""; while (f.getParent() != null) { root = f.getParent();//w ww .java 2s . c om f = new File(root); } try { URI rootURI = new URI("file:///"); Path rootPath = Paths.get(rootURI); Path dirPath = rootPath.resolve(root); FileStore dirFileStore = Files.getFileStore(dirPath); free = dirFileStore.getUsableSpace() / 1048576; result = String.valueOf(free) + " mb on " + root; } catch (Exception e) { result = "Error trying to determine free disk space " + e.getLocalizedMessage(); } return result; }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
@Test public void shouldNotIncludeFilesInBlacklist() throws IOException { Path zipup = folder.newFolder(); Path first = createZip(zipup.resolve("first.zip"), "dir/file1.txt", "dir/file2.txt", "com/example/Main.class"); JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"), ImmutableSortedSet.of(first.getFileName()), "com.example.Main", /* manifest file */ null, /* merge manifests */ true, /* blacklist */ ImmutableSet.of(Pattern.compile(".*2.*"))); assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode()); Path zip = zipup.resolve("output.jar"); // 3 files in total: file1.txt, & com/example/Main.class & the manifest. assertZipFileCountIs(3, zip);//from w w w . j a va2 s . c om assertZipContains(zip, "dir/file1.txt"); assertZipDoesNotContain(zip, "dir/file2.txt"); }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
@Test public void shouldNotIncludeFilesInClassesToRemoveFromJar() throws IOException { Path zipup = folder.newFolder(); Path first = createZip(zipup.resolve("first.zip"), "com/example/A.class", "com/example/B.class", "com/example/C.class"); JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"), ImmutableSortedSet.of(first.getFileName()), "com.example.A", /* manifest file */ null, /* merge manifests */ true, /* blacklist */ ImmutableSet.of(Pattern.compile("com.example.B"), Pattern.compile("com.example.C"))); assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode()); Path zip = zipup.resolve("output.jar"); // 2 files in total: com/example/A/class & the manifest. assertZipFileCountIs(2, zip);/*from w w w . ja v a2s . c o m*/ assertZipContains(zip, "com/example/A.class"); assertZipDoesNotContain(zip, "com/example/B.class"); assertZipDoesNotContain(zip, "com/example/C.class"); }