public static void log (String message, @NotNull LogFile logFile, boolean override) { try { Path pathToFile = Paths.get(pathToLogs.toString(), logFile.path()); if (!Files.exists(pathToLogs) || !Files.isDirectory(pathToLogs)) Files.createDirectory(pathToLogs); if (!Files.exists(pathToFile) || !Files.isRegularFile(pathToFile)) Files.createFile(pathToFile); String oldContent = override ? "" : cat(logFile); String newContent = (oldContent.isEmpty()) ? message : oldContent + "\n" + message; BufferedWriter out = new BufferedWriter(new FileWriter(pathToFile.toString())); out.write(newContent); out.close(); } catch (IOException e) { e.printStackTrace(); } }
@Test public void testPositionNegative() throws Exception { Path tempDir = Files.createTempDirectory("jaffree"); Path outputPath = tempDir.resolve(VIDEO_MP4.getFileName()); FFmpegResult result = FFmpeg.atPath(BIN) .addInput(UrlInput .fromPath(VIDEO_MP4) .setPositionEof(-7, TimeUnit.SECONDS) ) .addOutput(UrlOutput .toPath(outputPath) .copyAllCodecs()) .execute(); Assert.assertNotNull(result); double outputDuration = getDuration(outputPath); Assert.assertEquals(7.0, outputDuration, 0.5); }
private void scanDirectory(File directory, String prefix, Set<File> ancestors, Collection<Path> collector) throws IOException { File canonical = directory.getCanonicalFile(); if (ancestors.contains(canonical)) { // A cycle in the filesystem, for example due to a symbolic link. return; } File[] files = directory.listFiles(); if (files == null) { return; } HashSet<File> objects = new HashSet<>(); objects.addAll(ancestors); objects.add(canonical); Set<File> newAncestors = Collections.unmodifiableSet(objects); for (File f : files) { String name = f.getName(); if (f.isDirectory()) { scanDirectory(f, prefix + name + "/", newAncestors, collector); } else { collector.add(f.toPath()); } } }
Repository(IStore store, String repository_name, final Path base_path) throws RepositoryException { if (!repositoryNameIsLegal(repository_name)) { throw new RepositoryException("Illegal repository name <" + repository_name + ">"); } this.store = store; this.repository_name = repository_name; repository_path = base_path.resolve(repository_name); repository_directory = repository_path.toFile(); bucket_cache = new HashMap<>(); if (!repository_directory.exists()) { // only if the repo doesn't exist - try and make the directory if (!repository_directory.mkdir()) { throw new RepositoryException("Directory " + repository_directory.getAbsolutePath() + " does not exist and cannot be created"); } } else { // it does exist - check that it is a directory if (!repository_directory.isDirectory()) { throw new RepositoryException(repository_directory.getAbsolutePath() + " exists but is not a directory"); } } }
/** * Saves debug images of PDF pages from specified range and saves them in specified directory. * * @param document PDF document instance * @param startPage first page in range to process (first page == 1) * @param endPage last page in range * @param outputDir destination directory * @throws IOException */ public void savePdfTablePagesDebugImages(PDDocument document, int startPage, int endPage, Path outputDir) throws IOException { TableExtractor debugExtractor = new TableExtractor(settings); PDFRenderer renderer = new PDFRenderer(document); for (int page = startPage - 1; page < endPage; ++page) { PdfTableSettings debugSettings = PdfTableSettings.getBuilder() .setDebugImages(true) .setDebugFileOutputDir(outputDir) .setDebugFilename("page_" + (page + 1)) .build(); debugExtractor.setSettings(debugSettings); BufferedImage bi; synchronized (this) { bi = renderer.renderImageWithDPI(page, settings.getPdfRenderingDpi(), ImageType.RGB); } debugExtractor.getTableBoundingRectangles(bufferedImage2GrayscaleMat(bi)); } }
@BeforeClass public void setup() { theFileSystem = FileSystems.getFileSystem(URI.create("jrt:/")); Path modulesPath = Paths.get(System.getProperty("java.home"), "lib", "modules"); isExplodedBuild = Files.notExists(modulesPath); if (isExplodedBuild) { System.out.printf("%s doesn't exist.", modulesPath.toString()); System.out.println(); System.out.println("It is most probably an exploded build." + " Skip non-default FileSystem testing."); return; } Map<String, String> env = new HashMap<>(); // set java.home property to be underlying java.home // so that jrt-fs.jar loading is exercised. env.put("java.home", System.getProperty("java.home")); try { fs = FileSystems.newFileSystem(URI.create("jrt:/"), env); } catch (IOException ioExp) { throw new RuntimeException(ioExp); } }
public void testByteSource_size_ofSymlinkToDirectory() throws IOException { try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) { Path dir = fs.getPath("dir"); Files.createDirectory(dir); Path link = fs.getPath("link"); Files.createSymbolicLink(link, dir); ByteSource source = MoreFiles.asByteSource(link); assertThat(source.sizeIfKnown()).isAbsent(); try { source.size(); fail(); } catch (IOException expected) { } } }
@Test public void testJavaSE_Fail(Path base) throws Exception { Path src = base.resolve("src"); tb.writeJavaFiles(src, "module m { requires java.se; }", "import com.sun.source.tree.Tree;\n" // not in java.se (in jdk.compiler) + "class Test {\n" + " Tree t;\n" + "}"); Path classes = base.resolve("classes"); Files.createDirectories(classes); String log = new JavacTask(tb, Task.Mode.CMDLINE) .options("-XDrawDiagnostics") .files(findJavaFiles(src)) .outdir(classes) .run(Task.Expect.FAIL) .writeAll() .getOutput(Task.OutputKind.DIRECT); if (!log.contains("Test.java:1:22: compiler.err.package.not.visible: com.sun.source.tree, (compiler.misc.not.def.access.does.not.read: m, com.sun.source.tree, jdk.compiler)")) throw new Exception("expected output not found"); }
public void testReloadClasspath() { Function<String,String> prog = (s) -> String.format( "package pkg; public class A { public String toString() { return \"%s\"; } }\n", s); Compiler compiler = new Compiler(); Path outDir = Paths.get("testClasspathDirectory"); compiler.compile(outDir, prog.apply("A")); Path classpath = compiler.getPath(outDir); test( (a) -> assertCommand(a, "/env --class-path " + classpath, "| Setting new options and restoring state."), (a) -> assertMethod(a, "String foo() { return (new pkg.A()).toString(); }", "()String", "foo"), (a) -> assertVariable(a, "String", "v", "foo()", "\"A\""), (a) -> { if (!a) compiler.compile(outDir, prog.apply("Aprime")); assertCommand(a, "/reload", "| Restarting and restoring state.\n" + "-: String foo() { return (new pkg.A()).toString(); }\n" + "-: String v = foo();\n"); }, (a) -> assertCommand(a, "v", "v ==> \"Aprime\""), (a) -> evaluateExpression(a, "String", "foo()", "\"Aprime\""), (a) -> evaluateExpression(a, "pkg.A", "new pkg.A();", "Aprime") ); }
public static void main(String[] args) throws Exception { // create a zip file, and read it in as a byte array Path path = Files.createTempFile("bad", ".zip"); try (OutputStream os = Files.newOutputStream(path); ZipOutputStream zos = new ZipOutputStream(os)) { ZipEntry e = new ZipEntry("x"); zos.putNextEntry(e); zos.write((int) 'x'); } int len = (int) Files.size(path); byte[] data = new byte[len]; try (InputStream is = Files.newInputStream(path)) { is.read(data); } Files.delete(path); // year, month, day are zero testDate(data.clone(), 0, LocalDate.of(1979, 11, 30)); // only year is zero testDate(data.clone(), 0 << 25 | 4 << 21 | 5 << 16, LocalDate.of(1980, 4, 5)); }
@Test public void testModuleNotInModuleSrcPath(Path base) throws Exception { Path src = base.resolve("src"); Path m = src.resolve("m"); Files.createDirectories(m); Path extra = base.resolve("m"); tb.writeJavaFiles(extra, "module m {}"); Path classes = base.resolve("classes"); Files.createDirectories(classes); String log = new JavacTask(tb) .options("-XDrawDiagnostics", "--module-source-path", src.toString()) .outdir(classes) .files(findJavaFiles(extra)) .run(Task.Expect.FAIL) .writeAll() .getOutput(Task.OutputKind.DIRECT); if (!log.contains("module-info.java:1:1: compiler.err.module.not.found.on.module.source.path")) throw new Exception("expected output not found"); }
@Test public void testReportNoBranch() throws Exception { Path path = Paths.get("target", "coverage", "HtmlReportCoverageHandlerTest", "testReportNoBranch"); Files.deleteIfExists(path.resolve("covertest/HtmlReportCoverageHandlerTest/testReportNoBranch.html")); // カバレッジ用インスタンスをクリア Field field = AbstractAgent.class.getDeclaredField("coverageHandlerRef"); field.setAccessible(true); @SuppressWarnings("unchecked") AtomicReference<CoverageHandler> ref = (AtomicReference<CoverageHandler>) field.get(null); System.setProperty(SqlAgent.KEY_SQL_COVERAGE + ".dir", path.toString()); CoverageHandler before = ref.get(); ref.set(new HtmlReportCoverageHandler()); try (SqlAgent agent = config.agent()) { agent.query("covertest/HtmlReportCoverageHandlerTest/testReportNoBranch").collect(); } assertThat(Files.readAllLines(path.resolve("covertest/HtmlReportCoverageHandlerTest/testReportNoBranch.html")) .size(), is(61)); ref.set(before); System.clearProperty(SqlAgent.KEY_SQL_COVERAGE + ".dir"); }
public static OutputAnalyzer launchCompiler(String libName, String item, List<String> extraopts, List<String> compList) { Path file = null; if (compList != null && !compList.isEmpty()) { file = Paths.get(METHODS_LIST_FILENAME); try { Files.write(file, compList, StandardOpenOption.CREATE); } catch (IOException e) { throw new Error("Couldn't write " + METHODS_LIST_FILENAME + " " + e, e); } } List<String> args = new ArrayList<>(); args.add("--compile-with-assertions"); args.add("--output"); args.add(libName); if (file != null) { args.add("--compile-commands"); args.add(file.toString()); } args.add("--class-name"); args.add(item); String linker = resolveLinker(); if (linker != null) { args.add("--linker-path"); args.add(linker); } // Execute with asserts args.add("-J-ea"); args.add("-J-esa"); return launchJaotc(args, extraopts); }
@Override public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException { triggerEx(dir, "createDirectory"); Files.createDirectory(unwrap(dir), attrs); }
@Test public void testSingleModuleOptionWithNoModuleOnSourcePath(Path base) throws Exception { Path src = base.resolve("src"); Path mod1 = Paths.get(src.toString(), "m1"); execNegativeTask("--source-path", mod1.toString(), "--module", "m1"); assertMessagePresent("module m1 not found on source path"); }
static JmodFile newJmodFile(Path path) { try { return new JmodFile(path); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } }
private boolean checkValidPathEntry(Path p, String context, boolean isModulePath) { if (!Files.exists(p)) { msg("jshell.err.file.not.found", context, p); failed = true; return false; } if (Files.isDirectory(p)) { // if module-path, either an exploded module or a directory of modules return true; } String name = p.getFileName().toString(); int lastDot = name.lastIndexOf("."); if (lastDot > 0) { switch (name.substring(lastDot)) { case ".jar": return true; case ".jmod": if (isModulePath) { return true; } } } msg("jshell.err.arg", context, p); failed = true; return false; }
public static void main(String[] args) { if (args.length != 3) { System.err.println("Please provide a host, port and file name!"); System.exit(0); } String host = args[0]; int port = Integer.parseInt(args[1]); String relativeFileName = args[2]; Path path = Paths.get(relativeFileName); String fileName = path.getFileName().toString(); logger.info(String.format("host: %s, port: %d, file: %s", host, port, path.getFileName().toString())); MarcElasticsearchClient client = new MarcElasticsearchClient(host, port); JsonPathCache<? extends XmlFieldInstance> cache; List<String> records; try { records = Files.readAllLines(path, Charset.defaultCharset()); MarcFieldExtractor extractor = new MarcFieldExtractor(new MarcJsonSchema()); Map<String, Object> duplumKey; int i = 0; for (String record : records) { i++; cache = new JsonPathCache(record); extractor.measure(cache); duplumKey = extractor.getDuplumKeyMap(); client.indexDuplumKey((String)duplumKey.get("recordId"), duplumKey); if (i % 100 == 0) { logger.info(String.format("%s/%d) %s", fileName, i, duplumKey.get("recordId"))); } } logger.info("end of cycle"); } catch (IOException ex) { logger.severe(ex.toString()); System.exit(0); } logger.info("Bye!"); System.exit(0); }
/** * Checks if a BUILD file exists at a given path. If it does not, then it generates the BUILD and * any necessary intermediary directories. */ @VisibleForTesting static void generateBuildFileIfNecessary(Path buildFileDirectory) throws InterruptedException, IOException { checkState(Files.isDirectory(buildFileDirectory) || !Files.exists(buildFileDirectory)); if (Files.exists(buildFileDirectory.resolve("BUILD"))) { return; } if (!Files.exists(buildFileDirectory)) { Files.createDirectories(buildFileDirectory); } Files.createFile(buildFileDirectory.resolve("BUILD")); }
public static void main(String... args) throws Exception { Map<String, Path> artifacts = ArtifactResolver.resolve(Scimark.class); OutputAnalyzer output = new OutputAnalyzer(ProcessTools.createJavaProcessBuilder( "-cp", artifacts.get("gov.nist.math.scimark-2.0").toString(), "jnt.scimark2.commandline", "-large") .start()); output.shouldHaveExitValue(0); }
public GAV createGAV(Path pathToPom){ Element rootXmlElement = xmlElementFactory.createRootXmlElement(pathToPom); String groupId = getDirectChildsByTag(rootXmlElement, "groupId"); String artifactId = getDirectChildsByTag(rootXmlElement, "artifactId"); String version = getDirectChildsByTag(rootXmlElement, "version"); return new GAV(groupId, artifactId, version); }
/** * Get the absolute path to the file in the current asset. * * @param assetFile the file. * @return the absolute path to the file. */ @FromAnyThread public static @Nullable Path getRealFile(@NotNull final Path assetFile) { final EditorConfig editorConfig = EditorConfig.getInstance(); final Path currentAsset = editorConfig.getCurrentAsset(); if (currentAsset == null) return null; return currentAsset.resolve(assetFile); }
public CustomTreeItem(Path f, WatcherStructure watcherStructure, Project project, TabUpdater tabUpdater, TreeUpdater treeUpdater) { super(f); if (watcherStructure != null) { watcherStructure.start(); } this.project = project; this.tabUpdater = tabUpdater; this.treeUpdater = treeUpdater; }
@Override @BackgroundThread public void doSave(@NotNull final Path toStore) throws IOException { super.doSave(toStore); final M currentModel = getCurrentModel(); NodeUtils.visitGeometry(currentModel, geometry -> saveIfNeedTextures(geometry.getMaterial())); final BinaryExporter exporter = BinaryExporter.getInstance(); try (final OutputStream out = Files.newOutputStream(toStore)) { exporter.save(currentModel, out); } }
/** * Attempts to move source to target atomically and falls back to a non-atomic move if it fails. * * @throws IOException if both atomic and non-atomic moves fail */ public static void atomicMoveWithFallback(Path source, Path target) throws IOException { try { Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); } catch (IOException outer) { try { Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); log.debug("Non-atomic move of {} to {} succeeded after atomic move failed due to {}", source, target, outer.getMessage()); } catch (IOException inner) { inner.addSuppressed(outer); throw inner; } } }
@Test public void testMainDir() throws IOException, InterruptedException { Path out = temp.newFolder("outdex").toPath(); ProcessResult r8 = ToolHelper.forkR8(Paths.get("."), "--lib", ToolHelper.getDefaultAndroidJar(), "--output", out.toString(), "--pg-conf", PROGUARD_FLAGS.toString(), "--pg-conf", testFlags.toString(), INPUT_JAR.toString()); Assert.assertEquals(0, r8.exitCode); Assert.assertTrue(Files.isRegularFile(out.resolve(FileUtils.DEFAULT_DEX_FILENAME))); Assert.assertTrue(Files.isRegularFile(testFlags.getParent().resolve(MAPPING))); Assert.assertTrue(Files.isRegularFile(testFlags.getParent().resolve(SEEDS))); }
/** * Creates a simple {@link AppConfig} object */ public static Path createAppConfig(Path configurations, Path connectors) throws IOException { Path configFile = Files.createTempFile("test-config", ".json"); AppConfig.Global global = ImmutableAppConfig.Global.builder() .configurationsPath(configurations.toAbsolutePath().toString()) .connectorsPath(connectors.toAbsolutePath().toString()) .runOnce(true) .updateConfigurationIntervalMillis(100000L) .build(); AppConfig config = ImmutableAppConfig.builder().global(global).build(); mapper.writeValue(configFile.toFile(), config); return configFile; }
@FXThread private void fillChildren(@NotNull final Path prevFile, @NotNull final Path newFile, @NotNull final Array<TreeItem<ResourceElement>> children) { for (final TreeItem<ResourceElement> child : children) { final ResourceElement resourceElement = child.getValue(); final Path file = resourceElement.getFile(); final Path relativeFile = file.subpath(prevFile.getNameCount(), file.getNameCount()); final Path resultFile = newFile.resolve(relativeFile); child.setValue(createFor(resultFile)); } }
protected void writeFile(Path path, JsonElement json) throws IOException { try(BufferedWriter writer = Files.newBufferedWriter(path)) { JsonUtils.prettyGson.toJson(json, writer); } }
public static List<Path> listFiles(Path directory) throws IOException { final List<Path> files = new LinkedList<Path>(); if (Files.notExists(directory)) { return files; } Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) { files.add(path); return FileVisitResult.CONTINUE; } }); return files; }
private void generate(BufferedReader reader) throws IOException { // array is needed to change value inside a lambda long[] count = {0L}; String root = Utils.TEST_SRC; Path testFile = Paths.get(root) .resolve(group.groupName) .resolve("Test.java"); File testDir = testFile.getParent().toFile(); if (!testDir.mkdirs() && !testDir.exists()) { throw new Error("Can not create directories for " + testFile.toString()); } try (PrintStream ps = new PrintStream(testFile.toFile())) { ps.print(COPYRIGHT); ps.printf("/* DO NOT MODIFY THIS FILE. GENERATED BY %s */\n", getClass().getName()); reader.lines() .filter(group.filter) .forEach(s -> { count[0]++; ps.printf(DESC_FORMAT, s); }); ps.print('\n'); } System.out.printf("%d tests generated in %s%n", count[0], group.groupName); }
public void copyFileIn(String containerId, Path input, String pathInContainer) throws InterruptedException, DockerException, IOException { client.copyToContainer(input, containerId, pathInContainer); StringBuilder builder = new StringBuilder(); LOGGER.info(builder.append("copy file ").append(input.toString()).append(" into container ") .append(containerId).append(":").append(pathInContainer).append(" successful").toString()); }
private void writeData(LXP record_to_write, Path filepath) throws BucketException { try (Writer writer = Files.newBufferedWriter(filepath, FileManipulation.FILE_CHARSET)) { // auto close and exception record_to_write.serializeToJSON(new JSONWriter(writer), this); object_cache.put(record_to_write.getId(), record_to_write); // Putting this call here ensures that all records that are in a bucket and loaded are in the cache } catch (IOException | JSONException e) { throw new BucketException(e); } }
FileEntry(Path path, String name) { super(DirArchive.this, getPathName(path), name, Archive.Entry.EntryType.CLASS_OR_RESOURCE); this.path = path; try { size = Files.size(path); } catch (IOException ex) { throw new RuntimeException(ex); } }
static String makeClassName(Path path) { String fileName = path.toString(); if (!fileName.endsWith(".class")) { throw new IllegalArgumentException("File doesn't end with .class: '" + fileName + "'"); } fileName = stripRoot(path); String className = fileName.substring(0, fileName.length() - ".class".length()); className = className.replace(path.getFileSystem().getSeparator(), "."); return className; }
private void notifyPathsChanged(final Set<Path> changedPaths) { log.debug("Paths changed: {}", changedPaths); try { listener.onPathsChanged(rootDirectory, changedPaths); } catch (RuntimeException e) { if (log.isDebugEnabled()) { log.warn("Exception by listener '{}' while processing paths {}", listener, changedPaths, e); } else { log.warn("Exception by listener '{}' while processing paths {} : {}", listener, changedPaths, e.toString()); } } }
/** * Put a file represented as a path into an open ZipOutputStream. * @param zos ZipOutputStream to write to. * @param path Path representing a file to be written to the zip. */ private static void putEntry(ZipOutputStream zos, Path path, String target) throws IOException { // Make a new zipentry with the files at the top-level directory (instead of nested). final ZipEntry zipEntry = new ZipEntry(Paths.get(target).relativize(path).toString()); zos.putNextEntry(zipEntry); Files.copy(path, zos); zos.closeEntry(); }
/** * Returns a task that updates the registration of a directory with * a WatchService. */ static Callable<Boolean> newRegisterTask(WatchService watcher, Path dir) { return () -> { try { dir.register(watcher, StandardWatchEventKinds.ENTRY_DELETE); return true; } catch (ClosedWatchServiceException e) { return false; } catch (IOException ioe) { throw new UncheckedIOException(ioe); } }; }
@Test public void testSimpleCopy() throws Exception { Path tempDir = Files.createTempDirectory("jaffree"); Path outputPath = tempDir.resolve(VIDEO_MP4.getFileName()); FFmpegResult result = FFmpeg.atPath(BIN) .addInput(UrlInput.fromPath(VIDEO_MP4)) .addOutput(UrlOutput .toPath(outputPath) .copyAllCodecs()) .execute(); Assert.assertNotNull(result); }