List of usage examples for java.nio.file Files deleteIfExists
public static boolean deleteIfExists(Path path) throws IOException
From source file:com.github.robozonky.installer.RoboZonkyInstallerListener.java
private static void primeKeyStore(final char... keystorePassword) throws SetupFailedException, IOException { final String username = Variables.ZONKY_USERNAME.getValue(DATA); final char[] password = Variables.ZONKY_PASSWORD.getValue(DATA).toCharArray(); Files.deleteIfExists(KEYSTORE_FILE.toPath()); // re-install into the same directory otherwise fails final Feature f = new ZonkyPasswordFeature(KEYSTORE_FILE, keystorePassword, username, password); f.setup();/*from w ww .j a va 2 s . com*/ }
From source file:org.evosuite.junit.JUnitAnalyzerTest.java
@Test public void testSandboxIssue() throws Exception { //First, get a TestCase from a carved JUnit Properties.SELECTED_JUNIT = com.examples.with.different.packagename.sandbox.OpenStreamInATryCatch_FakeTestToCarve.class .getCanonicalName();//from w w w. ja v a 2s .c om Properties.TARGET_CLASS = com.examples.with.different.packagename.sandbox.OpenStreamInATryCatch.class .getCanonicalName(); Properties.CRITERION = new Properties.Criterion[] { Properties.Criterion.BRANCH }; Properties.SEED_MUTATIONS = 0; Properties.SEED_CLONE = 1; Properties.VIRTUAL_FS = false; Properties.SANDBOX = true; Properties.ENABLE_ASSERTS_FOR_EVOSUITE = true; //needed for setLoggingForJUnit Properties.TEST_SCAFFOLDING = false; //FIXME Sandbox.initializeSecurityManagerForSUT(); //file should never be created Assert.assertFalse(file.exists()); JUnitTestCarvedChromosomeFactory factory = new JUnitTestCarvedChromosomeFactory(null); TestChromosome carved = factory.getChromosome(); /* * FIXME: issue with carver */ Files.deleteIfExists(file.toPath()); Assert.assertFalse(file.exists()); Assert.assertNotNull(carved); TestCase test = carved.getTestCase(); Assert.assertEquals("Should be: constructor, 1 variable and 1 method", 3, test.size()); //Now that we have a test case, we check its execution after //recompiling it to JUnit, and see if sandbox kicks in List<TestCase> list = new ArrayList<TestCase>(); list.add(test); Assert.assertFalse(file.exists()); //NOTE: following order of checks reflects what is done // in EvoSuite after the search is finished System.out.println("\n COMPILATION CHECK \n"); //first try to compile (which implies execution) JUnitAnalyzer.removeTestsThatDoNotCompile(list); Assert.assertEquals(1, list.size()); Assert.assertFalse(file.exists()); System.out.println("\n FIRST STABILITY CHECK \n"); //try once JUnitAnalyzer.handleTestsThatAreUnstable(list); Assert.assertEquals(1, list.size()); Assert.assertFalse(file.exists()); System.out.println("\n SECOND STABILITY CHECK \n"); //try again JUnitAnalyzer.handleTestsThatAreUnstable(list); Assert.assertEquals(1, list.size()); Assert.assertFalse(file.exists()); System.out.println("\n FINAL VERIFICATION \n"); JUnitAnalyzer.verifyCompilationAndExecution(list); Assert.assertEquals(1, list.size()); Assert.assertFalse(file.exists()); }
From source file:org.jboss.as.test.manualmode.deployment.DeploymentScannerNotificationUnitTestCase.java
@Test public void testStartup() throws Exception { container.start();//from w ww.j a va2s. c o m try { client = TestSuiteEnvironment.getModelControllerClient(); try { final File deploymentOne = new File(deployDir, "deployment-one.jar"); createDeployment(deploymentOne, "org.jboss.modules"); // Add a new de addDeploymentScanner(1000, false); try { // Wait until deployed ... long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (!exists(DEPLOYMENT_ONE) && System.currentTimeMillis() < timeout) { Thread.sleep(100); } Assert.assertTrue(exists(DEPLOYMENT_ONE)); Assert.assertEquals("OK", deploymentState(DEPLOYMENT_ONE)); final Path oneDeployed = deployDir.toPath().resolve("deployment-one.jar.deployed"); final Path oneUndeployed = deployDir.toPath().resolve("deployment-one.jar.undeployed"); Assert.assertTrue(Files.deleteIfExists(oneDeployed)); timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (!Files.exists(oneUndeployed) && System.currentTimeMillis() < timeout) { Thread.sleep(10); } Assert.assertFalse(Files.exists(oneDeployed)); Assert.assertTrue(Files.exists(oneUndeployed)); Assert.assertTrue(Files.exists(deployDir.toPath().resolve("deployment-one.jar"))); Assert.assertFalse(exists(DEPLOYMENT_ONE)); ModelNode disableScanner = Util.getWriteAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=deployment-scanner/scanner=testScanner"), "scan-interval", 300000); ModelNode result = executeOperation(disableScanner); assertEquals("Unexpected outcome of disabling the test deployment scanner: " + disableScanner, ModelDescriptionConstants.SUCCESS, result.get(OUTCOME).asString()); deploy(deploymentOne); Assert.assertTrue(exists(DEPLOYMENT_ONE)); Assert.assertEquals("OK", deploymentState(DEPLOYMENT_ONE)); timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (!Files.exists(oneDeployed) && System.currentTimeMillis() < timeout) { Thread.sleep(10); } Assert.assertTrue(Files.exists(oneDeployed)); Assert.assertFalse(Files.exists(oneUndeployed)); } finally { removeDeploymentScanner(); undeploy("deployment-one.jar"); } } finally { StreamUtils.safeClose(client); } } finally { container.stop(); } }
From source file:org.esa.s2tbx.dataio.gdal.GDALInstaller.java
private void installDistribution(Path gdalFolderPath, OSCategory osCategory, String mapLibraryName) throws IOException { // the library file does not exist on the local disk among the folders from path environment String zipArchivePath = osCategory.getDirectory() + "/" + osCategory.getZipFileName(); Path zipFilePathOnLocalDisk = gdalFolderPath.resolve(zipArchivePath); Path gdalDistributionRootFolderPath = zipFilePathOnLocalDisk.getParent(); fixUpPermissions(gdalFolderPath);//from w ww .j av a2 s .c o m if (!Files.exists(gdalDistributionRootFolderPath)) { Files.createDirectories(gdalDistributionRootFolderPath); try { String zipFilePathFromSources = SRC_PATH + "/" + zipArchivePath; URL zipFileURLFromSources = getClass().getClassLoader().getResource(zipFilePathFromSources); FileHelper.copyFile(zipFileURLFromSources, zipFilePathOnLocalDisk); FileHelper.unzip(zipFilePathOnLocalDisk, gdalDistributionRootFolderPath, true); } finally { try { Files.deleteIfExists(zipFilePathOnLocalDisk); } catch (IOException e) { logger.log(Level.SEVERE, "GDAL configuration error: failed to delete zip after decompression.", e); } } } Path gdalBinFolderPath = gdalDistributionRootFolderPath.resolve(BIN_PATH); processInstalledDistribution(gdalFolderPath, gdalBinFolderPath, osCategory, mapLibraryName); }
From source file:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java
@Override public void execute() throws MojoExecutionException { Path warExecFile = Paths.get(this.buildDirectory, this.finalName); try {// www.j a v a 2 s . c om Files.deleteIfExists(warExecFile); Files.createDirectories(warExecFile.getParent()); try (OutputStream os = Files.newOutputStream(warExecFile); ArchiveOutputStream aos = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) { // If project is a war project add the war to the project if ("war".equalsIgnoreCase(this.project.getPackaging())) { File projectArtifact = this.project.getArtifact().getFile(); if (projectArtifact != null && Files.exists(projectArtifact.toPath())) { aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName())); try (InputStream is = Files.newInputStream(projectArtifact.toPath())) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } // Add extraWars into the jar if (this.extraWars != null) { for (Dependency extraWarDependency : this.extraWars) { ArtifactRequest request = new ArtifactRequest(); request.setArtifact(new DefaultArtifact(extraWarDependency.getGroupId(), extraWarDependency.getArtifactId(), extraWarDependency.getType(), extraWarDependency.getVersion())); request.setRepositories(this.projectRepos); ArtifactResult result; try { result = this.repoSystem.resolveArtifact(this.repoSession, request); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } File extraWarFile = result.getArtifact().getFile(); aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName())); try (InputStream is = Files.newInputStream(extraWarFile.toPath())) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } // Add extraResources into the jar. Folder /extra if (this.extraResources != null) { for (Resource extraResource : this.extraResources) { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(extraResource.getDirectory()); directoryScanner.setExcludes(extraResource.getExcludes() .toArray(new String[extraResource.getExcludes().size()])); if (!extraResource.getIncludes().isEmpty()) { directoryScanner.setIncludes(extraResource.getIncludes() .toArray(new String[extraResource.getIncludes().size()])); } else { // include everything by default directoryScanner.setIncludes(new String[] { "**" }); } directoryScanner.scan(); for (String includeFile : directoryScanner.getIncludedFiles()) { aos.putArchiveEntry( new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile)); Path extraFile = Paths.get(extraResource.getDirectory(), includeFile); try (InputStream is = Files.newInputStream(extraFile)) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } } Set<String> includeArtifacts = new HashSet<>(); includeArtifacts.add("org.apache.tomcat:tomcat-jdbc"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-websocket"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli"); includeArtifacts.add("org.yaml:snakeyaml"); includeArtifacts.add("com.beust:jcommander"); if (this.includeJSPSupport) { includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-el"); includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj"); } for (Artifact pluginArtifact : this.pluginArtifacts) { String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId(); if (includeArtifacts.contains(artifactName)) { try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) { extractJarToArchive(jarFile, aos); } } } if (this.extraDependencies != null) { for (Dependency dependency : this.extraDependencies) { ArtifactRequest request = new ArtifactRequest(); request.setArtifact(new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), dependency.getVersion())); request.setRepositories(this.projectRepos); ArtifactResult result; try { result = this.repoSystem.resolveArtifact(this.repoSession, request); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) { extractJarToArchive(jarFile, aos); } } } if (this.includeJSPSupport) { addFile(aos, "/conf/web.xml", "conf/web.xml"); } else { addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml"); } addFile(aos, "/conf/logging.properties", "conf/logging.properties"); if (this.includeTcNativeWin32 != null) { aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32")); Files.copy(Paths.get(this.includeTcNativeWin32), aos); aos.closeArchiveEntry(); } if (this.includeTcNativeWin64 != null) { aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64")); Files.copy(Paths.get(this.includeTcNativeWin64), aos); aos.closeArchiveEntry(); } String[] runnerClasses = { "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions", "ch.rasc.embeddedtc.runner.CheckConfig", "ch.rasc.embeddedtc.runner.Config", "ch.rasc.embeddedtc.runner.Shutdown", "ch.rasc.embeddedtc.runner.Context", "ch.rasc.embeddedtc.runner.DeleteDirectory", "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions", "ch.rasc.embeddedtc.runner.ObfuscateUtil", "ch.rasc.embeddedtc.runner.Runner$1", "ch.rasc.embeddedtc.runner.Runner$2", "ch.rasc.embeddedtc.runner.Runner$StartOptions", "ch.rasc.embeddedtc.runner.Runner$StopOptions", "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook", "ch.rasc.embeddedtc.runner.Runner" }; for (String rc : runnerClasses) { String classAsPath = rc.replace('.', '/') + ".class"; try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) { aos.putArchiveEntry(new JarArchiveEntry(classAsPath)); IOUtils.copy(is, aos); aos.closeArchiveEntry(); } } Manifest manifest = new Manifest(); Manifest.Attribute mainClassAtt = new Manifest.Attribute(); mainClassAtt.setName("Main-Class"); mainClassAtt.setValue(Runner.class.getName()); manifest.addConfiguredAttribute(mainClassAtt); aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF")); manifest.write(aos); aos.closeArchiveEntry(); aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME)); aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8)); aos.closeArchiveEntry(); } } catch (IOException | ArchiveException | ManifestException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:com.qwazr.library.poi.PptxParser.java
@Override public void parseContent(final MultivaluedMap<String, String> parameters, final InputStream inputStream, String extension, final String mimeType, final ParserResultBuilder resultBuilder) throws Exception { if (StringUtils.isEmpty(extension)) extension = ".pptx"; final Path tempFile = ParserAbstract.createTempFile(inputStream, extension); try {//from w ww . j a v a 2 s. com parseContent(parameters, tempFile, extension, mimeType, resultBuilder); } finally { Files.deleteIfExists(tempFile); } }
From source file:org.digidoc4j.ContainerTest.java
@AfterClass public static void deleteTemporaryFiles() { try {/* w w w. j ava 2 s. c o m*/ DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(".")); for (Path item : directoryStream) { String fileName = item.getFileName().toString(); if ((fileName.endsWith("bdoc") || fileName.endsWith("ddoc")) && fileName.startsWith("test")) Files.deleteIfExists(item); } } catch (IOException e) { e.printStackTrace(); } }
From source file:org.schedulesdirect.grabber.LogoTask.java
protected void removeStaleLogo() throws IOException { Path p = vfs.getPath("logos", String.format("%s.%s", callsign, ext)); if (Files.deleteIfExists(p)) { synchronized (cache) { cache.remove(callsign);/*from w w w . j a v a2 s.c om*/ } } }
From source file:edu.pitt.dbmi.ccd.queue.service.AlgorithmQueueService.java
@Async public Future<Void> runAlgorithmFromQueue(JobQueueInfo jobQueueInfo) { Long queueId = jobQueueInfo.getId(); String fileName = jobQueueInfo.getFileName() + ".txt"; String jsonFileName = jobQueueInfo.getFileName() + ".json"; String commands = jobQueueInfo.getCommands(); String tmpDirectory = jobQueueInfo.getTmpDirectory(); String outputDirectory = jobQueueInfo.getOutputDirectory(); List<String> cmdList = new LinkedList<>(); cmdList.addAll(Arrays.asList(commands.split(";"))); cmdList.add("--out"); cmdList.add(tmpDirectory);/*from w ww .ja v a 2 s . c o m*/ StringBuilder sb = new StringBuilder(); cmdList.forEach(cmd -> { sb.append(cmd); sb.append(" "); }); LOGGER.info("Algorithm command: " + sb.toString()); String errorFileName = String.format("error_%s", fileName); Path error = Paths.get(tmpDirectory, errorFileName); Path errorDest = Paths.get(outputDirectory, errorFileName); Path src = Paths.get(tmpDirectory, fileName); Path dest = Paths.get(outputDirectory, fileName); Path json = Paths.get(tmpDirectory, jsonFileName); Path jsonDest = Paths.get(outputDirectory, jsonFileName); try { ProcessBuilder pb = new ProcessBuilder(cmdList); pb.redirectError(error.toFile()); Process process = pb.start(); //Get process Id Long pid = Processes.processId(process); JobQueueInfo queuedJobInfo = jobQueueInfoService.findOne(queueId); LOGGER.info("Set Job's pid to be: " + pid); queuedJobInfo.setPid(pid); jobQueueInfoService.saveJobIntoQueue(queuedJobInfo); process.waitFor(); if (process.exitValue() == 0) { LOGGER.info(String.format("Moving txt file %s to %s", src, dest)); Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING); LOGGER.info(String.format("Moving json file %s to %s", json, dest)); Files.move(json, jsonDest, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(error); } else { LOGGER.info(String.format("Deleting tmp txt file %s", src)); Files.deleteIfExists(src); LOGGER.info(String.format("Moving error file %s to %s", error, errorDest)); Files.move(error, errorDest, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException | InterruptedException exception) { LOGGER.error("Algorithm did not run successfully.", exception); } LOGGER.info("Delete Job ID from queue: " + queueId); jobQueueInfoService.deleteJobById(queueId); return new AsyncResult<>(null); }
From source file:org.wso2.carbon.apimgt.core.impl.FileEncryptionUtility.java
/** * Encrypts the contents of a file and stores it in a new file * * @param inputFilePath absolute path of the file to encrypt * @param outputFilePath expected absolute path of the new encrypted file * @throws APIManagementException if an error occurs encrypting the file *//* w w w. j a v a 2 s. c om*/ public void encryptFile(String inputFilePath, String outputFilePath) throws APIManagementException { InputStream inputStream = null; CipherOutputStream cipherOutStream = null; try { Cipher aesCipher = Cipher.getInstance(EncryptionConstants.AES); SecretKeySpec aesKeySpec = new SecretKeySpec(getAESKey(), EncryptionConstants.AES); aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec); Files.deleteIfExists(Paths.get(outputFilePath)); inputStream = APIFileUtils.readFileContentAsStream(inputFilePath); cipherOutStream = new CipherOutputStream(new FileOutputStream(outputFilePath), aesCipher); IOUtils.copy(inputStream, cipherOutStream); APIFileUtils.deleteFile(inputFilePath); log.debug("Successfully encrypted file using stored AES key"); } catch (NoSuchPaddingException | NoSuchAlgorithmException | IOException | InvalidKeyException e) { String msg = "Error while encrypting the file at " + inputFilePath; throw new APIManagementException(msg, e); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(cipherOutStream); } }