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

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

Introduction

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

Prototype

public static String toString(URL url, Charset charset) throws IOException 

Source Link

Document

Reads all characters from a URL into a String , using the given character set.

Usage

From source file:com.optimizely.ab.config.DatafileProjectConfigTestUtils.java

/**
 * @return the expected {@link DatafileProjectConfig} for the json produced by {@link #invalidProjectConfigV5()}
 *//*from   w  ww  . j  a v  a2  s. c  o  m*/
public static String invalidProjectConfigV5() throws IOException {
    return Resources.toString(Resources.getResource("config/invalid-project-config-v5.json"), Charsets.UTF_8);
}

From source file:uk.os.vt.mbtiles.StorageImpl.java

private synchronized Flowable<VectorTileConfig> queryConfigFlowable() {
    final URL url = Resources.getResource("metadata_raw.sql");
    String query;/*from  ww w  .ja va  2 s.c o m*/
    try {
        query = Resources.toString(url, Charsets.UTF_8);
    } catch (final IOException ex) {
        return Flowable.error(ex);
    }
    return dataSource.select(query)
            .get(rs -> new VectorTileConfig(rs.getInt("min_zoom"), rs.getInt("max_zoom"),
                    rs.getInt("max_zoom_minx"), rs.getInt("max_zoom_miny"), rs.getInt("max_zoom_maxx"),
                    rs.getInt("max_zoom_maxy")));
}

From source file:org.dswarm.graph.resources.MaintainResource.java

private void initPrefixes(final GraphDatabaseService database) throws DMPGraphException {

    MaintainResource.LOG.debug("start initialising namespaces index");

    final TransactionHandler tx = new Neo4jTransactionHandler(database);
    final NamespaceIndex namespaceIndex = new NamespaceIndex(database, tx);

    tx.ensureRunningTx();//w w w  .java 2 s . c  o m

    try {

        final URL prefixesFileURL = Resources.getResource("prefixes.json");
        final String prefixesJSONString = Resources.toString(prefixesFileURL, Charsets.UTF_8);
        final Map<String, String> prefixesNamespacesMap = simpleObjectMapper.readValue(prefixesJSONString,
                new TypeReference<HashMap<String, String>>() {

                });

        for (final Map.Entry<String, String> entry : prefixesNamespacesMap.entrySet()) {

            final String prefix = entry.getKey();
            final String namespace = entry.getValue();

            final Optional<Node> optionalPrefix = NamespaceUtils.getPrefix(namespace, database);

            if (!optionalPrefix.isPresent()) {

                namespaceIndex.addPrefix(namespace, prefix);
            } else {

                final String prefixFromDB = (String) optionalPrefix.get()
                        .getProperty(GraphProcessingStatics.PREFIX_PROPERTY);

                MaintainResource.LOG.debug(
                        "prefix '{}' is already available for namespace '{}', i.e., no further entry with prefix '{}' will be created",
                        prefixFromDB, namespace, prefix);
            }
        }

        tx.succeedTx();
    } catch (final Exception e) {

        tx.failTx();

        final String message = "couldn't initialize prefixes successfully";

        LOG.error(message);

        throw new DMPGraphException(message, e);
    }

    MaintainResource.LOG.debug("finished initialising namespaces index");
}

From source file:com.spotify.helios.agent.AgentService.java

private void logBanner() {
    try {//  www. ja v  a2 s .  co  m
        final String banner = Resources.toString(Resources.getResource("agent-banner.txt"), UTF_8);
        log.info("\n{}", banner);
    } catch (IllegalArgumentException | IOException ignored) {
    }
}

From source file:org.voltdb.compilereport.ReportMaker.java

/**
 * Generate the HTML catalog report from a newly compiled VoltDB catalog
 *///from   w w w. ja va2  s.  c o m
public static String report(Catalog catalog) throws IOException {
    // asyncronously get platform properties
    new Thread() {
        @Override
        public void run() {
            PlatformProperties.getPlatformProperties();
        }
    }.start();

    URL url = Resources.getResource(ReportMaker.class, "template.html");
    String contents = Resources.toString(url, Charsets.UTF_8);

    Cluster cluster = catalog.getClusters().get("cluster");
    assert (cluster != null);
    Database db = cluster.getDatabases().get("database");
    assert (db != null);

    String statsData = getStatsHTML(db);
    contents = contents.replace("##STATS##", statsData);

    String schemaData = generateSchemaTable(db.getTables());
    contents = contents.replace("##SCHEMA##", schemaData);

    String procData = generateProceduresTable(db.getProcedures());
    contents = contents.replace("##PROCS##", procData);

    String platformData = PlatformProperties.getPlatformProperties().toHTML();
    contents = contents.replace("##PLATFORM##", platformData);

    contents = contents.replace("##VERSION##", VoltDB.instance().getVersionString());

    DateFormat df = new SimpleDateFormat("d MMM yyyy HH:mm:ss z");
    contents = contents.replace("##TIMESTAMP##", df.format(m_timestamp));

    String msg = Encoder.hexEncode(VoltDB.instance().getVersionString() + "," + System.currentTimeMillis());
    contents = contents.replace("get.py?a=KEY&", String.format("get.py?a=%s&", msg));

    return contents;
}

From source file:com.facebook.buck.apple.ProjectGenerator.java

private String getBuildWithBuckShellScript(TargetNode<?> targetNode) {
    ST template;//from w  w  w . ja v a 2s  .  c o m
    try {
        template = new ST(Resources.toString(
                Resources.getResource(ProjectGenerator.class, BUILD_WITH_BUCK_TEMPLATE), Charsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException("There was an error loading '" + BUILD_WITH_BUCK_TEMPLATE + "' template", e);
    }

    String buildFlags = getBuildFlags();
    String escapedBuildTarget = Escaper.escapeAsBashString(targetNode.getBuildTarget().getFullyQualifiedName());
    if (attemptToDetermineBestCxxPlatform) {
        escapedBuildTarget += XCODE_BUILD_SCRIPT_FLAVOR_VALUE;
    }

    template.add("repo_root", projectFilesystem.getRootPath());
    template.add("path_to_buck", getPathToBuck(executableFinder, environment));
    template.add("build_flags", buildFlags);
    template.add("escaped_build_target", escapedBuildTarget);

    return template.render();
}

From source file:org.rakam.client.builder.document.SlateDocumentGenerator.java

private Map<OperationIdentifier, Map<String, String>> generateExampleUsages() throws IOException {
    Map<OperationIdentifier, Map<String, String>> templates = Maps.newHashMap();

    Map<String, Entry<CodegenConfig, DefaultGenerator>> languages = new HashMap<>();

    for (CodegenConfigurator configurator : configurators) {
        ClientOptInput clientOptInput = configurator.toClientOptInput();
        clientOptInput.getConfig().processOpts();

        DefaultGenerator defaultGenerator = new DefaultGenerator();
        defaultGenerator.opts(clientOptInput);

        if (!supportedLanguages.contains(configurator.getLang())) {
            throw new IllegalArgumentException(
                    format("Language %s is not supported at the moment.", configurator.getLang()));
        }/*from  w  w w . ja  v  a2s .com*/

        languages.put(configurator.getLang(),
                new AbstractMap.SimpleImmutableEntry<>(clientOptInput.getConfig(), defaultGenerator));

        if (swagger == null) {
            swagger = clientOptInput.getSwagger();
        }
    }

    for (Entry<String, Entry<CodegenConfig, DefaultGenerator>> entry : languages.entrySet()) {
        String language = entry.getKey();
        Entry<CodegenConfig, DefaultGenerator> value = entry.getValue();

        Map<String, List<CodegenOperation>> operations = value.getValue().processPaths(swagger.getPaths());
        for (String parentTag : operations.keySet()) {
            List<CodegenOperation> ops = operations.get(parentTag);
            for (CodegenOperation op : ops) {
                Map<String, Object> operation = value.getValue().processOperations(value.getKey(), parentTag,
                        ImmutableList.of(op));

                operation.put("modelPackage", value.getKey().modelPackage());
                operation.put("classname", value.getKey().toApiName(parentTag));
                operation.put("hostname", swagger.getHost());

                for (String templateName : value.getKey().apiTemplateFiles().keySet()) {
                    String filename = value.getKey().apiFilename(templateName, parentTag);
                    if (!value.getKey().shouldOverwrite(filename) && new File(filename).exists()) {
                        continue;
                    }

                    String template;
                    URL resource = this.getClass().getClassLoader()
                            .getResource("templates/" + language + "_api_example.mustache");

                    template = Resources.toString(resource, StandardCharsets.UTF_8);

                    Template tmpl = Mustache.compiler()
                            .withLoader(name -> value.getValue().getTemplateReader(
                                    value.getKey().templateDir() + File.separator + name + ".mustache"))
                            .defaultValue("").compile(template);

                    templates.computeIfAbsent(new OperationIdentifier(op.path, op.httpMethod),
                            key -> Maps.newHashMap()).put(language, tmpl.execute(operation));
                }
            }
        }
    }

    return templates;
}

From source file:com.facebook.buck.apple.ProjectGenerator.java

private String getFixUUIDShellScript(TargetNode<?> targetNode) {
    ST template;//www  .  j  av  a 2  s .c o  m
    try {
        template = new ST(Resources.toString(Resources.getResource(ProjectGenerator.class, FIX_UUID_TEMPLATE),
                Charsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException("There was an error loading '" + FIX_UUID_TEMPLATE + "' template", e);
    }

    ImmutableSet<Flavor> flavors = ImmutableSet.copyOf(targetNode.getBuildTarget().getFlavors());
    CxxPlatform cxxPlatform = cxxPlatforms.getValue(flavors).or(defaultCxxPlatform);
    String compDir = cxxPlatform.getDebugPathSanitizer().getCompilationDirectory();
    // Use the hostname for padding instead of the directory, this way the directory matches without
    // having to resolve it.
    String sourceDir = Strings.padStart(":" + projectFilesystem.getRootPath().toString(), compDir.length(),
            'f');

    Optional<String> productName = getProductNameForTargetNode(targetNode);
    String binaryName = AppleBundle.getBinaryName(targetToBuildWithBuck.get(), productName);
    Path bundleDestination = getScratchPathForAppBundle(targetToBuildWithBuck.get(), binaryName);
    Path dsymDestination = getScratchPathForDsymBundle(targetToBuildWithBuck.get(), binaryName);
    Path resolvedBundleDestination = projectFilesystem.resolve(bundleDestination);
    Path resolvedDsymDestination = projectFilesystem.resolve(dsymDestination);
    Path fixUUIDScriptPath = getFixUUIDScriptPath(projectFilesystem);

    if (attemptToDetermineBestCxxPlatform) {
        template.add("buck_flavor", XCODE_BUILD_SCRIPT_FLAVOR_VALUE);
    } else {
        template.add("buck_flavor", "");
    }
    template.add("path_to_buck", getPathToBuck(executableFinder, environment));
    template.add("buck_target", targetToBuildWithBuck.get().getFullyQualifiedName());
    template.add("root_path", projectFilesystem.getRootPath());

    template.add("comp_dir", compDir);
    template.add("source_dir", sourceDir);

    template.add("resolved_bundle_destination", resolvedBundleDestination);
    template.add("resolved_bundle_destination_parent", resolvedBundleDestination.getParent());
    template.add("resolved_dsym_destination", resolvedDsymDestination);
    template.add("binary_name", binaryName);
    template.add("path_to_fix_uuid_script", fixUUIDScriptPath);

    return template.render();
}

From source file:com.facebook.buck.apple.project_generator.ProjectGenerator.java

private String getBuildWithBuckShellScript(TargetNode<?, ?> targetNode) {
    ST template;//from   w ww.j  av  a  2 s .com
    try {
        template = new ST(Resources.toString(
                Resources.getResource(ProjectGenerator.class, BUILD_WITH_BUCK_TEMPLATE), Charsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException("There was an error loading '" + BUILD_WITH_BUCK_TEMPLATE + "' template", e);
    }

    String buildFlags = getBuildFlags();
    String escapedBuildTarget = Escaper.escapeAsBashString(targetNode.getBuildTarget().getFullyQualifiedName());

    Optional<String> productName = getProductNameForTargetNode(targetNode);
    String binaryName = AppleBundle.getBinaryName(targetNode.getBuildTarget(), productName);
    Path bundleDestination = getScratchPathForAppBundle(projectFilesystem, targetNode.getBuildTarget(),
            binaryName);
    Path dsymDestination = getScratchPathForDsymBundle(projectFilesystem, targetNode.getBuildTarget(),
            binaryName);
    Path resolvedBundleDestination = projectFilesystem.resolve(bundleDestination);
    Path resolvedDsymDestination = projectFilesystem.resolve(dsymDestination);

    ImmutableSet<Flavor> flavors = ImmutableSet.copyOf(targetNode.getBuildTarget().getFlavors());
    CxxPlatform cxxPlatform = cxxPlatforms.getValue(flavors).orElse(defaultCxxPlatform);
    String oldCompDir = cxxPlatform.getCompilerDebugPathSanitizer().getCompilationDirectory();
    // Use the hostname for padding instead of the directory, this way the directory matches without
    // having to resolve it.
    String dsymPaddedCompDirWithHost = Strings.padStart(":" + projectFilesystem.getRootPath().toString(),
            oldCompDir.length(), 'f');

    template.add("path_to_build_with_buck_py", getBuildWithBuckPythonScriptPath(projectFilesystem));
    template.add("path_to_fix_uuid_script", getFixUUIDScriptPath(projectFilesystem));
    template.add("repo_root", projectFilesystem.getRootPath());
    template.add("path_to_buck", getPathToBuck(executableFinder, environment));
    template.add("build_flags", buildFlags);
    template.add("escaped_build_target", escapedBuildTarget);
    template.add("buck_dwarf_flavor",
            (appleConfig.forceDsymModeInBuildWithBuck() ? AppleDebugFormat.DWARF_AND_DSYM
                    : AppleDebugFormat.DWARF).getFlavor().getName());
    template.add("buck_dsym_flavor", AppleDebugFormat.DWARF_AND_DSYM.getFlavor().getName());
    template.add("binary_name", binaryName);
    template.add("comp_dir", oldCompDir);
    template.add("new_comp_dir", projectFilesystem.getRootPath().toString());
    template.add("padded_source_dir", dsymPaddedCompDirWithHost);
    template.add("resolved_bundle_destination", resolvedBundleDestination);
    template.add("resolved_bundle_destination_parent", resolvedBundleDestination.getParent());
    template.add("resolved_dsym_destination", resolvedDsymDestination);
    template.add("force_dsym", appleConfig.forceDsymModeInBuildWithBuck() ? "true" : "false");

    return template.render();
}

From source file:com.facebook.buck.apple.NewNativeTargetProjectMutator.java

private String generateXcodeShellScript(TargetNode<?> targetNode) {
    Preconditions.checkArgument(targetNode.getConstructorArg() instanceof ReactNativeLibraryArgs);

    ST template;//from  w  w w  . j av a 2s.c o  m
    try {
        template = new ST(Resources.toString(
                Resources.getResource(NewNativeTargetProjectMutator.class, REACT_NATIVE_PACKAGE_TEMPLATE),
                Charsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException("There was an error loading 'rn_package.st' template", e);
    }

    ReactNativeLibraryArgs args = (ReactNativeLibraryArgs) targetNode.getConstructorArg();

    template.add("bundle_name", args.bundleName);
    template.add("skip_rn_bundle", skipRNBundle);

    ProjectFilesystem filesystem = targetNode.getRuleFactoryParams().getProjectFilesystem();
    BuildTarget buildTarget = targetNode.getBuildTarget();
    Path jsOutput = ReactNativeBundle.getPathToJSBundleDir(buildTarget).resolve(args.bundleName);
    template.add("built_bundle_path", filesystem.resolve(jsOutput));

    Path resourceOutput = ReactNativeBundle.getPathToResources(buildTarget);
    template.add("built_resources_path", filesystem.resolve(resourceOutput));

    Path sourceMap = ReactNativeBundle.getPathToSourceMap(buildTarget);
    template.add("built_source_map_path", filesystem.resolve(sourceMap));

    return template.render();
}