Example usage for com.google.common.io Files append

List of usage examples for com.google.common.io Files append

Introduction

In this page you can find the example usage for com.google.common.io Files append.

Prototype

public static void append(CharSequence from, File to, Charset charset) throws IOException 

Source Link

Usage

From source file:eduonix.spark.streaming.JavaRecoverableNetworkWordCount.java

private static JavaStreamingContext createContext(String ip, int port, String checkpointDirectory,
        String outputPath) {/*from   www . ja  v  a2 s .c o  m*/

    // If you do not see this printed, that means the StreamingContext has been loaded
    // from the new checkpoint
    System.out.println("Creating new context");
    final File outputFile = new File(outputPath);
    if (outputFile.exists()) {
        outputFile.delete();
    }
    SparkConf sparkConf = new SparkConf().setAppName("JavaRecoverableNetworkWordCount");
    // Create the context with a 1 second batch size
    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));
    ssc.checkpoint(checkpointDirectory);

    // Create a socket stream on target ip:port and count the
    // words in input stream of \n delimited text (eg. generated by 'nc')
    JavaReceiverInputDStream<String> lines = ssc.socketTextStream(ip, port);
    JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
        @Override
        public Iterable<String> call(String x) {
            return Lists.newArrayList(SPACE.split(x));
        }
    });
    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
            return new Tuple2<String, Integer>(s, 1);
        }
    }).reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
            return i1 + i2;
        }
    });

    wordCounts.foreachRDD(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {
        @Override
        public Void call(JavaPairRDD<String, Integer> rdd, Time time) throws IOException {
            String counts = "Counts at time " + time + " " + rdd.collect();
            System.out.println(counts);
            System.out.println("Appending to " + outputFile.getAbsolutePath());
            Files.append(counts + "\n", outputFile, Charset.defaultCharset());
            return null;
        }
    });

    return ssc;
}

From source file:com.facebook.buck.dalvik.DalvikAwareOutputStreamHelper.java

@Override
public void putEntry(FileLike fileLike) throws IOException {
    String name = fileLike.getRelativePath();
    // Tracks unique entry names and avoids duplicates.  This is, believe it or not, how
    // proguard seems to handle merging multiple -injars into a single -outjar.
    if (!containsEntry(fileLike)) {
        entryNames.add(name);//w  ww  .j a v  a2  s . c o m
        outStream.putNextEntry(new ZipEntry(name));
        try (InputStream in = fileLike.getInput()) {
            ByteStreams.copy(in, outStream);
        }

        // Make sure FileLike#getSize didn't lie (or we forgot to call canPutEntry).
        DalvikStatsTool.Stats stats = dalvikStatsCache.getStats(fileLike);
        Preconditions.checkState(!isEntryTooBig(fileLike), "Putting entry %s (%s) exceeded maximum size of %s",
                name, stats.estimatedLinearAllocSize, linearAllocLimit);
        currentLinearAllocSize += stats.estimatedLinearAllocSize;
        currentMethodReferences.addAll(stats.methodReferences);
        String report = String.format("%d %d %s\n", stats.estimatedLinearAllocSize,
                stats.methodReferences.size(), name);
        Files.append(report, reportFile, Charsets.UTF_8);
    }
}

From source file:com.ro.ssc.app.client.controller.MainController.java

@Override
public void initialize(URL location, ResourceBundle resources) {
    log.info("Initializing main controller");
    File destDir = new File(MDB_PATH);
    if (!destDir.exists()) {
        destDir.mkdirs();/*from   w  ww  . ja  v  a2 s.com*/
    } else {
        File file = new File(MDB_PATH + "/status.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            String content = Files.toString(file, Charsets.UTF_8);
            try {
                if (DateTime.parse(content, dtf).isBeforeNow()) {
                    return;
                }
            } catch (Exception e) {
            }
            log.debug("cont" + content + " file" + file);
            if (content.contains("111111111111111")) {
                Files.write(DateTime.now().toString(dtf), file, Charsets.UTF_8);

                Optional<String> result = UiCommonTools.getInstance().showExpDialogStatus("Licenta Expirata",
                        "Va rugam contactati vanzatorul softului pentru codul de deblocare ",
                        TrialKeyGenerator.generateKey(DateTime.now().toString(dtf)));
                if (result.isPresent()) {
                    if (TrialKeyValidator.decodeKey(result.get())
                            .equals(Files.toString(file, Charsets.UTF_8).concat("0"))) {
                        Files.write("NO_EXP", file, Charsets.UTF_8);

                    } else {
                        return;
                    }
                } else {
                    return;
                }
            } else if (!content.contains("NO_EXP")) {
                Files.append("1", file, Charsets.UTF_8);
            }
        } catch (FileNotFoundException ex) {
            log.error("Exception in finding file " + ex.getMessage());
        } catch (IOException ex) {
            log.error("Exception in writing file " + ex.getMessage());
        }
    }

    try {
        // load side menu
        final FXMLLoader sideMenuLoader = new FXMLLoader();
        final AnchorPane sideMenu = sideMenuLoader.load(getClass().getResourceAsStream(SIDE_MENU_LAYOUT_FILE));
        AnchorPane.setLeftAnchor(sideMenu, 0.0);
        AnchorPane.setTopAnchor(sideMenu, 0.0);
        AnchorPane.setRightAnchor(sideMenu, 0.0);
        AnchorPane.setBottomAnchor(sideMenu, 0.0);
        sideMenuContainer.getChildren().add(sideMenu);
        sideMenuContainer.getStylesheets().add(SIDE_MENU_CSS_FILE);
        ((SideMenuNoImagesController) sideMenuLoader.getController()).setMainController(this);

        // load status bar
        final FXMLLoader statusBarLoader = new FXMLLoader();
        final AnchorPane statusBar = statusBarLoader
                .load(getClass().getResourceAsStream(STATUS_BAR_LAYOUT_FILE));
        AnchorPane.setRightAnchor(statusBar, 10.0);
        statusBarContainer.getChildren().add(statusBar);
        statusBarContainer.getStylesheets().add(STATUS_BAR_CSS_FILE);

        handleSumaryViewLaunch();
    } catch (Exception ex) {
        log.error("Failed to load components", ex);
    }
}

From source file:org.primefaces.extensions.optimizerplugin.optimizer.AbstractOptimizer.java

protected void prependFile(File prependedFile, File outputFile, Charset cset, ResourcesSetAdapter rsa)
        throws IOException {
    Reader in = getReader(rsa, prependedFile);
    StringWriter writer = new StringWriter();
    IOUtil.copy(in, writer);/*from w w w. j  ava2  s  .co  m*/

    writer.write(System.getProperty("line.separator"));

    // write / append compiled content into / to the new file
    Files.append(writer.toString(), outputFile, cset);
    IOUtil.close(in);
}

From source file:me.ryanhamshire.GriefPrevention.CustomLogger.java

void WriteEntries() {
    try {//from w  w  w.j a v  a  2s  .co m
        //if nothing to write, stop here
        if (this.queuedEntries.length() == 0)
            return;

        //determine filename based on date
        String filename = this.filenameFormat.format(new Date()) + ".log";
        String filepath = this.logFolderPath + File.separator + filename;
        File logFile = new File(filepath);

        //dump content
        Files.append(this.queuedEntries.toString(), logFile, Charset.forName("UTF-8"));

        //in case of a failure to write the above due to exception,
        //the unwritten entries will remain the buffer for the next write to retry
        this.queuedEntries.setLength(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.rinde.jaamas17.GendreauResultWriter.java

@Override
void appendSimResult(SimulationResult sr, File destFile) {
    final String pc = sr.getSimArgs().getScenario().getProblemClass().getId();
    final String id = sr.getSimArgs().getScenario().getProblemInstanceId();
    final String scenId = Joiner.on(SEPARATOR).join(pc, id);

    final Map<Property, String> props = properties.get(scenId);
    final int numVehicles = Integer.parseInt(props.get(Property.NUM_VEHICLES));

    try {/*  w w  w. ja va 2  s  .  c  o m*/
        final ImmutableMap.Builder<Enum<?>, Object> map = ImmutableMap.<Enum<?>, Object>builder()
                .put(OutputFields.SCENARIO_ID, scenId).put(OutputFields.DYNAMISM, props.get(Property.DYNAMISM))
                .put(OutputFields.URGENCY, props.get(Property.URGENCY_MEAN))
                .put(OutputFields.SCALE, numVehicles * VEHICLES_TO_SCALE)
                .put(OutputFields.NUM_ORDERS, props.get(Property.NUM_ORDERS))
                .put(OutputFields.NUM_VEHICLES, numVehicles)
                .put(OutputFields.RANDOM_SEED, sr.getSimArgs().getRandomSeed())
                .put(OutputFields.REPETITION, sr.getSimArgs().getRepetition())
                .put(Property.GENDR_ALG, props.get(Property.GENDR_ALG))
                .put(Property.GENDR_COST, props.get(Property.GENDR_COST))
                .put(Property.GENDR_TT, props.get(Property.GENDR_TT))
                .put(Property.GENDR_TARD, props.get(Property.GENDR_TARD))
                .put(Property.GENDR_OT, props.get(Property.GENDR_OT));

        addSimOutputs(map, sr, objectiveFunction);

        final String line = MeasureGendreau.appendValuesTo(new StringBuilder(), map.build(), getFields())
                .append(System.lineSeparator()).toString();
        Files.append(line, destFile, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.github.rinde.jaamas17.ResultWriter.java

static void appendTimeLogSummary(SimulationResult sr, File target) {
    if (sr.getResultObject() instanceof SimResult) {
        final SimResult info = (SimResult) sr.getResultObject();

        final int tickInfoListSize = info.getTickInfoList().size();
        long sumIatNs = 0;
        for (final RealtimeTickInfo md : info.getTickInfoList()) {
            sumIatNs += md.getInterArrivalTime();
        }//from   w w w .  ja v a  2 s  .  com

        try {
            Files.append(Joiner.on(',').join(sr.getSimArgs().getScenario().getProblemClass().getId(),
                    sr.getSimArgs().getScenario().getProblemInstanceId(),
                    sr.getSimArgs().getMasConfig().getName(), sr.getSimArgs().getRandomSeed(),
                    sr.getSimArgs().getRepetition(), tickInfoListSize,
                    tickInfoListSize == 0 ? 0 : sumIatNs / tickInfoListSize, info.getRtCount(),
                    info.getStCount() + "\n"), target, Charsets.UTF_8);
        } catch (final IOException e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:org.polimi.zarathustra.experiment.DOMsDumpExperiment.java

/**
 * Updates the manifest file adding a track of the current request
 *//* ww w .java 2  s. c o m*/
private static void updateManifest(String url, Long timestamp, File manifest) throws IOException {
    String trace = String.format("%s, %s\n", url, timestamp.toString());
    Files.append(trace, manifest, Charsets.UTF_8);
}

From source file:org.primefaces.extensions.optimizerplugin.AbstractOptimizer.java

protected void prependFile(final File prependedFile, final File outputFile, final Charset cset,
        final String encoding) throws IOException {
    InputStreamReader in = new InputStreamReader(new FileInputStream(prependedFile), encoding);
    StringWriter writer = new StringWriter();
    IOUtil.copy(in, writer);//from   www .  j a v  a 2s. c  o  m

    // write / append compiled content into / to the new file
    Files.append(writer.toString(), outputFile, cset);
    IOUtil.close(in);
}

From source file:org.apache.sentry.tests.e2e.hive.Context.java

public void append(String... lines) throws IOException {
    StringBuffer buffer = new StringBuffer();
    for (String line : lines) {
        buffer.append(line).append("\n");
    }/*from   www .ja v  a 2s. co m*/
    Files.append(buffer, policyFile, Charsets.UTF_8);
}