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

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

Introduction

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

Prototype

public static String toString(File file, Charset charset) throws IOException 

Source Link

Usage

From source file:org.bonitasoft.studio.designer.core.repository.JSONFileStore.java

protected JSONObject toJSONObject(final IFile jsonFile) throws ReadFileStoreException {
    try {// www. j av  a 2  s  .  c o  m
        return new org.json.JSONObject(Files.toString(jsonFile.getLocation().toFile(), Charsets.UTF_8));
    } catch (JSONException | IOException e) {
        throw new ReadFileStoreException(
                String.format("Failed to retrieve JSON content from %s", jsonFile.getName()), e);
    }
}

From source file:com.continuuity.test.input.ExampleReader.java

private <V extends NamedEntity> Map<String, V> getType(String pathName, Class<V> typeClass) throws Exception {
    Map<String, V> result = Maps.newHashMap();
    File pathFile = new File(pathName);
    File[] files = pathFile.listFiles();
    for (File file : files) {
        try {/*from   w  ww  .  ja  v a 2 s.  c  o m*/
            String json = Files.toString(file, Charsets.UTF_8);
            V value = gson.fromJson(json, typeClass);
            result.put(value.getName(), value);
        } catch (IOException e) {
            LOG.error("{} can't open.", file.getName());
        } catch (JsonSyntaxException e) {
            LOG.error("Got exception while parsing JSON: ", e);
        }
    }
    return result;
}

From source file:com.google.javascript.refactoring.RefasterJsScanner.java

/**
 * Loads the RefasterJs template. This must be called before the scanner is used.
 *//*w  ww  .  j  av a2s.  c  o  m*/
public void loadRefasterJsTemplate(String refasterjsTemplate) throws IOException {
    Preconditions.checkState(templateJs == null,
            "Can't load RefasterJs template since a template is already loaded.");
    this.templateJs = Thread.currentThread().getContextClassLoader().getResource(refasterjsTemplate) != null
            ? Resources.toString(Resources.getResource(refasterjsTemplate), UTF_8)
            : Files.toString(new File(refasterjsTemplate), UTF_8);
}

From source file:info.servertools.teleport.TeleportManager.java

private static void loadTeleportFile() {

    if (!teleportSaveFile.exists()) {
        ServerToolsTeleport.log.log(Level.TRACE, "Teleport save file doesn't exist, skipping it");
        return;//from   www  .  j a  v a 2s.  c  o m
    }

    teleportMap.clear();

    synchronized (lock) {
        try {
            String data = Files.toString(teleportSaveFile, Reference.CHARSET);
            Type type = new TypeToken<Map<String, Location>>() {
            }.getType();

            Map<String, Location> map = gson.fromJson(data, type);

            if (map != null)
                teleportMap = map;

        } catch (JsonParseException e) {
            ServerToolsTeleport.log.warn(String.format(
                    "The teleport file %s could not be parsed as valid JSON, it will not be loaded",
                    teleportSaveFile.getAbsolutePath()), e);
        } catch (FileNotFoundException e) {
            ServerToolsTeleport.log.warn(
                    String.format("Tried to load non-existant file: %s", teleportSaveFile.getAbsolutePath()),
                    e);
        } catch (IOException e) {
            ServerToolsTeleport.log.warn(String.format("Failed to close buffered reader stream for: %s",
                    teleportSaveFile.getAbsolutePath()), e);
        }
    }
}

From source file:com.google.cloud.genomics.examples.TransformNonVariantSegmentData.java

public static void main(String[] args) throws IOException, GeneralSecurityException {
    // Register the options so that they show up via --help.
    PipelineOptionsFactory.register(TransformNonVariantSegmentData.Options.class);
    TransformNonVariantSegmentData.Options options = PipelineOptionsFactory.fromArgs(args).withValidation()
            .as(TransformNonVariantSegmentData.Options.class);

    // Option validation is not yet automatic, we make an explicit call here.
    GenomicsDatasetOptions.Methods.validateOptions(options);
    Preconditions.checkState(options.getHasNonVariantSegments(),
            "This job is only valid for data containing non-variant segments. "
                    + "Set the --hasNonVariantSegments command line option accordingly.");

    // Grab and parse our optional list of genomes to skip.
    ImmutableSet<String> callSetNamesToExclude = null;
    String skipFilepath = options.getCallSetNamesToExclude();
    if (null != skipFilepath) {
        Iterable<String> callSetNames = Splitter.on(CharMatcher.BREAKING_WHITESPACE).omitEmptyStrings()
                .trimResults().split(Files.toString(new File(skipFilepath), Charset.defaultCharset()));
        callSetNamesToExclude = ImmutableSet.<String>builder().addAll(callSetNames).build();
        LOG.info("The pipeline will skip " + callSetNamesToExclude.size() + " genomes with callSetNames: "
                + callSetNamesToExclude);
    }/*from   ww  w .  j  a va2s .  c  o m*/

    GenomicsFactory.OfflineAuth auth = GenomicsOptions.Methods.getGenomicsAuth(options);
    List<SearchVariantsRequest> requests = GenomicsDatasetOptions.Methods.getVariantRequests(options, auth,
            SexChromosomeFilter.INCLUDE_XY);

    Pipeline p = Pipeline.create(options);
    DataflowWorkarounds.registerGenomicsCoders(p);

    PCollection<SearchVariantsRequest> input = p.begin().apply(Create.of(requests));

    // Create a collection of data with non-variant segments omitted but calls from overlapping
    // non-variant segments added to SNPs.
    PCollection<Variant> variants = JoinNonVariantSegmentsWithVariants.joinVariantsTransform(input, auth);

    // For each variant flag whether or not it has ambiguous calls for a particular sample and
    // optionally filter calls.
    PCollection<Variant> flaggedVariants = callSetNamesToExclude == null
            ? variants.apply(ParDo.of(new FlagVariantsWithAmbiguousCallsFn()))
            : variants.apply(ParDo.of(new FilterCallsFn(callSetNamesToExclude)))
                    .apply(ParDo.of(new FlagVariantsWithAmbiguousCallsFn()));

    // Emit the variants to BigQuery.
    flaggedVariants.apply(ParDo.of(new FormatVariantsFn()))
            .apply(BigQueryIO.Write.to(options.getOutputTable()).withSchema(getTableSchema())
                    .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
                    .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE));

    p.run();
}

From source file:com.google.devtools.javatools.transform.SourceTransformer.java

/**
 * Applies source transform {@literal task}s to each file in {@literal paths}, writing output
 * files for each one according to the {@literal outputFileFunction}.
 *
 * @throws IOException if a filesystem error occurs
 * @throws JavaParseException if source failed to parse
 *//*from  w  ww.  j a v a  2 s.  c o m*/
public void transform(Iterable<String> paths) throws IOException {
    for (String path : paths) {
        String fileContent = Files.toString(new File(path), Charsets.UTF_8);
        for (SourceTransformTask task : tasks) {
            CompilationUnitTree tree = parse(fileContent);
            fileContent = task.transform(tree, fileContent);
        }

        File outFile = new File(outputFileFunction.apply(path));
        Files.createParentDirs(outFile);
        Files.write(fileContent, outFile, Charsets.UTF_8);
    }
}

From source file:org.yes.cart.installer.ApacheTomcat7Configurer.java

private void configureSSL() throws IOException {
    if (sslKeyStoreFile == null) {
        return;//  w  w  w. ja va2  s.  c om
    }
    File serverXMLFile = new File(tomcatHome, "conf" + File.separator + "server.xml");
    Files.write(Files.toString(serverXMLFile, Charset.forName("UTF-8"))
            .replace("        <Connector port=\"8009\" protocol=\"AJP/1.3\" redirectPort=\"8443\" />",
                    "        <Connector port=\"8009\" protocol=\"AJP/1.3\" redirectPort=\"8443\" />\n"
                            + "        <Connector port=\"" + httpsPort
                            + "\" protocol=\"HTTP/1.1\" SSLEnabled=\"true\"\n"
                            + "               maxThreads=\"150\" scheme=\"https\" secure=\"true\"\n"
                            + "               clientAuth=\"false\" sslProtocol=\"TLS\"\n"
                            + "               keystoreFile=\"" + sslKeyStoreFile + "\" " + "keystorePass=\""
                            + Strings.nullToEmpty(sslKeyStorePassword) + "\" />")
            .replace("8443", Integer.toString(httpsPort)), serverXMLFile, Charset.forName("UTF-8"));
}

From source file:org.sonar.jproperties.checks.EndLineCharactersCheck.java

private boolean fileContainsIllegalEndLineCharacters() {
    try {//from  w ww . j  a  v  a 2s .c om
        String fileContent = Files.toString(getContext().getFile(), charset);
        return "CR".equals(endLineCharacters) && Pattern.compile("(?s)\n").matcher(fileContent).find()
                || "LF".equals(endLineCharacters) && Pattern.compile("(?s)\r").matcher(fileContent).find()
                || "CRLF".equals(endLineCharacters)
                        && Pattern.compile("(?s)(\r(?!\n)|(?<!\r)\n)").matcher(fileContent).find();
    } catch (IOException e) {
        throw new IllegalStateException("Check jproperties:" + this.getClass().getAnnotation(Rule.class).key()
                + ": File cannot be read.", e);
    }
}

From source file:com.google.testing.pogen.MeasureCommand.java

@Override
public void execute() throws IOException {
    int sumAllVariableCount = 0, sumVariableWithIdCount = 0;
    for (String templatePath : templatePaths) {
        TemplateParser templateParser = TemplateParsers.getPreferredParser(templatePath, attributeName);
        File templateFile = createFileFromFilePath(templatePath);
        checkExistenceAndPermission(templateFile, true, false);
        String template = Files.toString(templateFile, Charset.defaultCharset());
        try {//from  ww w .  j  a va2  s  . c  o m
            VariableCoverage result = VariableCoverageMeasurer.measure(templateParser.parse(template));
            sumAllVariableCount += result.getAllVariableCount();
            sumVariableWithIdCount += result.getVariableWithIdCount();
            if (verbose) {
                System.out.format("%.2f%% : %s", result.getCoverage() * 100, templateFile.getAbsolutePath());
            }
        } catch (TemplateParseException e) {
            throw new FileProcessException("Errors occur in parsing the specified file", templateFile, e);
        }
    }
    if (sumAllVariableCount > 0) {
        System.out.format("Summary: %.2f%% (%d / %d)",
                (double) sumVariableWithIdCount / sumAllVariableCount * 100, sumVariableWithIdCount,
                sumAllVariableCount);
    } else {
        System.out.println("Summary: no template variables were found.");
    }
}

From source file:io.divolte.server.recordmapping.DslRecordMapper.java

public DslRecordMapper(final ValidatedConfiguration vc, final String groovyFile, final Schema schema,
        final Optional<LookupService> geoipService) {
    this.schema = Objects.requireNonNull(schema);

    logger.info("Using mapping from script file: {}", groovyFile);

    try {/*  ww w  .j  av  a  2s .  c om*/
        final DslRecordMapping mapping = new DslRecordMapping(schema, new UserAgentParserAndCache(vc),
                geoipService);

        final String groovyScript = Files.toString(new File(groovyFile), StandardCharsets.UTF_8);

        final CompilerConfiguration compilerConfig = new CompilerConfiguration();
        compilerConfig.setScriptBaseClass("io.divolte.groovyscript.MappingBase");

        final Binding binding = new Binding();
        binding.setProperty("mapping", mapping);

        final GroovyShell shell = new GroovyShell(binding, compilerConfig);
        final Script script = shell.parse(groovyScript);

        script.run();

        actions = mapping.actions();
    } catch (IOException e) {
        throw new RuntimeException("Could not load mapping script file: " + groovyFile, e);
    }
}