List of usage examples for java.nio.file Path toAbsolutePath
Path toAbsolutePath();
From source file:org.finra.dm.dao.Log4jOverridableConfigurerTest.java
@Test @Ignore // This works locally, but fails in Jenkins for some reason. We'll need to investigate at some point. public void testLog4JFileWithRefreshInterval() throws Exception { Path configPath = getRandomLog4jConfigPath(); Path outputPath = getRandomLog4jOutputPath(); try {//from w w w . ja v a 2 s.c om // Write the standard JUnit Log4J configuration that won't create an output file. writeFileFromResourceLocation(DaoEnvTestSpringModuleConfig.TEST_LOG4J_CONFIG_RESOURCE_LOCATION, configPath, outputPath); // Initialize Log4J with a refresh interval of 1/2 second. This will cause Log4J to check for configuration updates every second. Log4jOverridableConfigurer log4jConfigurer = new Log4jOverridableConfigurer(); log4jConfigurer.setApplicationContext(applicationContext); log4jConfigurer .setDefaultResourceLocation(DaoEnvTestSpringModuleConfig.TEST_LOG4J_CONFIG_RESOURCE_LOCATION); log4jConfigurer.setOverrideResourceLocation(configPath.toAbsolutePath().toUri().toURL().toString()); log4jConfigurer.setRefreshIntervalMillis(500); log4jConfigurer.postProcessBeforeInitialization(null, null); // First ensure that the Log4J output file doesn't exist. assertTrue("Log4J output file exists, but shouldn't.", Files.notExists(outputPath)); // Replace the Log4J configuration file with the one that will create an output file. writeFileFromResourceLocation(LOG4J_CONFIG_FILENAME, configPath, outputPath); // Sleep one second which will give Log4J a chance to read the new configuration file which should create an output file. Thread.sleep(1000); // Ensure that the Log4J output file now exists. assertTrue("Log4J output file doesn't exist, but should.", Files.exists(outputPath)); } finally { cleanup(configPath, outputPath); } }
From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java
/** * Invokes the compiler on a given file and reports the output. * * @param pathToSourceFolder//from w w w . j a v a 2 s . c o m * Specifies the folder where source files are located. * @param outputFolder * Directory where the resulting binaries are placed * @param compilerName * The compiler to be used (usually javac). * @param compilerFlags * Additional flags to be passed to the compiler. * @throws FileNotFoundException * Is thrown when the file in pathToProgramFile cannot be * opened * @throws BadCompilerSpecifiedException * Is thrown when the given compiler cannot be called * @return A {@link CompilerOutput} that contains all compiler messages and * flags on how the compile run went. * @throws BadFlagException * When javac doesn't recognize a flag, this exception is * thrown. * @throws CompilerOutputFolderExistsException * The output folder may not exist. This is thrown when it does * exist. */ @Override public CompilerOutput checkProgram(Path pathToSourceFolder, Path outputFolder, String compilerName, List<String> compilerFlags) throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException, CompilerOutputFolderExistsException { // First we build the command to invoke the compiler. This consists of // the compiler executable, the path of the // file to compile and compiler flags. List<String> compilerInvocation = createCompilerInvocation(pathToSourceFolder, outputFolder, compilerName, compilerFlags); // Now we build a launchable process from the given parameters and set // the working directory. CompilerOutput result = runJavacProcess(compilerInvocation, pathToSourceFolder, false); compilerInvocation.clear(); compilerInvocation.add("javac"); compilerInvocation.add("-cp"); // Add testDependencies to classpath String cp = ".:" + m_junitLocation + ":" + outputFolder.toAbsolutePath(); // Add all additional .jar files contained in javalib directory to the classpath if (!m_libLocation.toFile().exists()) { m_libLocation.toFile().mkdir(); } else { for (File f : FileUtils.listFiles(m_libLocation.toFile(), new String[] { "jar" }, false)) { cp = cp + ":" + f.getAbsolutePath(); } } compilerInvocation.add(cp); //make sure java uses utf8 for encoding compilerInvocation.add("-encoding"); compilerInvocation.add("UTF-8"); compilerInvocation.add("-d"); compilerInvocation.add(m_junitTestFilesLocation.toAbsolutePath().toString()); List<Path> foundUnitTests = exploreDirectory(m_junitTestFilesLocation); for (Path path : foundUnitTests) { compilerInvocation.add(path.toAbsolutePath().toString()); } runJavacProcess(compilerInvocation, m_junitTestFilesLocation, true); return result; }
From source file:org.finra.herd.dao.Log4jOverridableConfigurerTest.java
@Test @Ignore // This works locally, but fails in Jenkins for some reason. We'll need to investigate at some point. public void testLog4JFileWithRefreshInterval() throws Exception { Path configPath = getRandomLog4jConfigPath(); Path outputPath = getRandomLog4jOutputPath(); try {/*from w ww.j a v a2 s . com*/ // Write the standard JUnit Log4J configuration that won't create an output file. writeFileFromResourceLocation(DaoEnvTestSpringModuleConfig.TEST_LOG4J_CONFIG_RESOURCE_LOCATION, configPath, outputPath, 1); // Initialize Log4J with a refresh interval of 1/2 second. This will cause Log4J to check for configuration updates every second. Log4jOverridableConfigurer log4jConfigurer = new Log4jOverridableConfigurer(); log4jConfigurer.setApplicationContext(applicationContext); log4jConfigurer .setDefaultResourceLocation(DaoEnvTestSpringModuleConfig.TEST_LOG4J_CONFIG_RESOURCE_LOCATION); log4jConfigurer.setOverrideResourceLocation(configPath.toAbsolutePath().toUri().toURL().toString()); log4jConfigurer.postProcessBeforeInitialization(null, null); // First ensure that the Log4J output file doesn't exist. assertTrue("Log4J output file exists, but shouldn't.", Files.notExists(outputPath)); // Replace the Log4J configuration file with the one that will create an output file. writeFileFromResourceLocation(LOG4J_CONFIG_FILENAME, configPath, outputPath, 1); // Sleep one second which will give Log4J a chance to read the new configuration file which should create an output file. Thread.sleep(3000); // Ensure that the Log4J output file now exists. assertTrue("Log4J output file doesn't exist, but should.", Files.exists(outputPath)); } finally { cleanup(configPath, outputPath); } }
From source file:net.sf.jabref.gui.FindUnlinkedFilesDialog.java
/** * Opens a {@link JFileChooser} and receives the user input as a * {@link File} object, which this method returns. <br> * <br>/*from w w w.ja v a 2 s. c o m*/ * The "Open file" dialog will start at the path that is set in the * "directory" textfield, or at the last stored path for this dialog, if the * textfield is empty. <br> * <br> * If the user cancels the "Open file" dialog, this method returns null. <br> * <br> * If the user has selected a valid directory in the "Open file" dialog, * this path will be stored persistently for this dialog, so that it can be * preset at the next time this dialog is opened. * * @return The selected directory from the user, or <code>null</code>, if * the user has aborted the selection. */ private Path chooseDirectory() { if (fileChooser == null) { fileChooser = new JFileChooser(); fileChooser.setAutoscrolls(true); fileChooser.setDialogTitle(Localization.lang("Select directory")); fileChooser.setApproveButtonText(Localization.lang("Choose directory")); fileChooser.setApproveButtonToolTipText( Localization.lang("Use the selected directory to start with the search.")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } String path = textfieldDirectoryPath.getText(); if (path.isEmpty()) { fileChooser.setCurrentDirectory(lastSelectedDirectory.toFile()); } else { fileChooser.setCurrentDirectory(Paths.get(path).toFile()); } int result = fileChooser.showOpenDialog(frame); if (result == JFileChooser.CANCEL_OPTION) { return null; } Path selectedDirectory = fileChooser.getSelectedFile().toPath(); String filepath = ""; if (selectedDirectory != null) { filepath = selectedDirectory.toAbsolutePath().toString(); } textfieldDirectoryPath.setText(filepath); return selectedDirectory; }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java
/** * bootstrap the repository//from w ww. ja va 2 s . co m */ public void bootstrap() throws Exception { Path globalConfigFolder = Paths.get(rootPath, "global-configuration"); boolean bootstrapCheck = Files.exists(globalConfigFolder); if (bootstrapEnabled && !bootstrapCheck) { try { logger.error("Bootstrapping repository for Crafter CMS"); Files.createDirectories(globalConfigFolder); } catch (Exception alreadyExistsErr) { // do nothing. } try { Path globalConfigRepoPath = Paths.get(globalConfigFolder.toAbsolutePath().toString(), ".git"); Repository repository = FileRepositoryBuilder.create(globalConfigRepoPath.toFile()); repository.create(); } catch (IOException e) { logger.error("Error while creating global configuration repository", e); } String bootstrapFolderPath = this.ctx.getRealPath(File.separator + "gitrepo-bootstrap"); Path source = java.nio.file.FileSystems.getDefault().getPath(bootstrapFolderPath); logger.info("Bootstrapping with baseline @ " + source.toFile().toString()); Path target = Paths.get(rootPath); TreeCopier tc = new TreeCopier(source, target); EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(source, opts, Integer.MAX_VALUE, tc); try { Repository globalConfigRepo = getGlobalConfigurationRepositoryInstance(); Git git = new Git(globalConfigRepo); Status status = git.status().call(); if (status.hasUncommittedChanges() || !status.isClean()) { DirCache dirCache = git.add().addFilepattern(".").call(); RevCommit commit = git.commit().setMessage("initial content").call(); String tmp = commit.getId().toString(); } } catch (IOException | GitAPIException err) { logger.error("error creating initial commit for global configuration", err); } } }
From source file:com.github.podd.resources.test.DataReferenceAttachResourceImplTest.java
/** * Given the path to a resource containing an incomplete File Reference object, this method * constructs a complete File Reference and returns it as an RDF/XML string. * * @param fragmentSource// w w w . jav a2 s.c o m * Location of resource containing incomplete File Reference * @return String containing RDF statements */ private String buildFileReferenceString(final String fragmentSource, final RDFFormat format, final Path testDirectory) throws Exception { // read the fragment's RDF statements into a Model final InputStream inputStream = this.getClass().getResourceAsStream(fragmentSource); final Model model = Rio.parse(inputStream, "", format); // path to be set as part of the file reference final Path completePath = testDirectory.resolve(TestConstants.TEST_REMOTE_FILE_NAME); Files.copy( this.getClass().getResourceAsStream( TestConstants.TEST_REMOTE_FILE_PATH + "/" + TestConstants.TEST_REMOTE_FILE_NAME), completePath, StandardCopyOption.REPLACE_EXISTING); final Resource aliasUri = model.filter(null, PODD.PODD_BASE_HAS_ALIAS, null).subjects().iterator().next(); model.add(aliasUri, PODD.PODD_BASE_HAS_FILE_PATH, ValueFactoryImpl.getInstance().createLiteral(testDirectory.toAbsolutePath().toString())); model.add(aliasUri, PODD.PODD_BASE_HAS_FILENAME, ValueFactoryImpl.getInstance().createLiteral(TestConstants.TEST_REMOTE_FILE_NAME)); // get a String representation of the statements in the Model final StringWriter out = new StringWriter(); Rio.write(model, out, format); return out.toString(); }
From source file:org.dia.kafka.isatools.producer.DirWatcher.java
/** * Process all events for keys queued to the watcher * @param isatProd/* w w w .ja v a 2s. c om*/ */ void processEvents(ISAToolsKafkaProducer isatProd) { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } List<JSONObject> jsonParsedResults = new ArrayList<JSONObject>(); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // If an inner file has been modify then, recreate the entry if (kind == ENTRY_MODIFY || kind == ENTRY_CREATE) { File fileCheck = child.getParent().toFile(); if (child.toFile().isDirectory()) { fileCheck = child.toFile(); } System.out.format("[%s] %s : %s\n", this.getClass().getSimpleName(), kind.toString(), fileCheck.getAbsolutePath()); List<String> folderFiles = ISAToolsKafkaProducer.getFolderFiles(fileCheck); List<JSONObject> jsonObjects = ISAToolsKafkaProducer.doTikaRequest(folderFiles); if (!jsonObjects.isEmpty()) { // jsonParsedResults.addAll(jsonObjects); isatProd.sendISAToolsUpdates(jsonObjects); } } // TODO this event has still to be specified for documents if (kind == ENTRY_DELETE) { System.err.println(String.format("Delete event not supported %s", child.toAbsolutePath())); } // if directory is created, and watching recursively, then // register it and its sub-directories if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(child, NOFOLLOW_LINKS)) { registerAll(child); } } catch (IOException x) { // ignore to keep sample readbale System.err.format("IOException when creating %s \n", child.toAbsolutePath()); } } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } }
From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java
/** * Runs tests in testLocation on the source code given in the parameter. * * @param submissionBinariesLocation/*from w ww . j a v a 2 s .co m*/ * The path to the compiled binaries of the submission. * * @return the {@link TestOutput} containing the test results. * * @throws ClassNotFoundException * Throws if the loaded Classes are not found * @throws IOException * Throws if the sourceCodeLocation is malformed or the * {@link URLClassLoader} can't be closed. */ @Override public TestOutput testSubmission(Path submissionBinariesLocation) throws ClassNotFoundException, IOException { // if there are no tests create and empty TestOutput with didTest false if ((testLocation == null) || testLocation.toString().isEmpty()) { return new TestOutput(null, false); } else { List<Result> results = new LinkedList<>(); // create the classloader URL submissionURL = submissionBinariesLocation.toUri().toURL(); URL testsURL = testLocation.toUri().toURL(); // URLClassLoader loader = // new URLClassLoader(new URL[] { submissionURL, testsURL }); URLClassLoader loader = new URLClassLoader(new URL[] { testsURL, submissionURL }); // iterate submission source code files and load the .class files. /* * We need to iterate all files in a directory and thus are using * the apache commons io utility FileUtils.listFiles. This needs a) * the directory, and b) a file filter for which we also use the * one supplied by apache commons io. */ Path submissionBin = submissionBinariesLocation.toAbsolutePath(); List<Path> exploreDirectory = exploreDirectory(submissionBin, ExplorationType.CLASSFILES); for (Path path : exploreDirectory) { String quallifiedName = getQuallifiedName(submissionBin, path); loader.loadClass(quallifiedName); } // iterate tests, load them and run them Path testLoc = testLocation.toAbsolutePath(); List<Path> exploreDirectory2 = exploreDirectory(testLoc, ExplorationType.SOURCEFILES); for (Path path : exploreDirectory2) { String unitTestName = getQuallifiedNameFromSource(path); try { Class<?> testerClass = loader.loadClass(unitTestName); Result runClasses = JUnitCore.runClasses(testerClass); results.add(runClasses); } catch (Throwable e) { LOGGER.severe("can't load class: " + unitTestName); LOGGER.severe(e.getMessage()); } } loader.close(); // creates new TestOutput from results and returns it return new TestOutput(results, true); } }
From source file:com.spectralogic.ds3client.integration.Smoke_Test.java
@Test public void partialGetWithBookOverChunkBoundry() throws IOException, XmlProcessingException, URISyntaxException { final String bucketName = "partialGetOnBook"; final Path filePath = Files.createTempFile("ds3", "lesmis-copies.txt"); LOG.info("TempFile for partial get of book: " + filePath.toAbsolutePath().toString()); try {// www .j a va2 s .c o m HELPERS.ensureBucketExists(bucketName, envDataPolicyId); final List<Ds3Object> putObjects = Lists.newArrayList(new Ds3Object("lesmis-copies.txt", 13290604)); final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, putObjects, WriteJobOptions .create().withMaxUploadSize(PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES)); putJob.transfer(new ResourceObjectPutter("largeFiles/")); final List<Ds3Object> getObjects = Lists.newArrayList(); getObjects.add(new PartialDs3Object("lesmis-copies.txt", Range.byLength(1048476, 200))); final Ds3ClientHelpers.Job getJob = HELPERS.startReadJob(bucketName, getObjects); getJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { return Files.newByteChannel(filePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE); } }); final Path expectedResultPath = Paths.get(Smoke_Test.class.getResource("/largeFiles/output").toURI()); assertThat(Files.size(filePath), is(200L)); final String partialFile = new String(Files.readAllBytes(filePath), Charset.forName("UTF-8")); final String expectedResult = new String(Files.readAllBytes(expectedResultPath), Charset.forName("UTF-8")); assertThat(partialFile, is(expectedResult.substring(0, expectedResult.length() - 1))); // need the trim to remove a newline that is added by the os } finally { deleteAllContents(client, bucketName); Files.delete(filePath); } }
From source file:org.opencb.cellbase.app.cli.DownloadCommandExecutor.java
private void runGeneExtraInfo(Species sp, String assembly, Path geneFolder) throws IOException, InterruptedException { logger.info("Downloading gene extra info ..."); String geneExtraInfoLogFile = geneFolder.resolve("gene_extra_info.log").toString(); List<String> args = new ArrayList<>(); if (sp.getScientificName().equals("Homo sapiens") && assembly.equalsIgnoreCase("GRCh37")) { args.addAll(Arrays.asList("--species", sp.getScientificName(), "--outdir", geneFolder.toAbsolutePath().toString(), "--ensembl-libs", configuration.getDownload().getEnsembl().getLibs().replace("79", "75"))); } else {//ww w . ja v a2 s.co m args.addAll(Arrays.asList("--species", sp.getScientificName(), "--outdir", geneFolder.toAbsolutePath().toString(), "--ensembl-libs", configuration.getDownload().getEnsembl().getLibs())); } if (!configuration.getSpecies().getVertebrates().contains(species) && !species.getScientificName().equals("Drosophila melanogaster")) { args.add("--phylo"); args.add("no-vertebrate"); } // run gene_extra_info.pl boolean geneExtraInfoDownloaded = runCommandLineProcess(ensemblScriptsFolder, "./gene_extra_info.pl", args, geneExtraInfoLogFile); // check output if (geneExtraInfoDownloaded) { logger.info("Gene extra files created OK"); } else { logger.error("Gene extra info for " + sp.getScientificName() + " cannot be downloaded"); } }