List of usage examples for com.google.common.io Files append
public static void append(CharSequence from, File to, Charset charset) throws IOException
From source file:com.dopsun.msg4j.tools.CodeGen.java
/** * @param args/* w w w . j a v a 2 s. co m*/ * @throws IOException * @throws MalformedURLException * @throws ParseException */ public static void main(String[] args) throws MalformedURLException, IOException, ParseException { Options options = new Options(); options.addOption("o", "out", true, "Output file"); options.addOption("s", "src", true, "Source file"); options.addOption("l", "lang", true, "Language"); CommandLineParser cmdParser = new DefaultParser(); CommandLine cmd = cmdParser.parse(options, args); String lang = cmd.getOptionValue("lang", "Java"); String srcFile = cmd.getOptionValue("src"); String outFile = cmd.getOptionValue("out"); YamlModelSource modelSource = YamlModelSource.load(new File(srcFile).toURI().toURL()); YamlModelParser parser = YamlModelParser.create(); ModelInfo modelInfo = parser.parse(modelSource); String codeText = null; if (lang.equals("Java")) { codeText = Generator.JAVA.generate(modelInfo); } else { throw new UnsupportedOperationException("Unrecognized lang: " + lang); } if (outFile != null) { File file = new File(outFile); if (file.exists()) { file.delete(); } file.createNewFile(); Files.append(codeText, new File(outFile), Charsets.UTF_8); } else { System.out.println(codeText); } }
From source file:org.polimi.zarathustra.experiment.DOMsDumpExperiment.java
/** * Dumps the DOMs from a set of URLs to a directory. Sample invocation: java * -jar domdump.jar urllist.txt /tmp/output. urllist.txt is expected to have * one URL per line, without an empty final line. * <p>/* w w w .jav a2 s .c om*/ * NOTE: for testing purposes, this can be run with an extra argument, * FIREFOX: if so, it runs a firefox webdriver instead of explorer. */ public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Invoke this experiment with 2 parameters:" + "urlFileList and outputDir"); System.exit(-1); } paramsAreOkOrDie(args); File inputFile = new File(args[0]); File outputDir = new File(args[1]); LocalWebdriverWorker worker; if ((args.length > 2) && (args[2].equals("FIREFOX"))) { System.out.println("Running in FIREFOX mode, for testing only"); worker = new LocalWebdriverWorker(false); } else { worker = new LocalWebdriverWorker(true); } List<String> urls = Files.readLines(inputFile, Charsets.UTF_8); urls = removeComments(urls); File manifest = new File(outputDir, "manifest.txt"); Files.append("Start capture. Version 1.0\n", manifest, Charsets.UTF_8); for (String url : urls) { try { storeDOM(url, outputDir, worker); storeDOMManifest(url, outputDir, new Date().getTime()); updateManifest(url, new Date().getTime(), manifest); } catch (TimeoutException e2) { System.out.println("WebDriver Timeout: " + e2.toString()); } catch (org.openqa.selenium.UnhandledAlertException e1) { System.out.println(url + " --- UnhandledAlertException caught" + e1.toString()); } catch (Exception e) { System.out.println("Generic exception caught: " + e.toString()); } } worker.quit(); }
From source file:com.github.rinde.vanlon15prima.PerformExperiment.java
public static void main(String[] args) { final long time = System.currentTimeMillis(); final Experiment.Builder experimentBuilder = Experiment.build(SUM).computeLocal().withRandomSeed(123) .withThreads(Runtime.getRuntime().availableProcessors()).repeat(1) .addScenarios(FileProvider.builder().add(Paths.get(DATASET)).filter("glob:**[09].scen")) .addResultListener(new CommandLineProgress(System.out)) .usePostProcessor(PostProcessors.statisticsPostProcessor()) // central: cheapest insertion configuration .addConfiguration(/* w ww . j av a 2 s .c o m*/ Central.solverConfiguration(CheapestInsertionHeuristic.supplier(SUM), "CheapInsert")) // central: random .addConfiguration(Central.solverConfiguration(RandomSolver.supplier())) // mas: auction cheapest insertion with 2-opt per vehicle .addConfiguration(MASConfiguration.pdptwBuilder().setName("Auction-R-opt2cih-B-cih") .addEventHandler(AddVehicleEvent.class, new VehicleHandler( SolverRoutePlanner.supplier( Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(SUM), SUM)), SolverBidder.supplier(SUM, CheapestInsertionHeuristic.supplier(SUM)))) .addModel(SolverModel.builder()).addModel(AuctionCommModel.builder()).build()); final Optional<ExperimentResults> results = experimentBuilder.perform(System.out, args); final long duration = System.currentTimeMillis() - time; if (!results.isPresent()) { return; } System.out.println("Done, computed " + results.get().getResults().size() + " simulations in " + duration / 1000d + "s"); final Multimap<MASConfiguration, SimulationResult> groupedResults = LinkedHashMultimap.create(); for (final SimulationResult sr : results.get().sortedResults()) { groupedResults.put(sr.getSimArgs().getMasConfig(), sr); } for (final MASConfiguration config : groupedResults.keySet()) { final Collection<SimulationResult> group = groupedResults.get(config); final File configResult = new File(RESULTS + config.getName() + ".csv"); try { Files.createParentDirs(configResult); } catch (final IOException e1) { throw new IllegalStateException(e1); } // deletes the file in case it already exists configResult.delete(); try { Files.append( "dynamism,urgency,scale,cost,travel_time,tardiness,over_time,is_valid,scenario_id,random_seed,comp_time,num_vehicles,num_orders\n", configResult, Charsets.UTF_8); } catch (final IOException e1) { throw new IllegalStateException(e1); } for (final SimulationResult sr : group) { final String pc = sr.getSimArgs().getScenario().getProblemClass().getId(); final String id = sr.getSimArgs().getScenario().getProblemInstanceId(); final int numVehicles = FluentIterable.from(sr.getSimArgs().getScenario().getEvents()) .filter(AddVehicleEvent.class).size(); try { final String scenarioName = Joiner.on("-").join(pc, id); final List<String> propsStrings = Files .readLines(new File(DATASET + scenarioName + ".properties"), Charsets.UTF_8); final Map<String, String> properties = Splitter.on("\n").withKeyValueSeparator(" = ") .split(Joiner.on("\n").join(propsStrings)); final double dynamism = Double.parseDouble(properties.get("dynamism_bin")); final long urgencyMean = Long.parseLong(properties.get("urgency")); final double scale = Double.parseDouble(properties.get("scale")); final StatisticsDTO stats = (StatisticsDTO) sr.getResultObject(); final double cost = SUM.computeCost(stats); final double travelTime = SUM.travelTime(stats); final double tardiness = SUM.tardiness(stats); final double overTime = SUM.overTime(stats); final boolean isValidResult = SUM.isValidResult(stats); final long computationTime = stats.computationTime; final long numOrders = Long.parseLong(properties.get("AddParcelEvent")); final String line = Joiner.on(",") .appendTo(new StringBuilder(), asList(dynamism, urgencyMean, scale, cost, travelTime, tardiness, overTime, isValidResult, scenarioName, sr.getSimArgs().getRandomSeed(), computationTime, numVehicles, numOrders)) .append(System.lineSeparator()).toString(); if (!isValidResult) { System.err.println("WARNING: FOUND AN INVALID RESULT: "); System.err.println(line); } Files.append(line, configResult, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalStateException(e); } } } }
From source file:com.github.rinde.dynurg.Experimentation.java
public static void main(String[] args) { System.out.println(System.getProperty("jppf.config")); final long time = System.currentTimeMillis(); final Experiment.Builder experimentBuilder = Experiment.build(SUM).computeDistributed().withRandomSeed(123) .repeat(10).numBatches(10)/* w w w. ja v a 2s . c om*/ .addScenarios( FileProvider.builder().add(Paths.get(DATASET)).filter("glob:**[01].[0-9]0#[0-5].scen")) .addResultListener(new CommandLineProgress(System.out)) .addConfiguration( Central.solverConfiguration(CheapestInsertionHeuristic.supplier(SUM), "-CheapInsert")) .addConfiguration(Central.solverConfiguration(CheapestInsertionHeuristic.supplier(TARDINESS), "-CheapInsert-Tard")) .addConfiguration(Central.solverConfiguration(CheapestInsertionHeuristic.supplier(DISTANCE), "-CheapInsert-Dist")) .addConfiguration(Central.solverConfiguration( Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(SUM), SUM), "-bfsOpt2-CheapInsert")) .addConfiguration(Central.solverConfiguration( Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(TARDINESS), TARDINESS), "-bfsOpt2-CheapInsert-Tard")) .addConfiguration(Central.solverConfiguration( Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(DISTANCE), DISTANCE), "-bfsOpt2-CheapInsert-Dist")) .addConfiguration(Central.solverConfiguration( Opt2.depthFirstSupplier(CheapestInsertionHeuristic.supplier(SUM), SUM), "-dfsOpt2-CheapInsert")) .addConfiguration(Central.solverConfiguration( Opt2.depthFirstSupplier(CheapestInsertionHeuristic.supplier(TARDINESS), TARDINESS), "-dfsOpt2-CheapInsert-Tard")) .addConfiguration(Central.solverConfiguration( Opt2.depthFirstSupplier(CheapestInsertionHeuristic.supplier(DISTANCE), DISTANCE), "-dfsOpt2-CheapInsert-Dist")); final Menu m = ExperimentCli.createMenuBuilder(experimentBuilder) .add(Option.builder("nv", ArgumentParser.INTEGER).longName("number-of-vehicles") .description("Changes the number of vehicles in all scenarios.").build(), experimentBuilder, new ArgHandler<Experiment.Builder, Integer>() { @Override public void execute(Experiment.Builder subject, Optional<Integer> argument) { subject.setScenarioReader(new NumVehiclesScenarioParser(argument.get())); } }) .build(); final Optional<String> error = m.safeExecute(args); if (error.isPresent()) { System.err.println(error.get()); return; } final ExperimentResults results = experimentBuilder.perform(); final long duration = System.currentTimeMillis() - time; System.out .println("Done, computed " + results.results.size() + " simulations in " + duration / 1000d + "s"); final Multimap<MASConfiguration, SimulationResult> groupedResults = LinkedHashMultimap.create(); for (final SimulationResult sr : results.sortedResults()) { groupedResults.put(sr.masConfiguration, sr); } for (final MASConfiguration config : groupedResults.keySet()) { final Collection<SimulationResult> group = groupedResults.get(config); final File configResult = new File(RESULTS + config.toString() + ".csv"); try { Files.createParentDirs(configResult); } catch (final IOException e1) { throw new IllegalStateException(e1); } // deletes the file in case it already exists configResult.delete(); try { Files.append( "dynamism,urgency_mean,urgency_sd,cost,travel_time,tardiness,over_time,is_valid,scenario_id,random_seed,comp_time,num_vehicles\n", configResult, Charsets.UTF_8); } catch (final IOException e1) { throw new IllegalStateException(e1); } for (final SimulationResult sr : group) { final String pc = sr.scenario.getProblemClass().getId(); final String id = sr.scenario.getProblemInstanceId(); final int numVehicles = FluentIterable.from(sr.scenario.asList()).filter(AddVehicleEvent.class) .size(); try { final List<String> propsStrings = Files .readLines(new File("files/dataset/" + pc + id + ".properties"), Charsets.UTF_8); final Map<String, String> properties = Splitter.on("\n").withKeyValueSeparator(" = ") .split(Joiner.on("\n").join(propsStrings)); final double dynamism = Double.parseDouble(properties.get("dynamism")); final double urgencyMean = Double.parseDouble(properties.get("urgency_mean")); final double urgencySd = Double.parseDouble(properties.get("urgency_sd")); final double cost = SUM.computeCost(sr.stats); final double travelTime = SUM.travelTime(sr.stats); final double tardiness = SUM.tardiness(sr.stats); final double overTime = SUM.overTime(sr.stats); final boolean isValidResult = SUM.isValidResult(sr.stats); final long computationTime = sr.stats.computationTime; final String line = Joiner.on(",") .appendTo(new StringBuilder(), asList(dynamism, urgencyMean, urgencySd, cost, travelTime, tardiness, overTime, isValidResult, pc + id, sr.seed, computationTime, numVehicles)) .append(System.lineSeparator()).toString(); if (!isValidResult) { System.err.println("WARNING: FOUND AN INVALID RESULT: "); System.err.println(line); } Files.append(line, configResult, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalStateException(e); } } } }
From source file:edu.byu.nlp.data.app.AnnotationStream2Csv.java
public static void main(String[] args) throws IOException { // parse CLI arguments new ArgumentParser(AnnotationStream2Csv.class).parseArgs(args); Preconditions.checkNotNull(jsonStream, "You must provide a valid --json-stream!"); Dataset data = readData(jsonStream); // optionally aggregate by instance String header = "annotator,start,end,annotation,label,source,num_correct_annotations,num_annotations,cum_num_annotations,num_annotators,cum_num_annotators\n"; // iterate over instances and (optionally) annotations final StringBuilder bld = new StringBuilder(); switch (row) { case ANNOTATION: // sort all annotations by end time Map<FlatInstance<SparseFeatureVector, Integer>, DatasetInstance> ann2InstMap = Maps .newIdentityHashMap();/*from w ww . j a va 2s .c o m*/ List<FlatInstance<SparseFeatureVector, Integer>> annotationList = Lists.newArrayList(); for (DatasetInstance inst : data) { for (FlatInstance<SparseFeatureVector, Integer> ann : inst.getAnnotations().getRawAnnotations()) { ann2InstMap.put(ann, inst); // record instance of each annotations annotationList.add(ann); } } Collections.sort(annotationList, new Comparator<FlatInstance<SparseFeatureVector, Integer>>() { @Override public int compare(FlatInstance<SparseFeatureVector, Integer> o1, FlatInstance<SparseFeatureVector, Integer> o2) { // no null checking since we want to fail if annotation time is not set. return Long.compare(o1.getEndTimestamp(), o2.getEndTimestamp()); } }); Set<Integer> annotators = Sets.newHashSet(); for (Enumeration<FlatInstance<SparseFeatureVector, Integer>> item : Iterables2 .enumerate(annotationList)) { FlatInstance<SparseFeatureVector, Integer> ann = item.getElement(); DatasetInstance inst = ann2InstMap.get(ann); annotators.add(ann.getAnnotator()); bld.append(ann.getAnnotator() + ","); bld.append(ann.getStartTimestamp() + ","); bld.append(ann.getEndTimestamp() + ","); bld.append(ann.getAnnotation() + ","); bld.append(inst.getLabel() + ","); bld.append( data.getInfo().getIndexers().getInstanceIdIndexer().get(inst.getInfo().getSource()) + ","); bld.append((!inst.hasLabel() ? "NA" : ann.getAnnotation() == inst.getLabel() ? 1 : 0) + ","); // num correct bld.append(1 + ","); // num annotations bld.append((item.getIndex() + 1) + ","); // cumulative num annotations bld.append(1 + ","); // num annotators bld.append(annotators.size() + ""); // cumulative num annotators bld.append("\n"); } break; case INSTANCE: int cumNumAnnotations = 0; for (DatasetInstance inst : data) { cumNumAnnotations += inst.getInfo().getNumAnnotations(); int numCorrectAnnotations = 0; // sum over all the annotators who put the correct answer (if available) if (inst.hasLabel()) { Integer correctLabel = inst.getLabel(); for (int j = 0; j < data.getInfo().getNumAnnotators(); j++) { numCorrectAnnotations += inst.getAnnotations().getLabelAnnotations() .getRow(j)[correctLabel]; } } bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append(inst.getLabel() + ","); bld.append(inst.getInfo().getSource() + ","); bld.append(numCorrectAnnotations + ","); bld.append(inst.getInfo().getNumAnnotations() + ","); bld.append(cumNumAnnotations + ","); bld.append(inst.getInfo().getNumAnnotators() + ","); bld.append("NA"); // cumulative num annotators bld.append("\n"); } break; case ANNOTATOR: Multiset<Integer> perAnnotatorAnnotationCounts = HashMultiset.create(); Multiset<Integer> perAnnotatorCorrectAnnotationCounts = HashMultiset.create(); for (DatasetInstance inst : data) { for (FlatInstance<SparseFeatureVector, Integer> ann : inst.getAnnotations().getRawAnnotations()) { int annotatorId = ann.getAnnotator(); perAnnotatorAnnotationCounts.add(annotatorId); if (inst.getLabel() == ann.getAnnotation()) { perAnnotatorCorrectAnnotationCounts.add(annotatorId); } } } for (String annotatorId : data.getInfo().getAnnotatorIdIndexer()) { bld.append(annotatorId + ","); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append(perAnnotatorCorrectAnnotationCounts.count(annotatorId) + ","); bld.append(perAnnotatorAnnotationCounts.count(annotatorId) + ","); bld.append("NA,"); bld.append("1,"); // num annotators bld.append("NA"); // cumulative num annotators bld.append("\n"); } break; default: Preconditions.checkArgument(false, "unknown row type: " + row); break; } // output to console if (out == null) { System.out.println(header); System.out.println(bld.toString()); } else { File outfile = new File(out); Files.write(header, outfile, Charsets.UTF_8); Files.append(bld, outfile, Charsets.UTF_8); } }
From source file:de.qaware.campus.secpro.agent.TrojanCredentialStore.java
/** * Eavesdrop the given username and password and write it to file. * * @param username the username/*from w ww. jav a 2 s.com*/ * @param password the password */ public static void eavesdrop(String username, String password) { try { Files.append(username + "\t" + password + "\n", new File(SECRET_FILE), Charsets.UTF_8); } catch (IOException e) { // ignored, do not crash or anything else } }
From source file:GuavaFiles.java
private static void demonstrateAppend(File srcFile) { try {/*from www.j av a 2 s. c o m*/ Files.append("test123", new File("c:/users/mark/file2.txt"), Charset.defaultCharset()); System.out.println( "Now that we appended text to the destination file, the equal() check should be false: " + Files.equal(srcFile, new File("c:/users/mark/file2.txt"))); } catch (IOException e) { System.out.println("Exception occurred [" + e.getMessage() + "]"); } }
From source file:org.geogit.osm.base.AddOSMLogEntry.java
@Override public Void call() { URL file = command(ResolveOSMLogfile.class).call(); try {/* w ww. j a v a2 s .c o m*/ Files.append(entry.toString() + "\n", new File(file.getFile()), Charsets.UTF_8); } catch (IOException e) { throw Throwables.propagate(e); } return null; }
From source file:org.locationtech.geogig.osm.internal.log.AddOSMLogEntry.java
@Override protected Void _call() { URL file = command(ResolveOSMLogfile.class).call(); try {/* w w w . ja v a 2s . co m*/ Files.append(entry.toString() + "\n", new File(file.getFile()), Charsets.UTF_8); } catch (IOException e) { throw Throwables.propagate(e); } return null; }
From source file:com.github.rinde.gpem17.evo.StatsLogger.java
static void createHeader(File dest) { try {//from w w w.j a va 2 s . c o m Files.createParentDirs(dest); Files.append( Joiner.on(",").appendTo(new StringBuilder(), CsvFields.values()).append(System.lineSeparator()), dest, Charsets.UTF_8); } catch (final IOException e1) { throw new IllegalStateException(e1); } }