List of usage examples for java.io File createTempFile
public static File createTempFile(String prefix, String suffix) throws IOException
From source file:de.brazzy.nikki.util.ThumbnailBenchmark.java
public static void main(String[] args) throws Exception { ImageReader r = new ImageReader(new File("C:/tmp/test.JPG"), DateTimeZone.UTC); r.readMainImage();// ww w . j av a2s . c o m long start = System.nanoTime(); byte[] t = r.scale(150, false, true); System.out.println(); System.out.println("ThumpnailRescaleOp: " + (System.nanoTime() - start) / (1000 * 1000 * 1000.0)); File out = File.createTempFile("thumbnail", ".jpg"); FileOutputStream stream = new FileOutputStream(out); IOUtils.write(t, stream); stream.close(); Desktop.getDesktop().open(out); start = System.nanoTime(); t = r.scale(150, false, false); System.out.println(); System.out.println("ResampleOp: " + (System.nanoTime() - start) / (1000 * 1000 * 1000.0)); out = File.createTempFile("thumbnail", ".jpg"); stream = new FileOutputStream(out); IOUtils.write(t, stream); stream.close(); Desktop.getDesktop().open(out); }
From source file:azkaban.migration.schedule2trigger.Schedule2Trigger.java
public static void main(String[] args) throws Exception { if (args.length < 1) { printUsage();/*from w w w. j a v a 2 s . c om*/ } File confFile = new File(args[0]); try { logger.info("Trying to load config from " + confFile.getAbsolutePath()); props = loadAzkabanConfig(confFile); } catch (Exception e) { e.printStackTrace(); logger.error(e); return; } try { outputDir = File.createTempFile("schedules", null); logger.info("Creating temp dir for dumping existing schedules."); outputDir.delete(); outputDir.mkdir(); } catch (Exception e) { e.printStackTrace(); logger.error(e); return; } try { schedule2File(); } catch (Exception e) { e.printStackTrace(); logger.error(e); return; } try { file2ScheduleTrigger(); } catch (Exception e) { e.printStackTrace(); logger.error(e); return; } logger.info("Uploaded all schedules. Removing temp dir."); FileUtils.deleteDirectory(outputDir); System.exit(0); }
From source file:info.debatty.java.datasets.examples.GaussianMixtureBuilder.java
/** * @param args the command line arguments *///from w w w. j av a2s. c om public static void main(String[] args) throws IOException, ClassNotFoundException { Dataset dataset = new Dataset.Builder(DIMENSIONALITY, CENTERS).setOverlap(Dataset.Builder.Overlap.MEDIUM) .varyDeviation(true).varyWeight(true).setSize(SIZE).build(); // You can serialize and save your Dataset. // This will not save all the points, but only the Dataset oject // (including eventual random seeds), // which allows to reproduce the dataset using only a small amount of // memory File file = File.createTempFile("testfile", ".ser"); dataset.save(new FileOutputStream(file)); Dataset d2 = (Dataset) Dataset.load(new FileInputStream(file)); // You can also save to complete data to disk if needed // (e.g. for plotting with Gnuplot) d2.saveCsv(new BufferedOutputStream(new FileOutputStream(File.createTempFile("gaussian", ".dat")))); float[][] float_array = new float[SIZE][]; int i = 0; for (double[] vector : d2) { //GaussianMixture.println(vector); float_array[i] = toFloatArray(vector); i++; } final FastScatterPlot2D demo = new FastScatterPlot2D("Gaussian Mixture Plot", transposeMatrix(float_array)); demo.pack(); demo.setVisible(true); }
From source file:com.mapr.PurchaseLog.java
public static void main(String[] args) throws IOException { Options opts = new Options(); CmdLineParser parser = new CmdLineParser(opts); try {/*from w w w . j ava2 s . com*/ parser.parseArgument(args); } catch (CmdLineException e) { System.err.println("Usage: -count <number>G|M|K [ -users number ] log-file user-profiles"); return; } Joiner withTab = Joiner.on("\t"); // first generate lots of user definitions SchemaSampler users = new SchemaSampler( Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read()); File userFile = File.createTempFile("user", "tsv"); BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8); for (int i = 0; i < opts.users; i++) { out.write(withTab.join(users.sample())); out.newLine(); } out.close(); // now generate a session for each user Splitter onTabs = Splitter.on("\t"); Splitter onComma = Splitter.on(","); Random gen = new Random(); SchemaSampler intermediate = new SchemaSampler( Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read()); final int COUNTRY = users.getFieldNames().indexOf("country"); final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list"); final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords"); Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema"); Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema"); Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema"); out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8); for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) { long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble()); List<String> user = Lists.newArrayList(onTabs.split(line)); // pick session length int n = (int) Math.floor(-30 * Math.log(gen.nextDouble())); for (int i = 0; i < n; i++) { // time on page int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble())); t += dt; // hit specific values JsonNode step = intermediate.sample(); // check for purchase double p = 0.01; List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText())); List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText())); if ((user.get(COUNTRY).equals("us") && campaigns.contains("5")) || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer") || keywords.contains("simpson")) { p = 0.5; } String events = gen.nextDouble() < p ? "1" : "-"; out.write(Long.toString(t)); out.write("\t"); out.write(line); out.write("\t"); out.write(withTab.join(step)); out.write("\t"); out.write(events); out.write("\n"); } } out.close(); }
From source file:io.anserini.util.SearchTimeUtil.java
public static void main(String[] args) throws IOException, ParseException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { if (args.length != 1) { System.err.println("Usage: SearchTimeUtil <indexDir>"); System.err.println("indexDir: index directory"); System.exit(1);// w w w.j a v a2 s. c o m } String[] topics = { "topics.web.1-50.txt", "topics.web.51-100.txt", "topics.web.101-150.txt", "topics.web.151-200.txt", "topics.web.201-250.txt", "topics.web.251-300.txt" }; SearchWebCollection searcher = new SearchWebCollection(args[0]); for (String topicFile : topics) { Path topicsFile = Paths.get("src/resources/topics-and-qrels/", topicFile); TopicReader tr = (TopicReader) Class.forName("io.anserini.search.query." + "Webxml" + "TopicReader") .getConstructor(Path.class).newInstance(topicsFile); SortedMap<Integer, String> queries = tr.read(); for (int i = 1; i <= 3; i++) { final long start = System.nanoTime(); String submissionFile = File.createTempFile(topicFile + "_" + i, ".tmp").getAbsolutePath(); RerankerCascade cascade = new RerankerCascade(); cascade.add(new IdentityReranker()); searcher.search(queries, submissionFile, new BM25Similarity(0.9f, 0.4f), 1000, cascade); final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS); System.out.println(topicFile + "_" + i + " search completed in " + DurationFormatUtils.formatDuration(durationMillis, "mm:ss:SSS")); } } searcher.close(); }
From source file:TempFiles.java
public static void main(String[] argv) throws IOException { // 1. Make an existing file temporary // Construct a File object for the backup created by editing // this source file. The file probably already exists. // My editor creates backups by putting ~ at the end of the name. File bkup = new File("Rename.java~"); // Arrange to have it deleted when the program ends. bkup.deleteOnExit();/*from w w w .ja va 2 s.c o m*/ // 2. Create a new temporary file. // Make a file object for foo.tmp, in the default temp directory File tmp = File.createTempFile("foo", "tmp"); // Report on the filename that it made up for us. System.out.println("Your temp file is " + tmp.getCanonicalPath()); // Arrange for it to be deleted at exit. tmp.deleteOnExit(); // Now do something with the temporary file, without having to // worry about deleting it later. writeDataInTemp(tmp.getCanonicalPath()); }
From source file:bixo.tools.LengthenUrlsTool.java
/** * @param args - URL to fetch, or path to file of URLs *//*from w w w. j ava2s . c o m*/ @SuppressWarnings("rawtypes") public static void main(String[] args) { try { String url = null; if (args.length == 0) { System.out.print("URL to lengthen: "); url = readInputLine(); if (url.length() == 0) { System.exit(0); } if (!url.startsWith("http://")) { url = "http://" + url; } } else if (args.length != 1) { System.out.print("A single URL or filename parameter is allowed"); System.exit(0); } else { url = args[0]; } String filename; if (!url.startsWith("http://")) { // It's a path to a file of URLs filename = url; } else { // We have a URL that we need to write to a temp file. File tempFile = File.createTempFile("LengthenUrlsTool", "txt"); filename = tempFile.getAbsolutePath(); FileWriter fw = new FileWriter(tempFile); IOUtils.write(url, fw); fw.close(); } System.setProperty("bixo.root.level", "TRACE"); // Uncomment this to see the wire log for HttpClient // System.setProperty("bixo.http.level", "DEBUG"); BaseFetcher fetcher = UrlLengthener.makeFetcher(10, ConfigUtils.BIXO_TOOL_AGENT); Pipe pipe = new Pipe("urls"); pipe = new Each(pipe, new UrlLengthener(fetcher)); pipe = new Each(pipe, new Debug()); BixoPlatform platform = new BixoPlatform(LengthenUrlsTool.class, Platform.Local); BasePath filePath = platform.makePath(filename); TextLine textLineLocalScheme = new TextLine(new Fields("url")); Tap sourceTap = platform.makeTap(textLineLocalScheme, filePath, SinkMode.KEEP); SinkTap sinkTap = new NullSinkTap(new Fields("url")); FlowConnector flowConnector = platform.makeFlowConnector(); Flow flow = flowConnector.connect(sourceTap, sinkTap, pipe); flow.complete(); } catch (Exception e) { System.err.println("Exception running tool: " + e.getMessage()); e.printStackTrace(System.err); System.exit(-1); } }
From source file:eu.ensure.aging.AgingSimulator.java
public static void main(String[] args) { Options options = new Options(); options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file"); options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file"); options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)"); Properties properties = new Properties(); CommandLineParser parser = new PosixParser(); try {//from ww w. ja v a 2s. co m CommandLine line = parser.parse(options, args); // if (line.hasOption("flip-bit-in-name")) { properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name")); } else { // On by default (if not explicitly de-activated above) properties.put("flip-bit-in-name", "true"); } // if (line.hasOption("flip-bit-in-uname")) { properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname")); } else { properties.put("flip-bit-in-uname", "false"); } // if (line.hasOption("update-checksum")) { properties.put("update-checksum", line.getOptionValue("update-checksum")); } else { properties.put("update-checksum", "false"); } String[] fileArgs = line.getArgs(); if (fileArgs.length < 1) { printHelp(options, System.err); System.exit(1); } String srcPath = fileArgs[0]; File srcAIP = new File(srcPath); if (!srcAIP.exists()) { String info = "The source path does not locate a file: " + srcPath; System.err.println(info); System.exit(1); } if (srcAIP.isDirectory()) { String info = "The source path locates a directory, not a file: " + srcPath; System.err.println(info); System.exit(1); } if (!srcAIP.canRead()) { String info = "Cannot read source file: " + srcPath; System.err.println(info); System.exit(1); } boolean doReplace = false; File destAIP = null; if (fileArgs.length > 1) { String destPath = fileArgs[1]; destAIP = new File(destPath); if (destAIP.exists()) { String info = "The destination path locates an existing file: " + destPath; System.err.println(info); System.exit(1); } } else { doReplace = true; try { destAIP = File.createTempFile("tmp-aged-aip-", ".tar"); } catch (IOException ioe) { String info = "Failed to create temporary file: "; info += ioe.getMessage(); System.err.println(info); System.exit(1); } } String info = "Age simulation\n"; info += " Reading from " + srcAIP.getName() + "\n"; if (doReplace) { info += " and replacing it's content"; } else { info += " Writing to " + destAIP.getName(); } System.out.println(info); // InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(srcAIP)); os = new BufferedOutputStream(new FileOutputStream(destAIP)); simulateAging(srcAIP.getName(), is, os, properties); } catch (FileNotFoundException fnfe) { info = "Could not locate file: " + fnfe.getMessage(); System.err.println(info); } finally { try { if (null != os) os.close(); if (null != is) is.close(); } catch (IOException ignore) { } } // if (doReplace) { File renamedOriginal = new File(srcAIP.getName() + "-backup"); srcAIP.renameTo(renamedOriginal); ReadableByteChannel rbc = null; WritableByteChannel wbc = null; try { rbc = Channels.newChannel(new FileInputStream(destAIP)); wbc = Channels.newChannel(new FileOutputStream(srcAIP)); FileIO.fastChannelCopy(rbc, wbc); } catch (FileNotFoundException fnfe) { info = "Could not locate temporary output file: " + fnfe.getMessage(); System.err.println(info); } catch (IOException ioe) { info = "Could not copy temporary output file over original AIP: " + ioe.getMessage(); System.err.println(info); } finally { try { if (null != wbc) wbc.close(); if (null != rbc) rbc.close(); destAIP.delete(); } catch (IOException ignore) { } } } } catch (ParseException pe) { String info = "Failed to parse command line: " + pe.getMessage(); System.err.println(info); printHelp(options, System.err); System.exit(1); } }
From source file:com.vmware.photon.controller.core.Main.java
public static void main(String[] args) throws Throwable { try {//from w w w .j a v a2 s . co m 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:it.unimi.di.big.mg4j.tool.URLMPHVirtualDocumentResolver.java
public static void main(final String[] arg) throws JSAPException, IOException { final SimpleJSAP jsap = new SimpleJSAP(URLMPHVirtualDocumentResolver.class.getName(), "Builds a URL document resolver from a sequence of URIs, extracted typically using ScanMetadata, using a suitable function. You can specify that the list is sorted, in which case it is possible to generate a resolver that occupies less space.", new Parameter[] { new Switch("sorted", 's', "sorted", "URIs are sorted: use a monotone minimal perfect hash function."), new Switch("iso", 'i', "iso", "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)."), new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b', "buffer-size", "The size of the I/O buffer used to read terms."), new FlaggedOption("class", MG4JClassParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'c', "class", "A class used to create the function from URIs to their ranks; defaults to it.unimi.dsi.sux4j.mph.MHWCFunction for non-sorted inputs, and to it.unimi.dsi.sux4j.mph.TwoStepsLcpMonotoneMinimalPerfectHashFunction for sorted inputs."), new FlaggedOption("width", JSAP.INTEGER_PARSER, Integer.toString(Long.SIZE), JSAP.NOT_REQUIRED, 'w', "width", "The width, in bits, of the signatures used to sign the function from URIs to their rank."), new FlaggedOption("termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "offline", "Read terms from this file (without loading them into core memory) instead of standard input."), new FlaggedOption("uniqueUris", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'U', "unique-uris", "Force URIs to be unique by adding random garbage at the end of duplicates; the argument is an upper bound for the number of URIs that will be read, and will be used to create a Bloom filter."), new UnflaggedOption("resolver", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the resolver.") }); JSAPResult jsapResult = jsap.parse(arg); if (jsap.messagePrinted()) return;/* ww w. j ava 2 s . c om*/ final int bufferSize = jsapResult.getInt("bufferSize"); final String resolverName = jsapResult.getString("resolver"); //final Class<?> tableClass = jsapResult.getClass( "class" ); final boolean iso = jsapResult.getBoolean("iso"); String termFile = jsapResult.getString("termFile"); BloomFilter<Void> filter = null; final boolean uniqueURIs = jsapResult.userSpecified("uniqueUris"); if (uniqueURIs) filter = BloomFilter.create(jsapResult.getInt("uniqueUris")); final Collection<? extends CharSequence> collection; if (termFile == null) { ArrayList<MutableString> termList = new ArrayList<MutableString>(); final ProgressLogger pl = new ProgressLogger(); pl.itemsName = "URIs"; final LineIterator termIterator = new LineIterator( new FastBufferedReader(new InputStreamReader(System.in, "UTF-8"), bufferSize), pl); pl.start("Reading URIs..."); MutableString uri; while (termIterator.hasNext()) { uri = termIterator.next(); if (uniqueURIs) makeUnique(filter, uri); termList.add(uri.copy()); } pl.done(); collection = termList; } else { if (uniqueURIs) { // Create temporary file with unique URIs final ProgressLogger pl = new ProgressLogger(); pl.itemsName = "URIs"; pl.start("Copying URIs..."); final LineIterator termIterator = new LineIterator( new FastBufferedReader(new InputStreamReader(new FileInputStream(termFile)), bufferSize), pl); File temp = File.createTempFile(URLMPHVirtualDocumentResolver.class.getName(), ".uniqueuris"); temp.deleteOnExit(); termFile = temp.toString(); final FastBufferedOutputStream outputStream = new FastBufferedOutputStream( new FileOutputStream(termFile), bufferSize); MutableString uri; while (termIterator.hasNext()) { uri = termIterator.next(); makeUnique(filter, uri); uri.writeUTF8(outputStream); outputStream.write('\n'); } pl.done(); outputStream.close(); } collection = new FileLinesCollection(termFile, "UTF-8"); } LOGGER.debug("Building function..."); final int width = jsapResult.getInt("width"); if (jsapResult.getBoolean("sorted")) BinIO.storeObject( new URLMPHVirtualDocumentResolver( new ShiftAddXorSignedStringMap(collection.iterator(), new TwoStepsLcpMonotoneMinimalPerfectHashFunction<CharSequence>(collection, iso ? TransformationStrategies.prefixFreeIso() : TransformationStrategies.prefixFreeUtf16()), width)), resolverName); else BinIO.storeObject( new URLMPHVirtualDocumentResolver(new ShiftAddXorSignedStringMap(collection.iterator(), new MWHCFunction<CharSequence>(collection, iso ? TransformationStrategies.iso() : TransformationStrategies.utf16()), width)), resolverName); LOGGER.debug(" done."); }