List of usage examples for java.io File deleteOnExit
public void deleteOnExit()
From source file:edu.uthscsa.ric.papaya.builder.Builder.java
public static void main(final String[] args) { final Builder builder = new Builder(); // process command line final CommandLine cli = builder.createCLI(args); builder.setUseSample(cli.hasOption(ARG_SAMPLE)); builder.setUseAtlas(cli.hasOption(ARG_ATLAS)); builder.setLocal(cli.hasOption(ARG_LOCAL)); builder.setPrintHelp(cli.hasOption(ARG_HELP)); builder.setUseImages(cli.hasOption(ARG_IMAGE)); builder.setSingleFile(cli.hasOption(ARG_SINGLE)); builder.setUseParamFile(cli.hasOption(ARG_PARAM_FILE)); builder.setUseTitle(cli.hasOption(ARG_TITLE)); // print help, if necessary if (builder.isPrintHelp()) { builder.printHelp();//from www.j av a2s . co m return; } // find project root directory if (cli.hasOption(ARG_ROOT)) { try { builder.projectDir = (new File(cli.getOptionValue(ARG_ROOT))).getCanonicalFile(); } catch (final IOException ex) { System.err.println("Problem finding root directory. Reason: " + ex.getMessage()); } } if (builder.projectDir == null) { builder.projectDir = new File(System.getProperty("user.dir")); } // clean output dir final File outputDir = new File(builder.projectDir + "/" + OUTPUT_DIR); System.out.println("Cleaning output directory..."); try { builder.cleanOutputDir(outputDir); } catch (final IOException ex) { System.err.println("Problem cleaning build directory. Reason: " + ex.getMessage()); } if (builder.isLocal()) { System.out.println("Building for local usage..."); } // write JS final File compressedFileJs = new File(outputDir, OUTPUT_JS_FILENAME); // build properties try { final File buildFile = new File(builder.projectDir + "/" + BUILD_PROP_FILE); builder.readBuildProperties(buildFile); builder.buildNumber++; // increment build number builder.writeBuildProperties(compressedFileJs, true); builder.writeBuildProperties(buildFile, false); } catch (final IOException ex) { System.err.println("Problem handling build properties. Reason: " + ex.getMessage()); } String htmlParameters = null; if (builder.isUseParamFile()) { final String paramFileArg = cli.getOptionValue(ARG_PARAM_FILE); if (paramFileArg != null) { try { System.out.println("Including parameters..."); final String parameters = FileUtils.readFileToString(new File(paramFileArg), "UTF-8"); htmlParameters = "var params = " + parameters + ";"; } catch (final IOException ex) { System.err.println("Problem reading parameters file! " + ex.getMessage()); } } } String title = null; if (builder.isUseTitle()) { String str = cli.getOptionValue(ARG_TITLE); if (str != null) { str = str.trim(); str = str.replace("\"", ""); str = str.replace("'", ""); if (str.length() > 0) { title = str; System.out.println("Using title: " + title); } } } try { final JSONArray loadableImages = new JSONArray(); // sample image if (builder.isUseSample()) { System.out.println("Including sample image..."); final File sampleFile = new File(builder.projectDir + "/" + SAMPLE_IMAGE_NII_FILE); final String filename = Utilities .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(sampleFile.getName())); if (builder.isLocal()) { loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename + "\",\"encode\":\"" + filename + "\"}")); final String sampleEncoded = Utilities.encodeImageFile(sampleFile); FileUtils.writeStringToFile(compressedFileJs, "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true); } else { loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename + "\",\"url\":\"" + SAMPLE_IMAGE_NII_FILE + "\"}")); FileUtils.copyFile(sampleFile, new File(outputDir + "/" + SAMPLE_IMAGE_NII_FILE)); } } // atlas if (builder.isUseAtlas()) { Atlas atlas = null; try { String atlasArg = cli.getOptionValue(ARG_ATLAS); if (atlasArg == null) { atlasArg = (builder.projectDir + "/" + SAMPLE_DEFAULT_ATLAS_FILE); } final File atlasXmlFile = new File(atlasArg); System.out.println("Including atlas " + atlasXmlFile); atlas = new Atlas(atlasXmlFile); final File atlasJavaScriptFile = atlas.createAtlas(builder.isLocal()); System.out.println("Using atlas image file " + atlas.getImageFile()); if (builder.isLocal()) { loadableImages.put( new JSONObject("{\"nicename\":\"Atlas\",\"name\":\"" + atlas.getImageFileNewName() + "\",\"encode\":\"" + atlas.getImageFileNewName() + "\",\"hide\":true}")); } else { final File atlasImageFile = atlas.getImageFile(); final String atlasPath = "data/" + atlasImageFile.getName(); loadableImages.put(new JSONObject("{\"nicename\":\"Atlas\",\"name\":\"" + atlas.getImageFileNewName() + "\",\"url\":\"" + atlasPath + "\",\"hide\":true}")); FileUtils.copyFile(atlasImageFile, new File(outputDir + "/" + atlasPath)); } builder.writeFile(atlasJavaScriptFile, compressedFileJs); } catch (final IOException ex) { System.err.println("Problem finding atlas file. Reason: " + ex.getMessage()); } } // additional images if (builder.isUseImages()) { final String[] imageArgs = cli.getOptionValues(ARG_IMAGE); if (imageArgs != null) { for (final String imageArg : imageArgs) { final File file = new File(imageArg); System.out.println("Including image " + file); final String filename = Utilities .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(file.getName())); if (builder.isLocal()) { loadableImages.put(new JSONObject( "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName()) + "\",\"name\":\"" + filename + "\",\"encode\":\"" + filename + "\"}")); final String sampleEncoded = Utilities.encodeImageFile(file); FileUtils.writeStringToFile(compressedFileJs, "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true); } else { final String filePath = "data/" + file.getName(); loadableImages.put(new JSONObject( "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName()) + "\",\"name\":\"" + filename + "\",\"url\":\"" + filePath + "\"}")); FileUtils.copyFile(file, new File(outputDir + "/" + filePath)); } } } } File tempFileJs = null; try { tempFileJs = builder.createTempFile(); } catch (final IOException ex) { System.err.println("Problem creating temp write file. Reason: " + ex.getMessage()); } // write image refs FileUtils.writeStringToFile(tempFileJs, "var " + PAPAYA_LOADABLE_IMAGES + " = " + loadableImages.toString() + ";\n", "UTF-8", true); // compress JS tempFileJs = builder.concatenateFiles(JS_FILES, "js", tempFileJs); System.out.println("Compressing JavaScript... "); FileUtils.writeStringToFile(compressedFileJs, "\n", "UTF-8", true); builder.compressJavaScript(tempFileJs, compressedFileJs, new YuiCompressorOptions()); //tempFileJs.deleteOnExit(); } catch (final IOException ex) { System.err.println("Problem concatenating JavaScript. Reason: " + ex.getMessage()); } // compress CSS final File compressedFileCss = new File(outputDir, OUTPUT_CSS_FILENAME); try { final File concatFile = builder.concatenateFiles(CSS_FILES, "css", null); System.out.println("Compressing CSS... "); builder.compressCSS(concatFile, compressedFileCss, new YuiCompressorOptions()); concatFile.deleteOnExit(); } catch (final IOException ex) { System.err.println("Problem concatenating CSS. Reason: " + ex.getMessage()); } // write HTML try { System.out.println("Writing HTML... "); if (builder.singleFile) { builder.writeHtml(outputDir, compressedFileJs, compressedFileCss, htmlParameters, title); } else { builder.writeHtml(outputDir, htmlParameters, title); } } catch (final IOException ex) { System.err.println("Problem writing HTML. Reason: " + ex.getMessage()); } System.out.println("Done! Output files located at " + outputDir); }
From source file:Lock.java
public static void main(String args[]) throws IOException, InterruptedException { RandomAccessFile file = null; // The file we'll lock FileChannel f = null; // The channel to the file FileLock lock = null; // The lock object we hold try { // The finally clause closes the channel and releases the lock // We use a temporary file as the lock file. String tmpdir = System.getProperty("java.io.tmpdir"); String filename = Lock.class.getName() + ".lock"; File lockfile = new File(tmpdir, filename); // Create a FileChannel that can read and write that file. // Note that we rely on the java.io package to open the file, // in read/write mode, and then just get a channel from it. // This will create the file if it doesn't exit. We'll arrange // for it to be deleted below, if we succeed in locking it. file = new RandomAccessFile(lockfile, "rw"); f = file.getChannel();//from ww w . ja v a 2 s. com // Try to get an exclusive lock on the file. // This method will return a lock or null, but will not block. // See also FileChannel.lock() for a blocking variant. lock = f.tryLock(); if (lock != null) { // We obtained the lock, so arrange to delete the file when // we're done, and then write the approximate time at which // we'll relinquish the lock into the file. lockfile.deleteOnExit(); // Just a temporary file // First, we need a buffer to hold the timestamp ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes // Put the time in the buffer and flip to prepare for writing // Note that many Buffer methods can be "chained" like this. bytes.putLong(System.currentTimeMillis() + 10000).flip(); f.write(bytes); // Write the buffer contents to the channel f.force(false); // Force them out to the disk } else { // We didn't get the lock, which means another instance is // running. First, let the user know this. System.out.println("Another instance is already running"); // Next, we attempt to read the file to figure out how much // longer the other instance will be running. Since we don't // have a lock, the read may fail or return inconsistent data. try { ByteBuffer bytes = ByteBuffer.allocate(8); f.read(bytes); // Read 8 bytes from the file bytes.flip(); // Flip buffer before extracting bytes long exittime = bytes.getLong(); // Read bytes as a long // Figure out how long that time is from now and round // it to the nearest second. long secs = (exittime - System.currentTimeMillis() + 500) / 1000; // And tell the user about it. System.out.println("Try again in about " + secs + " seconds"); } catch (IOException e) { // This probably means that locking is enforced by the OS // and we were prevented from reading the file. } // This is an abnormal exit, so set an exit code. System.exit(1); } // Simulate a real application by sleeping for 10 seconds. System.out.println("Starting..."); Thread.sleep(10000); System.out.println("Exiting."); } finally { // Always release the lock and close the file // Closing the RandomAccessFile also closes its FileChannel. if (lock != null && lock.isValid()) lock.release(); if (file != null) file.close(); } }
From source file:com.vmware.photon.controller.core.Main.java
public static void main(String[] args) throws Throwable { try {/*w w w . ja v a2s. c om*/ LoggingFactory.bootstrap(); logger.info("args: " + Arrays.toString(args)); ArgumentParser parser = ArgumentParsers.newArgumentParser("PhotonControllerCore").defaultHelp(true) .description("Photon Controller Core"); parser.addArgument("config-file").help("photon controller configuration file"); parser.addArgument("--manual").type(Boolean.class).setDefault(false) .help("If true, create default deployment."); Namespace namespace = parser.parseArgsOrFail(args); PhotonControllerConfig photonControllerConfig = getPhotonControllerConfig(namespace); DeployerConfig deployerConfig = photonControllerConfig.getDeployerConfig(); new LoggingFactory(photonControllerConfig.getLogging(), "photon-controller-core").configure(); SSLContext sslContext; if (deployerConfig.getDeployerContext().isAuthEnabled()) { sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL); TrustManagerFactory tmf = null; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream in = FileUtils .openInputStream(new File(deployerConfig.getDeployerContext().getKeyStorePath())); keyStore.load(in, deployerConfig.getDeployerContext().getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext.init(null, tmf.getTrustManagers(), null); } else { KeyStoreUtils.generateKeys("/thrift/"); sslContext = KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } ThriftModule thriftModule = new ThriftModule(sslContext); PhotonControllerXenonHost xenonHost = startXenonHost(photonControllerConfig, thriftModule, deployerConfig, sslContext); if ((Boolean) namespace.get("manual")) { DefaultDeployment.createDefaultDeployment(photonControllerConfig.getXenonConfig().getPeerNodes(), deployerConfig, xenonHost); } // Creating a temp configuration file for apife with modification to some named sections in photon-controller-config // so that it can match the Configuration class of dropwizard. File apiFeTempConfig = File.createTempFile("apiFeTempConfig", ".tmp"); File source = new File(args[0]); FileInputStream fis = new FileInputStream(source); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); FileWriter fstream = new FileWriter(apiFeTempConfig, true); BufferedWriter out = new BufferedWriter(fstream); String aLine = null; while ((aLine = in.readLine()) != null) { if (aLine.equals("apife:")) { aLine = aLine.replace("apife:", "server:"); } out.write(aLine); out.newLine(); } in.close(); out.close(); // This approach can be simplified once the apife container is gone, but for the time being // it expects the first arg to be the string "server". String[] apiFeArgs = new String[2]; apiFeArgs[0] = "server"; apiFeArgs[1] = apiFeTempConfig.getAbsolutePath(); ApiFeService.setupApiFeConfigurationForServerCommand(apiFeArgs); ApiFeService.addServiceHost(xenonHost); ApiFeService.setSSLContext(sslContext); ApiFeService apiFeService = new ApiFeService(); apiFeService.run(apiFeArgs); apiFeTempConfig.deleteOnExit(); LocalApiClient localApiClient = apiFeService.getInjector().getInstance(LocalApiClient.class); xenonHost.setApiClient(localApiClient); // in the non-auth enabled scenario we need to be able to accept any self-signed certificate if (!deployerConfig.getDeployerContext().isAuthEnabled()) { KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { logger.info("Shutting down"); xenonHost.stop(); logger.info("Done"); LoggingFactory.detachAndStop(); } }); } catch (Exception e) { logger.error("Failed to start photon controller ", e); throw e; } }
From source file:Main.java
public static void deleteTmpFileOnExit(File fi) { fi.deleteOnExit(); }
From source file:Main.java
/** * Clear the cache directory./*from ww w . ja v a 2s. c o m*/ * * @return whether the cache directory is cleared. */ public static boolean clearCache() { File[] files = sAppContext.getCacheDir().listFiles(); if (files == null) return false; for (File file : files) { file.deleteOnExit(); } return true; }
From source file:Main.java
private static File createTempFile(String filename) { try {/*from www.j a va2 s . c o m*/ int dotIndex = filename.lastIndexOf("."); String prefix = filename.substring(0, dotIndex); String suffix = filename.substring(dotIndex + 1); File temp = File.createTempFile(prefix, suffix); temp.deleteOnExit(); return temp; } catch (Exception e) { throw new RuntimeException("Could not create temp file: " + filename, e); } }
From source file:edu.uci.ics.asterix.drivers.AsterixCLI.java
public static void setUp(Options options) throws Exception { System.setProperty(GlobalConfig.CONFIG_FILE_PROPERTY, options.properties); File outdir = new File(options.outputFolder); outdir.mkdirs();//from w w w.j av a 2 s . c om File log = new File("asterix_logs"); if (log.exists()) FileUtils.deleteDirectory(log); File lsn = new File("last_checkpoint_lsn"); lsn.deleteOnExit(); AsterixHyracksIntegrationUtil.init(); }
From source file:Main.java
public static void createTestDataFile(String filename, String[] lines) throws IOException { FileWriter writer = null;// w ww .j a va2 s. c o m try { File file = new File(filename); file.deleteOnExit(); writer = new FileWriter(file); for (String line : lines) { writer.write(line + "\n"); } } finally { if (writer != null) { writer.close(); } } }
From source file:edu.scripps.fl.test.pubchem.test.FetchFromDepositionSystemTest.java
private static void displayFile(int aid, InputStream is, String ext) throws IOException { File file = File.createTempFile("AID" + aid + "-", "." + ext); file.deleteOnExit(); IOUtils.copy(is, new FileOutputStream(file)); is.close();//from w w w . j a va2 s. c om log.info("Created file " + file); // Desktop.getDesktop().open(file); }
From source file:Main.java
public static File WriteStreamToFile(InputStream resStream) { try {// www. ja v a2s. c om byte[] bytes = new byte[resStream.available()]; File tmpFile = File.createTempFile("z4-", ".tmp"); tmpFile.deleteOnExit(); DataInputStream dis = new DataInputStream(resStream); dis.readFully(bytes); FileOutputStream foutStream = new FileOutputStream(tmpFile.getPath()); foutStream.write(bytes); foutStream.close(); dis.close(); return tmpFile; } catch (Exception e) { e.printStackTrace(); } return null; }