List of usage examples for java.io File deleteOnExit
public void deleteOnExit()
From source file:it.cnr.icar.eric.server.cms.CanonicalXMLFilteringService.java
/** * Runs XSLT based upon specified inputs and returns the outputfile. * * TODO: Need some refactoring to make this reusable throughout OMAR * particularly in CanonicalXMLCatalogingService. *///www . j ava2s . co m protected static File runXSLT(StreamSource input, StreamSource xslt, URIResolver resolver, HashMap<String, String> params) throws RegistryException { File outputFile = null; try { //dumpStream(xslt); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = initTransformer(tFactory, xslt); // Use FilteringService URIResolver to resolve RIs submitted in the // ServiceInput object transformer.setURIResolver(resolver); //Set respository item as parameter //Create the output file with the filtered RegistryObject Metadata outputFile = File.createTempFile("CanonicalXMLFilteringService_Output", ".xml"); outputFile.deleteOnExit(); log.debug("outputFile= " + outputFile.getAbsolutePath()); Iterator<String> iter = params.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); Object value = params.get(key); transformer.setParameter(key, value); } StreamResult sr = new StreamResult(outputFile); transformer.transform(input, sr); } catch (Exception e) { throw new RegistryException(e); } return outputFile; }
From source file:com.hazelcast.test.starter.HazelcastVersionLocator.java
private static File downloadFile(String url, File targetDirectory, String filename) { CloseableHttpClient client = HttpClients.createDefault(); File targetFile = new File(targetDirectory, filename); if (targetFile.isFile() && targetFile.exists()) { return targetFile; }/*from w ww . j a v a2 s . com*/ HttpGet request = new HttpGet(url); try { CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != SC_OK) { throw new GuardianException("Cannot download file from " + url + ", http response code: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); FileOutputStream fos = new FileOutputStream(targetFile); entity.writeTo(fos); fos.close(); targetFile.deleteOnExit(); return targetFile; } catch (IOException e) { throw rethrowGuardianException(e); } finally { try { client.close(); } catch (IOException e) { // ignore } } }
From source file:com.intel.cryptostream.utils.NativeCodeLoader.java
/** * Extract the specified library file to the target folder * /*from w ww . j a v a2 s . co m*/ * @param libFolderForCurrentOS * @param libraryFileName * @param targetFolder * @return */ private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Attach UUID to the native library file to ensure multiple class loaders // can read the libcryptostream multiple times. String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("cryptostream-%s-%s-%s", getVersion(), uuid, libraryFileName); File extractedLibFile = new File(targetFolder, extractedLibFileName); try { // Extract a native library file into the target directory InputStream reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); try { byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } } finally { // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); if (writer != null) writer.close(); if (reader != null) reader.close(); } // Set executable (x) flag to enable Java to load the native library extractedLibFile.setReadable(true); extractedLibFile.setWritable(true, true); extractedLibFile.setExecutable(true); // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath); InputStream extractedLibIn = new FileInputStream(extractedLibFile); try { if (!contentsEquals(nativeIn, extractedLibIn)) throw new RuntimeException( String.format("Failed to write a native library file at %s", extractedLibFile)); } finally { if (nativeIn != null) nativeIn.close(); if (extractedLibIn != null) extractedLibIn.close(); } } return new File(targetFolder, extractedLibFileName); } catch (IOException e) { e.printStackTrace(System.err); return null; } }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * <p>This method updates a template war with the following settings.</p> * @param templateWar The name of the template war to pull from the classpath. * @param war The path of an external war to update (optional). * @param newWarNames The name to give the new war. (note: only the first element of this list is used.) * @param repoUri The uri to a github repo to pull content from. * @param branch The branch of the github repo to pull content from. * @param configRepoUri The uri to a github repo to pull config from. * @param configBranch The branch of the github repo to pull config from. * @param domain The domain to bind a vHost to. * @param context The context root that this war will deploy to. * @param secure A flag to set if this war needs to have its contents password protected. * @throws Exception/*from w ww . j a v a 2 s .co m*/ */ public static void updateWar(String templateWar, String war, List<String> newWarNames, String repoUri, String branch, String configRepoUri, String configBranch, String domain, String context, boolean secure, Logger log) throws Exception { ZipFile inZip = null; ZipOutputStream outZip = null; InputStream in = null; OutputStream out = null; try { if (war != null) { if (war.equals(newWarNames.get(0))) { File tmpZip = File.createTempFile(war, null); tmpZip.delete(); tmpZip.deleteOnExit(); new File(war).renameTo(tmpZip); war = tmpZip.getAbsolutePath(); } inZip = new ZipFile(war); } else { File tmpZip = File.createTempFile("cadmium-war", "war"); tmpZip.delete(); tmpZip.deleteOnExit(); in = WarUtils.class.getClassLoader().getResourceAsStream(templateWar); out = new FileOutputStream(tmpZip); FileSystemManager.streamCopy(in, out); inZip = new ZipFile(tmpZip); } outZip = new ZipOutputStream(new FileOutputStream(newWarNames.get(0))); ZipEntry cadmiumPropertiesEntry = null; cadmiumPropertiesEntry = inZip.getEntry("WEB-INF/cadmium.properties"); Properties cadmiumProps = updateProperties(inZip, cadmiumPropertiesEntry, repoUri, branch, configRepoUri, configBranch); ZipEntry jbossWeb = null; jbossWeb = inZip.getEntry("WEB-INF/jboss-web.xml"); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().equals(cadmiumPropertiesEntry.getName())) { storeProperties(outZip, cadmiumPropertiesEntry, cadmiumProps, newWarNames); } else if (((domain != null && domain.length() > 0) || (context != null && context.length() > 0)) && e.getName().equals(jbossWeb.getName())) { updateDomain(inZip, outZip, jbossWeb, domain, context); } else if (secure && e.getName().equals("WEB-INF/web.xml")) { addSecurity(inZip, outZip, e); } else { outZip.putNextEntry(e); if (!e.isDirectory()) { FileSystemManager.streamCopy(inZip.getInputStream(e), outZip, true); } outZip.closeEntry(); } } } finally { if (FileSystemManager.exists("tmp_cadmium-war.war")) { new File("tmp_cadmium-war.war").delete(); } try { if (inZip != null) { inZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + war); } } try { if (outZip != null) { outZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + newWarNames.get(0)); } } try { if (out != null) { out.close(); } } catch (Exception e) { } try { if (in != null) { in.close(); } } catch (Exception e) { } } }
From source file:gov.jgi.meta.MetaUtils.java
/** * Recursively delete file or directory// w w w . ja v a 2 s . c o m * * @param fileOrDir the file or dir to delete * @return true iff all files are successfully deleted */ public static boolean recursiveDelete(File fileOrDir) { if (fileOrDir.isDirectory()) { // recursively delete contents for (File innerFile : fileOrDir.listFiles()) { if (!recursiveDelete(innerFile)) { fileOrDir.deleteOnExit(); return (false); } } } if (!fileOrDir.delete()) { fileOrDir.deleteOnExit(); return (false); } return (true); }
From source file:gate.util.Files.java
/** * Writes a temporary file into the default temporary directory, * form an InputStream a unique ID is generated and associated automaticaly * with the file name...// w w w. ja v a 2 s .com */ public static File writeTempFile(InputStream contentStream) throws IOException { File resourceFile = null; FileOutputStream resourceFileOutputStream = null; try { // create a temporary file name resourceFile = File.createTempFile("gateResource", ".tmp"); resourceFileOutputStream = new FileOutputStream(resourceFile); resourceFile.deleteOnExit(); if (contentStream == null) return resourceFile; int bytesRead = 0; final int readSize = 1024; byte[] bytes = new byte[readSize]; while ((bytesRead = contentStream.read(bytes, 0, readSize)) != -1) resourceFileOutputStream.write(bytes, 0, bytesRead); } finally { IOUtils.closeQuietly(resourceFileOutputStream); IOUtils.closeQuietly(contentStream); } return resourceFile; }
From source file:com.zimbra.qa.unittest.TestImap.java
private static Literal message(int size) throws IOException { File file = File.createTempFile("msg", null); file.deleteOnExit(); FileWriter out = new FileWriter(file); try {//from w ww . j a va 2 s .co m out.write(simpleMessage("test message")); for (int i = 0; i < size; i++) { out.write('X'); if (i % 72 == 0) { out.write("\r\n"); } } } finally { out.close(); } return new Literal(file, true); }
From source file:com.intel.chimera.utils.NativeCodeLoader.java
/** * Extracts the specified library file to the target folder. * /*from www .j a va 2 s .c o m*/ * @param libFolderForCurrentOS the library in chimera.lib.path. * @param libraryFileName the library name. * @param targetFolder Target folder for the native lib. Use the value of * chimera.tempdir or java.io.tmpdir. * @return the library file. */ private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Attach UUID to the native library file to ensure multiple class loaders // can read the libchimera multiple times. String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("chimera-%s-%s-%s", getVersion(), uuid, libraryFileName); File extractedLibFile = new File(targetFolder, extractedLibFileName); InputStream reader = null; try { // Extract a native library file into the target directory reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); try { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } } finally { // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); if (writer != null) { writer.close(); } if (reader != null) { reader.close(); reader = null; } } // Set executable (x) flag to enable Java to load the native library if (!extractedLibFile.setReadable(true) || !extractedLibFile.setExecutable(true) || !extractedLibFile.setWritable(true, true)) { throw new RuntimeException("Invalid path for library path"); } // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = null; InputStream extractedLibIn = null; try { nativeIn = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath); extractedLibIn = new FileInputStream(extractedLibFile); if (!contentsEquals(nativeIn, extractedLibIn)) throw new RuntimeException( String.format("Failed to write a native library file at %s", extractedLibFile)); } finally { if (nativeIn != null) nativeIn.close(); if (extractedLibIn != null) extractedLibIn.close(); } } return new File(targetFolder, extractedLibFileName); } catch (IOException e) { e.printStackTrace(System.err); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:eu.edisonproject.training.execute.Main.java
private static void calculateTFIDF(String in, String out) throws IOException { File tmpFolder = null; try {//w ww .j a v a 2 s . c o m String contextName = FilenameUtils.removeExtension(in.substring(in.lastIndexOf(File.separator) + 1)); ITFIDFDriver tfidfDriver = new TFIDFDriverImpl(contextName); File inFile = new File(in); String workingFolder = System.getProperty("working.folder"); if (workingFolder == null) { workingFolder = prop.getProperty("working.folder", System.getProperty("java.io.tmpdir")); } tmpFolder = new File(workingFolder + File.separator + System.currentTimeMillis()); tmpFolder.mkdir(); tmpFolder.deleteOnExit(); setTFIDFDriverImplPaths(inFile, tmpFolder); tfidfDriver.executeTFIDF(tmpFolder.getAbsolutePath()); tfidfDriver.driveProcessResizeVector(); File ctxPath = new File(TFIDFDriverImpl.CONTEXT_PATH); for (File f : ctxPath.listFiles()) { if (FilenameUtils.getExtension(f.getName()).endsWith("csv")) { FileUtils.moveFile(f, new File(out + File.separator + f.getName())); } } } finally { if (tmpFolder != null && tmpFolder.exists()) { tmpFolder.delete(); FileUtils.forceDelete(tmpFolder); } } }
From source file:net.lightbody.bmp.proxy.jetty.util.JarResource.java
public static void extract(Resource resource, File directory, boolean deleteOnExit) throws IOException { if (log.isDebugEnabled()) log.debug("Extract " + resource + " to " + directory); JarInputStream jin = new JarInputStream(resource.getInputStream()); JarEntry entry = null;/*from w ww . j av a2 s . c o m*/ while ((entry = jin.getNextJarEntry()) != null) { File file = new File(directory, entry.getName()); if (entry.isDirectory()) { // Make directory if (!file.exists()) file.mkdirs(); } else { // make directory (some jars don't list dirs) File dir = new File(file.getParent()); if (!dir.exists()) dir.mkdirs(); // Make file FileOutputStream fout = null; try { fout = new FileOutputStream(file); IO.copy(jin, fout); } finally { IO.close(fout); } // touch the file. if (entry.getTime() >= 0) file.setLastModified(entry.getTime()); } if (deleteOnExit) file.deleteOnExit(); } }