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.ProjectConfigTestUtils.java

public static String noAudienceProjectConfigJson() throws IOException {
    return Resources.toString(Resources.getResource("config/no-audience-project-config.json"), Charsets.UTF_8);
}

From source file:io.soabase.admin.details.IndexServlet.java

private void doReplacements(ComponentManager componentManager, Map<String, Entry> files) throws IOException {
    int currentYear = Calendar.getInstance().get(Calendar.YEAR);

    String firstId = "";
    StringBuilder tabsBuilder = new StringBuilder();
    StringBuilder idsBuilder = new StringBuilder();
    StringBuilder cssBuilder = new StringBuilder();
    StringBuilder jsBuilder = new StringBuilder();
    StringBuilder tabContentBuilder = new StringBuilder();
    StringBuilder metricsBuilder = new StringBuilder();

    for (TabComponent tab : componentManager.getTabs()) {
        if (firstId.length() == 0) {
            firstId = tab.getId();/*from  w  ww.j  a  v  a2 s. c  om*/
        }

        String id = SOA_TAB_PREFIX + tab.getId();
        tabsBuilder.append("<li id='").append(id).append("-li").append("'><a href=\"#").append(tab.getId())
                .append("\">").append(tab.getName()).append("</a></li>\n");
        idsBuilder.append("soaTabIds.push('").append(id).append("');\n");

        for (String cssFile : tab.getCssUris()) {
            cssBuilder.append("<link rel=\"stylesheet\" href=\"").append(cssFile).append("\">\n");
        }
        for (String jssFile : tab.getJavascriptUris()) {
            jsBuilder.append("<script src=\"").append(jssFile).append("\"></script>\n");
        }

        String tabContent = Resources.toString(Resources.getResource(tab.getContentResourcePath()),
                Charsets.UTF_8);
        tabContentBuilder.append("<div class=\"soa-hidden\" id=\"" + SOA_TAB_PREFIX).append(tab.getId())
                .append("\">").append(tabContent).append("</div>\n");
    }

    for (MetricComponent metric : componentManager.getMetrics()) {
        String obj = mapper.writeValueAsString(metric);
        metricsBuilder.append("vmMetrics.push(").append(obj).append(");\n");
    }

    String tabs = tabsBuilder.toString();
    String metrics = metricsBuilder.toString();
    String tabContent = tabContentBuilder.toString();
    String ids = idsBuilder.toString();
    String css = cssBuilder.toString();
    String js = jsBuilder.toString();

    for (Mapping mapping : mappings) {
        Entry entry = files.get(mapping.key);
        String content = entry.content;

        content = content.replace("$SOA_TABS$", tabs);
        content = content.replace("$SOA_TABS_CONTENT$", tabContent);
        content = content.replace("$SOA_METRICS$", metrics);
        content = content.replace("$SOA_DEFAULT_TAB_ID$", firstId);
        content = content.replace("$SOA_TAB_IDS$", ids);
        content = content.replace("$SOA_CSS$", css);
        content = content.replace("$SOA_JS$", js);
        content = content.replace("$SOA_NAME$", componentManager.getAppName());
        content = content.replace("$SOA_COPYRIGHT$",
                "" + currentYear + " " + componentManager.getCompanyName());
        content = content.replace("$SOA_FOOTER_MESSAGE$", "" + componentManager.getFooterMessage());

        String eTag = '"' + Hashing.murmur3_128().hashBytes(content.getBytes()).toString() + '"';
        files.put(mapping.key, new Entry(content, eTag));
    }
}

From source file:org.apache.drill.exec.store.StoragePluginRegistryImpl.java

private Map<String, StoragePlugin> createPlugins() throws DrillbitStartupException {
    try {//from  w  w  w . jav  a  2  s  .c  om
        /*
         * Check if the storage plugins system table has any entries. If not, load the boostrap-storage-plugin file into
         * the system table.
         */
        if (!pluginSystemTable.getAll().hasNext()) {
            // bootstrap load the config since no plugins are stored.
            logger.info(
                    "No storage plugin instances configured in persistent store, loading bootstrap configuration.");
            Collection<URL> urls = ClassPathScanner.forResource(ExecConstants.BOOTSTRAP_STORAGE_PLUGINS_FILE,
                    false);
            if (urls != null && !urls.isEmpty()) {
                logger.info("Loading the storage plugin configs from URLs {}.", urls);
                Map<String, URL> pluginURLMap = Maps.newHashMap();
                for (URL url : urls) {
                    String pluginsData = Resources.toString(url, Charsets.UTF_8);
                    StoragePlugins plugins = lpPersistence.getMapper().readValue(pluginsData,
                            StoragePlugins.class);
                    for (Map.Entry<String, StoragePluginConfig> config : plugins) {
                        if (!pluginSystemTable.putIfAbsent(config.getKey(), config.getValue())) {
                            logger.warn(
                                    "Duplicate plugin instance '{}' defined in [{}, {}], ignoring the later one.",
                                    config.getKey(), pluginURLMap.get(config.getKey()), url);
                            continue;
                        }
                        pluginURLMap.put(config.getKey(), url);
                    }
                }
            } else {
                throw new IOException("Failure finding " + ExecConstants.BOOTSTRAP_STORAGE_PLUGINS_FILE);
            }
        }

        Map<String, StoragePlugin> activePlugins = new HashMap<String, StoragePlugin>();
        for (Map.Entry<String, StoragePluginConfig> entry : Lists.newArrayList(pluginSystemTable.getAll())) {
            String name = entry.getKey();
            StoragePluginConfig config = entry.getValue();
            if (config.isEnabled()) {
                try {
                    StoragePlugin plugin = create(name, config);
                    activePlugins.put(name, plugin);
                } catch (ExecutionSetupException e) {
                    logger.error("Failure while setting up StoragePlugin with name: '{}', disabling.", name, e);
                    config.setEnabled(false);
                    pluginSystemTable.put(name, config);
                }
            }
        }

        activePlugins.put(INFORMATION_SCHEMA_PLUGIN,
                new InfoSchemaStoragePlugin(new InfoSchemaConfig(), context, INFORMATION_SCHEMA_PLUGIN));
        activePlugins.put(SYS_PLUGIN,
                new SystemTablePlugin(SystemTablePluginConfig.INSTANCE, context, SYS_PLUGIN));

        return activePlugins;
    } catch (IOException e) {
        logger.error("Failure setting up storage plugins.  Drillbit exiting.", e);
        throw new IllegalStateException(e);
    }
}

From source file:org.eclipse.che.commons.test.db.PersistTestModuleBuilder.java

/**
 * Creates or overrides META-INF/persistence.xml.
 *///from  w  w w  .ja va2 s . c o  m
public Path savePersistenceXml() throws IOException, URISyntaxException {
    Path persistenceXmlPath = getOrCreateMetaInf().resolve("persistence.xml");
    URL url = Thread.currentThread().getContextClassLoader()
            .getResource(PERSISTENCE_XML_TEMPLATE_RESOURCE_PATH);
    if (url == null) {
        throw new IOException("Resource '" + PERSISTENCE_XML_TEMPLATE_RESOURCE_PATH + "' doesn't exist");
    }
    ST st = new ST(Resources.toString(url, UTF_8), '$', '$');
    if (persistenceUnit != null) {
        st.add("unit", persistenceUnit);
    }
    if (!entityFqnSet.isEmpty()) {
        st.add("entity_classes", entityFqnSet);
    }
    if (!properties.isEmpty()) {
        st.add("properties", properties);
    }
    Files.write(persistenceXmlPath, st.render().getBytes(UTF_8));
    return persistenceXmlPath;
}

From source file:org.mayocat.theme.internal.DefaultThemeFileResolver.java

/**
 * Tries to get template content for a certain theme and breakpoint. Tries in order : - tenant theme folder in
 * persistent directory (example : data/tenants/thetenant/themes/thetheme/[breakpoint/]filename - global theme
 * folder in persistent directory (example : data/themes/thetheme/[breakpoint/]filename) - classpath (example uri :
 * /themes/thetheme/[breakpoint/]filename) For each step, checks the breakpoint (if set) and fallback on the
 * no-breakpoint file/* w  w  w. j a  v a2s .  co m*/
 *
 * @param theme the theme for which to try and get the template content
 * @param name the name of the template to get
 * @param breakpoint the breakpoint for which to get the template content
 * @return the content of the template, or null if not found
 * @throws IOException when there is an IO exception getting the content
 */
private String getTemplateContent(Theme theme, String name, Optional<Breakpoint> breakpoint)
        throws IOException {
    ThemeResource resource = this.getResource(theme, name, breakpoint);
    if (resource == null) {
        return null;
    }

    switch (resource.getType()) {
    default:
    case FILE:
        return Files.toString(resource.getPath().toFile(), Charsets.UTF_8);
    case CLASSPATH_RESOURCE:
        return Resources.toString(Resources.getResource(resource.getPath().toString()), Charsets.UTF_8);
    }
}

From source file:org.apache.zeppelin.submarine.commons.SubmarineUI.java

public void printCommnadUI(SubmarineCommand submarineCmd) {
    try {/*w w w.  j a va 2  s  . c  o  m*/
        HashMap<String, Object> mapParams = new HashMap();
        mapParams.put(unifyKey(SubmarineConstants.PARAGRAPH_ID), intpContext.getParagraphId());

        URL urlTemplate = Resources.getResource(SUBMARINE_DASHBOARD_JINJA);
        String template = Resources.toString(urlTemplate, Charsets.UTF_8);
        Jinjava jinjava = new Jinjava();
        String submarineUsage = jinjava.render(template, mapParams);

        InterpreterResultMessageOutput outputUI = intpContext.out.getOutputAt(0);
        outputUI.clear();
        outputUI.write(submarineUsage);
        outputUI.flush();

        // UI update, log needs to be cleaned at the same time
        InterpreterResultMessageOutput outputLOG = intpContext.out.getOutputAt(1);
        outputLOG.clear();
        outputLOG.flush();
    } catch (IOException e) {
        LOGGER.error("Can't print usage", e);
    }
}

From source file:high.mackenzie.autumn.lang.compiler.args.Visitor.java

/**
 * {@inheritDoc}//  w  ww . j a v  a 2  s  .  c o  m
 */
@Override
public void visit_case_version(final ITreeNode node) {
    final URL url = Resources.getResource(Main.class, VERSION);

    try {
        System.out.println(Resources.toString(url, Charset.defaultCharset()));
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        return;
    }
}

From source file:org.dspace.statistics.ElasticSearchLoggerServiceImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    log.info("DSpace ElasticSearchLogger Initializing");
    try {//w  w  w  .j  a  va  2  s  .c  om
        LookupService service = null;
        // Get the db file for the location
        String dbfile = ConfigurationManager.getProperty("usage-statistics", "dbfile");
        if (dbfile != null) {
            try {
                service = new LookupService(dbfile, LookupService.GEOIP_STANDARD);
            } catch (FileNotFoundException fe) {
                log.error("The GeoLite Database file is missing (" + dbfile
                        + ")! Usage Statistics cannot generate location based reports! Please see the DSpace installation instructions for instructions to install this file.",
                        fe);
            } catch (IOException e) {
                log.error("Unable to load GeoLite Database file (" + dbfile
                        + ")! You may need to reinstall it. See the DSpace installation instructions for more details.",
                        e);
            }
        } else {
            log.error("The required 'dbfile' configuration is missing in usage-statistics.cfg!");
        }
        locationService = service;

        if ("true".equals(ConfigurationManager.getProperty("useProxies"))) {
            useProxies = true;
        } else {
            useProxies = false;
        }

        log.info("useProxies=" + useProxies);

        // Configurable values for all elasticsearch connection constants
        clusterName = getConfigurationStringWithFallBack("elastic-search-statistics", "clusterName",
                clusterName);
        indexName = getConfigurationStringWithFallBack("elastic-search-statistics", "indexName", indexName);
        indexType = getConfigurationStringWithFallBack("elastic-search-statistics", "indexType", indexType);
        address = getConfigurationStringWithFallBack("elastic-search-statistics", "address", address);
        port = ConfigurationManager.getIntProperty("elastic-search-statistics", "port", port);

        //Initialize the connection to Elastic Search, and ensure our index is available.
        client = getClient();
        boolean hasIndex = false;
        try {
            log.info("Checking Elastic Search cluster health...");
            ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(indexName)
                    .setWaitForYellowStatus().setTimeout(TimeValue.timeValueSeconds(30)).execute().actionGet();

            if (healthResponse.isTimedOut() || healthResponse.getStatus() == ClusterHealthStatus.RED) {
                throw new IllegalStateException(
                        "cluster not ready due to health: " + healthResponse.toString());
            }

            log.info("DS ES Checking if index exists");
            hasIndex = client.admin().indices().prepareExists(indexName).execute().actionGet().isExists();
        } catch (Exception e) {
            log.error(
                    "Exception during health check, likely have to create index and put mapping still. Exception:"
                            + e.getMessage());
            hasIndex = false;
        }

        if (!hasIndex) {
            //If elastic search index exists, then we are good to go, otherwise, we need to create that index. Should only need to happen once ever.
            log.info("DS ES index didn't exist, we need to create it.");

            String mappingPath = ElasticSearchLoggerServiceImpl.class.getPackage().getName().replaceAll("\\.",
                    "/");
            URL url = Resources.getResource(mappingPath + "/elasticsearch-statistics-mapping.json");
            String stringMappingJSON = Resources.toString(url, Charsets.UTF_8);
            stringMappingJSON = stringMappingJSON.replace("stats", indexType);

            //Necessary to post, in order for index/type to be created.
            client.prepareIndex(indexName, indexType, "1")
                    .setSource(XContentFactory.jsonBuilder().startObject().field("user", "kimchy")
                            .field("postDate", new Date()).field("message", "trying out Elastic Search")
                            .endObject())
                    .execute().actionGet();

            log.info("Create INDEX [" + indexName + "]/[" + indexType + "]");

            // Wait for create to be finished.
            client.admin().indices().prepareRefresh(indexName).execute().actionGet();

            //Put the schema/mapping
            log.info("Put Mapping for [" + indexName + "]/[" + indexType + "]=" + stringMappingJSON);
            PutMappingRequestBuilder putMappingRequestBuilder = client.admin().indices()
                    .preparePutMapping(indexName).setType(indexType);
            putMappingRequestBuilder.setSource(stringMappingJSON);
            PutMappingResponse response = putMappingRequestBuilder.execute().actionGet();

            if (!response.isAcknowledged()) {
                log.info("Could not define mapping for type [" + indexName + "]/[" + indexType + "]");
            } else {
                log.info("Successfully put mapping for [" + indexName + "]/[" + indexType + "]");
            }

            log.info("DS ES index didn't exist, but we created it.");
        } else {
            log.info("DS ES index already exists");
        }

        log.info("DSpace ElasticSearchLogger Initialized Successfully (I suppose)");

    } catch (Exception e) {
        log.error("Elastic Search crashed during init. " + e.getMessage(), e);
    }
}

From source file:org.dspace.statistics.ElasticSearchLogger.java

public void initializeElasticSearch() {
    log.info("DSpace ElasticSearchLogger Initializing");
    try {/*from  w  ww .ja  v a  2 s .  com*/
        LookupService service = null;
        // Get the db file for the location
        String dbfile = ConfigurationManager.getProperty("usage-statistics", "dbfile");
        if (dbfile != null) {
            try {
                service = new LookupService(dbfile, LookupService.GEOIP_STANDARD);
            } catch (FileNotFoundException fe) {
                log.error("The GeoLite Database file is missing (" + dbfile
                        + ")! Usage Statistics cannot generate location based reports! Please see the DSpace installation instructions for instructions to install this file.",
                        fe);
            } catch (IOException e) {
                log.error("Unable to load GeoLite Database file (" + dbfile
                        + ")! You may need to reinstall it. See the DSpace installation instructions for more details.",
                        e);
            }
        } else {
            log.error("The required 'dbfile' configuration is missing in usage-statistics.cfg!");
        }
        locationService = service;

        if ("true".equals(ConfigurationManager.getProperty("useProxies"))) {
            useProxies = true;
        } else {
            useProxies = false;
        }

        log.info("useProxies=" + useProxies);

        // Configurable values for all elasticsearch connection constants
        clusterName = getConfigurationStringWithFallBack("elastic-search-statistics", "clusterName",
                clusterName);
        indexName = getConfigurationStringWithFallBack("elastic-search-statistics", "indexName", indexName);
        indexType = getConfigurationStringWithFallBack("elastic-search-statistics", "indexType", indexType);
        address = getConfigurationStringWithFallBack("elastic-search-statistics", "address", address);
        port = ConfigurationManager.getIntProperty("elastic-search-statistics", "port", port);

        //Initialize the connection to Elastic Search, and ensure our index is available.
        client = getClient();
        boolean hasIndex = false;
        try {
            log.info("Checking Elastic Search cluster health...");
            ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth(indexName)
                    .setWaitForYellowStatus().setTimeout(TimeValue.timeValueSeconds(30)).execute().actionGet();

            if (healthResponse.isTimedOut() || healthResponse.getStatus() == ClusterHealthStatus.RED) {
                throw new IllegalStateException(
                        "cluster not ready due to health: " + healthResponse.toString());
            }

            log.info("DS ES Checking if index exists");
            hasIndex = client.admin().indices().prepareExists(indexName).execute().actionGet().isExists();
        } catch (Exception e) {
            log.error(
                    "Exception during health check, likely have to create index and put mapping still. Exception:"
                            + e.getMessage());
            hasIndex = false;
        }

        if (!hasIndex) {
            //If elastic search index exists, then we are good to go, otherwise, we need to create that index. Should only need to happen once ever.
            log.info("DS ES index didn't exist, we need to create it.");

            String mappingPath = ElasticSearchLogger.class.getPackage().getName().replaceAll("\\.", "/");
            URL url = Resources.getResource(mappingPath + "/elasticsearch-statistics-mapping.json");
            String stringMappingJSON = Resources.toString(url, Charsets.UTF_8);
            stringMappingJSON = stringMappingJSON.replace("stats", indexType);

            //Necessary to post, in order for index/type to be created.
            client.prepareIndex(indexName, indexType, "1")
                    .setSource(XContentFactory.jsonBuilder().startObject().field("user", "kimchy")
                            .field("postDate", new Date()).field("message", "trying out Elastic Search")
                            .endObject())
                    .execute().actionGet();

            log.info("Create INDEX [" + indexName + "]/[" + indexType + "]");

            // Wait for create to be finished.
            client.admin().indices().prepareRefresh(indexName).execute().actionGet();

            //Put the schema/mapping
            log.info("Put Mapping for [" + indexName + "]/[" + indexType + "]=" + stringMappingJSON);
            PutMappingRequestBuilder putMappingRequestBuilder = client.admin().indices()
                    .preparePutMapping(indexName).setType(indexType);
            putMappingRequestBuilder.setSource(stringMappingJSON);
            PutMappingResponse response = putMappingRequestBuilder.execute().actionGet();

            if (!response.isAcknowledged()) {
                log.info("Could not define mapping for type [" + indexName + "]/[" + indexType + "]");
            } else {
                log.info("Successfully put mapping for [" + indexName + "]/[" + indexType + "]");
            }

            log.info("DS ES index didn't exist, but we created it.");
        } else {
            log.info("DS ES index already exists");
        }

        log.info("DSpace ElasticSearchLogger Initialized Successfully (I suppose)");

    } catch (Exception e) {
        log.error("Elastic Search crashed during init. " + e.getMessage(), e);
    }
}

From source file:high.mackenzie.autumn.lang.compiler.args.Visitor.java

/**
 * {@inheritDoc}//  w  ww . ja va2s  .  com
 */
@Override
public void visit_case_license(final ITreeNode node) {
    final URL url = Resources.getResource(Main.class, LICENSE);

    try {
        System.out.println(Resources.toString(url, Charset.defaultCharset()));
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        return;
    }
}