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

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

Introduction

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

Prototype

public static CharSink asCharSink(File to, Charset charset) 

Source Link

Usage

From source file:com.android.builder.core.DexProcessBuilder.java

@NonNull
private List<String> getFilesToAdd(@NonNull BuildToolInfo buildToolInfo) throws ProcessException {
    // remove non-existing files.
    Set<File> existingFiles = Sets.filter(mInputs, new Predicate<File>() {
        @Override//from w  w  w.  j  ava 2 s .  c  om
        public boolean apply(@Nullable File input) {
            return input != null && input.exists();
        }
    });

    if (existingFiles.isEmpty()) {
        throw new ProcessException("No files to pass to dex.");
    }

    // sort the inputs
    List<File> sortedList = Lists.newArrayList(existingFiles);
    Collections.sort(sortedList, new Comparator<File>() {
        @Override
        public int compare(File file, File file2) {
            boolean file2IsDir = file2.isDirectory();
            if (file.isDirectory()) {
                return file2IsDir ? 0 : -1;
            } else if (file2IsDir) {
                return 1;
            }

            long diff = file.length() - file2.length();
            return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
        }
    });

    // convert to String-based paths.
    List<String> filePathList = Lists.newArrayListWithCapacity(sortedList.size());
    for (File f : sortedList) {
        filePathList.add(f.getAbsolutePath());
    }

    if (mTempInputFolder != null
            && buildToolInfo.getRevision().compareTo(MIN_BUILD_TOOLS_REVISION_FOR_DEX_INPUT_LIST) >= 0) {
        File inputListFile = new File(mTempInputFolder, "inputList.txt");
        // Write each library line by line to file
        try {
            Files.asCharSink(inputListFile, Charsets.UTF_8).writeLines(filePathList);
        } catch (IOException e) {
            throw new ProcessException(e);
        }
        return Collections.singletonList("--input-list=" + inputListFile.getAbsolutePath());
    } else {
        return filePathList;
    }
}

From source file:it.sayservice.platform.smartplanner.utils.CacheGenerator.java

public void _testGeneratedTripsSchedule() throws IOException {
    String[] gtfs = { "12", "16", "10", "5", "6", "17" };
    java.util.Map<String, String> agencyPrefixMap = new java.util.HashMap<String, String>();
    agencyPrefixMap.put("12", "tt");
    agencyPrefixMap.put("16", "rv");
    agencyPrefixMap.put("10", "tm");
    agencyPrefixMap.put("5", "bv");
    agencyPrefixMap.put("6", "tb");
    agencyPrefixMap.put("17", "ext");
    String pathToGTFSZip = "C:\\deleted\\daily-work\\07.05.15\\otp-0.15\\trentino\\";
    String schedulesDir = System.getenv("OTP_HOME") + System.getProperty("file.separator") + "cache"
            + System.getProperty("file.separator") + "schedules" + System.getProperty("file.separator");
    String tripsDir = System.getenv("OTP_HOME") + System.getProperty("file.separator") + "cache"
            + System.getProperty("file.separator") + "trips" + System.getProperty("file.separator");
    String stopsDir = System.getenv("OTP_HOME") + System.getProperty("file.separator") + "cache"
            + System.getProperty("file.separator") + "stops" + System.getProperty("file.separator");
    File cacheSchedulesDir = new File(schedulesDir);
    cacheSchedulesDir.mkdir();/*from  ww  w  .ja  v a 2 s . com*/
    File cacheTripsDir = new File(tripsDir);
    cacheTripsDir.mkdir();
    File cacheStopsDir = new File(stopsDir);
    cacheStopsDir.mkdir();

    for (String gtfsName : gtfs) {
        // unzip the new GTFS file
        File newFolder = unzip(pathToGTFSZip + gtfsName + ".zip");

        // read/remove headers.
        File trips = new File(newFolder, "trips.txt");
        List<String> linesT = Files.asCharSource(trips, Charsets.UTF_8).readLines();
        File calendar = new File(newFolder, "calendar.txt");
        List<String> linesC = Files.asCharSource(calendar, Charsets.UTF_8).readLines();
        File calendarDates = new File(newFolder, "calendar_dates.txt");
        List<String> linesCD = Files.asCharSource(calendarDates, Charsets.UTF_8).readLines();
        File stopTimes = new File(newFolder, "stop_times.txt");
        List<String> linesStopTimes = Files.asCharSource(stopTimes, Charsets.UTF_8).readLines();
        File stops = new File(newFolder, "stops.txt");
        List<String> linesStop = Files.asCharSource(stops, Charsets.UTF_8).readLines();
        // create dir.
        File scheduleAgenecyDir = new File(schedulesDir, gtfsName);
        scheduleAgenecyDir.mkdir();
        // copy files to cache/schedule folder.
        File calfile = new File(scheduleAgenecyDir, "calendar.txt");
        Files.asCharSink(calfile, Charsets.UTF_8).writeLines(linesC.subList(1, linesC.size()));
        File caldatesfile = new File(scheduleAgenecyDir, "calendar_dates.txt");
        Files.asCharSink(caldatesfile, Charsets.UTF_8).writeLines(linesCD.subList(1, linesCD.size()));
        File stoptimesfile = new File(scheduleAgenecyDir, "stop_times.txt");
        Files.asCharSink(stoptimesfile, Charsets.UTF_8)
                .writeLines(linesStopTimes.subList(1, linesStopTimes.size()));
        File tripfile = new File(scheduleAgenecyDir, "trips.txt");
        Files.asCharSink(tripfile, Charsets.UTF_8).writeLines(linesT.subList(1, linesT.size()));
        // copy files to cache/trip folder.
        File tripsTripfile = new File(cacheTripsDir, "trips_" + agencyPrefixMap.get(gtfsName) + ".txt");
        Files.asCharSink(tripsTripfile, Charsets.UTF_8).writeLines(linesT.subList(1, linesT.size()));
        // copy files to cache/stop folder.
        File stopsStopfile = new File(cacheStopsDir, "stops_" + agencyPrefixMap.get(gtfsName) + ".txt");
        Files.asCharSink(stopsStopfile, Charsets.UTF_8).writeLines(linesStop.subList(1, linesStop.size()));
    }

}

From source file:org.glowroot.tests.WebDriverSetup.java

private static Container createContainer(int uiPort, File testDir) throws Exception {
    File adminFile = new File(testDir, "admin.json");
    Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}");
    Container container;//from ww  w  . j a v a 2 s  .  co  m
    if (Containers.useJavaagent()) {
        container = new JavaagentContainer(testDir, true, ImmutableList.of());
    } else {
        container = new LocalContainer(testDir, true, ImmutableMap.of());
    }
    // wait for UI to be available (UI starts asynchronously in order to not block startup)
    CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy())
            .build();
    Stopwatch stopwatch = Stopwatch.createStarted();
    Exception lastException = null;
    while (stopwatch.elapsed(SECONDS) < 10) {
        HttpGet request = new HttpGet("http://localhost:" + uiPort);
        try (CloseableHttpResponse response = httpClient.execute(request);
                InputStream content = response.getEntity().getContent()) {
            ByteStreams.exhaust(content);
            lastException = null;
            break;
        } catch (Exception e) {
            lastException = e;
        }
    }
    httpClient.close();
    if (lastException != null) {
        throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException);
    }
    return container;
}

From source file:works.chatterbox.chatterbox.api.impl.channel.DefaultChannelAPI.java

@Override
public void saveMemberships() {
    if (this.memberships == null)
        return;/*from ww w.  ja va 2 s  .  co m*/
    final File source = new File(this.chatterbox.getDataFolder(), "memberships.yml");
    if (!source.exists()) {
        try {
            Preconditions.checkState(source.createNewFile(), "Could not save memberships file");
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
    }
    final YAMLConfigurationLoader loader = YAMLConfigurationLoader.builder().setFile(source)
            .setSink(Files.asCharSink(source, StandardCharsets.UTF_8)).build();
    try {
        loader.save(this.memberships);
    } catch (final IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.gradle.plugin.devel.tasks.ValidateTaskProperties.java

private void storeResults(List<String> problemMessages, File outputFile) throws IOException {
    if (outputFile != null) {
        //noinspection ResultOfMethodCallIgnored
        outputFile.createNewFile();/*from w  w  w .  j  a  v a  2  s. c  o  m*/
        Files.asCharSink(outputFile, Charsets.UTF_8).write(Joiner.on('\n').join(problemMessages));
    }
}

From source file:com.google.api.tools.framework.model.testing.BaselineTestCase.java

/**
 * Creates a baseline file that will need to be used to make the current test pass.
 *
 * <p>If the test is failing for a valid reason (e.g. developer changed some of the output text),
 * then this file provides a convenient way for the developer to overwrite the old baseline
 * and keep the test passing./* w  w  w  .j  a  v  a2 s .  c om*/
 *
 *  <p>The created file is stored under /tmp or location specified by the environment
 *  variable DIRECTORY_TO_COPY_NEW_BASELINE. Information where the file is stored is returned
 *  as a string.
 *  <p>The directory structure of the package where the baseline file belongs can be retained by
 *  setting environment variable RETAIN_DIRECTORY_TREE_FOR_BASELINE_OUTPUT to true. If this
 *  variable is not set, the new baseline file is dropped inside a folder name
 *  {package name}_testdata
 *
 *  <p>This method might be overridden to provide a different way to store a new baseline.
 */
protected String tryCreateNewBaseline(String actual) throws IOException {
    File file = new File(File.separator + DIRECTORY_TO_COPY_NEW_BASELINE + File.separator
            + getSubDirectoryPathForNewBaseline() + File.separator + baselineFileName());
    Files.createParentDirs(file);
    Files.asCharSink(file, Charset.defaultCharset()).write(actual);
    return file.toString();
}

From source file:com.technophobia.substeps.glossary.SubstepsGlossaryMojo.java

private void writeOutputFile(String xml, String filename) {
    final File output = new File(outputDirectory, filename);

    if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
        throw new IllegalStateException("unable to create output directory");
    }//  ww  w. j  a v a  2  s .  c  o m

    try {

        Files.asCharSink(output, Charset.forName("UTF-8")).write(xml);

    } catch (final IOException e) {
        log.error("error writing file", e);
    }
}