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:org.apache.drill.exec.store.StoragePluginRegistry.java

private Map<String, StoragePlugin> createPlugins() throws DrillbitStartupException {
    try {/*  w w  w .j  a v  a 2  s .  com*/
        /*
         * Check if the storage plugins system table has any entries.  If not, load the boostrap-storage-plugin file into the system table.
         */
        if (!pluginSystemTable.iterator().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 = PathScanner.forResource(ExecConstants.BOOTSTRAP_STORAGE_PLUGINS_FILE, false,
                    Resources.class.getClassLoader());
            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 = context.getConfig().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 : pluginSystemTable) {
            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:com.google.api.tools.framework.importers.swagger.MultiSwaggerParser.java

/**
 * Validates the input Swagger JsonNode against Swagger Specification schema.
 *
 * @throws SwaggerConversionException// w  ww.  j  a  va  2  s.c o m
 */
private static void validateSwaggerSpec(JsonNode swaggerJsonNode) throws SwaggerConversionException {
    ProcessingReport report = null;
    try {
        URL url = Resources.getResource(SCHEMA_RESOURCE_PATH);
        String swaggerSchema = Resources.toString(url, StandardCharsets.UTF_8);
        JsonNode schemaNode = Yaml.mapper().readTree(swaggerSchema);
        JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode);
        report = schema.validate(swaggerJsonNode);
    } catch (Exception ex) {
        throw new SwaggerConversionException("Unable to parse the content. " + ex.getMessage(), ex);
    }
    if (!report.isSuccess()) {
        String message = "";
        Iterator itr = report.iterator();
        if (itr.hasNext()) {
            message += ((ProcessingMessage) itr.next()).toString();
        }
        while (itr.hasNext()) {
            message += "," + ((ProcessingMessage) itr.next()).toString();
        }
        throw new SwaggerConversionException(
                String.format("Invalid Swagger spec. Please fix the schema errors:\n%s", message));
    }
}

From source file:org.openqa.selenium.remote.http.W3CHttpCommandCodec.java

private Map<String, ?> executeAtom(String atomFileName, Object... args) {
    try {/*www  .  j a v a2s .  c  om*/
        String scriptName = "/org/openqa/selenium/remote/" + atomFileName;
        URL url = getClass().getResource(scriptName);

        String rawFunction = Resources.toString(url, Charsets.UTF_8);
        String script = String.format("return (%s).apply(null, arguments);", rawFunction);
        return toScript(script, args);
    } catch (IOException | NullPointerException e) {
        throw new WebDriverException(e);
    }
}

From source file:org.mayocat.shop.front.views.WebViewMessageBodyWriter.java

private void writeHttpError(String message, OutputStream entityStream) {
    try {/*from ww w.j  av  a 2 s .c om*/
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        Template error;
        Template masterTemplate = null;
        try {
            masterTemplate = themeFileResolver.getIndexTemplate(webContext.getRequest().getBreakpoint());
        } catch (TemplateNotFoundException e) {
            // Nothing doing
        }
        try {
            error = themeFileResolver.getTemplate("500.html", webContext.getRequest().getBreakpoint());
        } catch (TemplateNotFoundException notFound) {
            // Fallback on the classpath hosted error 500 file
            error = new Template("500",
                    Resources.toString(Resources.getResource("templates/500.html"), Charsets.UTF_8));
        }
        Map<String, Object> errorContext = Maps.newHashMap();
        errorContext.put("error", message);

        engine.get().register(error);

        String rendered;

        if (masterTemplate != null) {
            errorContext.put("templateContent", error.getId());
            errorContext.put("template", "500");
            engine.get().register(masterTemplate);
            rendered = engine.get().render(masterTemplate.getId(), mapper.writeValueAsString(errorContext));
        } else {
            rendered = engine.get().render(error.getId(), mapper.writeValueAsString(errorContext));
        }

        entityStream.write(rendered.getBytes());
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }
}

From source file:io.github.adessaigne.cameldemo.basic.common.AbstractExercise.java

/**
 * Creates and initializes the database.
 *
 * @return Database//from   w ww  .  ja  v a 2  s  .  c om
 * @throws SQLException
 * @throws IOException
 */
private JdbcConnectionPool createDatabase() throws SQLException, IOException {
    JdbcConnectionPool db = JdbcConnectionPool.create("jdbc:h2:mem:test", "sa", "sa");
    try (Connection connection = db.getConnection()) {
        try (Statement statement = connection.createStatement()) {
            statement.execute(Resources.toString(AbstractExercise.class.getResource("database.sql"), UTF_8));
        }
    }
    return db;
}

From source file:org.auraframework.util.javascript.directive.DirectiveBasedJavascriptGroup.java

protected void generateForMode(File destRoot, final JavascriptGeneratorMode mode) throws IOException {
    final File dest = new File(destRoot, getName() + "_" + mode.getSuffix() + ".js");
    if (dest.exists()) {
        if (dest.lastModified() < getLastMod()) {
            dest.delete();/*  w w w .j  ava 2 s  . c o m*/
        } else {
            // its up to date already, skip
            counter.countDown();
            return;
        }
    }
    dest.getParentFile().mkdirs();
    final String everything = buildContent(mode);
    final String threadName = THREAD_NAME + mode;
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Writer writer = null;
                try {
                    writer = new FileWriter(dest);
                    mode.getJavascriptWriter().compress(everything, writer, dest.getName());
                    writer.write('\n');
                    appendExternalLibraries(writer);
                } finally {
                    if (writer != null) {
                        writer.close();
                    }
                    dest.setReadOnly();
                }
            } catch (Throwable t) {
                // Store any problems, to be thrown in a composite runtime exception from the main thread.
                // Otherwise, they kill this worker thread but are basically ignored.
                errors.put(threadName, t);
            } finally {
                counter.countDown();
            }
        }

        private void appendExternalLibraries(Writer writer) throws IOException {
            ResourceLoader rl = getResourceLoader();
            String minified = "";
            if (mode.allowedInProduction()) {
                minified = ".min";
            }
            writer.write("\n Aura.externalLibraries = function() {\n");
            try {
                appendResourceToWriter(writer, "moment",
                        rl.getResource("aura/resources/moment/moment" + minified + ".js"));
                // 1999 is selected since it's when SFDC starts
                appendResourceToWriter(writer, "moment-timezone-with-data-1999-2020",
                        rl.getResource("aura/resources/moment-timezone/moment-timezone-with-data-1999-2020"
                                + minified + ".js"));
                appendResourceToWriter(writer, "DOMPurify",
                        rl.getResource("aura/resources/domPurify/DOMPurify" + minified + ".js"));
            } catch (Exception ignored) {
            }

            writer.write("\n};");
        }

        private void appendResourceToWriter(Writer writer, String name, URL url) throws IOException {
            writer.write("// " + name + "\n");
            writer.write(Resources.toString(url, Charsets.UTF_8));
            writer.write("\n");
        }

        private ResourceLoader getResourceLoader() throws IOException {
            if (resourceLoader == null) {
                resourceLoader = new ResourceLoader(LIB_CACHE_TEMP_DIR, true);
            }
            return resourceLoader;
        }
    }, threadName);
    t.start();
}

From source file:com.google.appinventor.buildserver.ProjectBuilder.java

private static Set<String> getAllComponentTypes() throws IOException {
    Set<String> compSet = Sets.newHashSet();
    String[] components = Resources
            .toString(ProjectBuilder.class.getResource(ALL_COMPONENT_TYPES), Charsets.UTF_8).split("\n");
    for (String component : components) {
        compSet.add(component);//from w  ww  .  j  ava 2s. co m
    }
    return compSet;
}

From source file:io.fabric8.service.jclouds.CloudContainerInstallationTask.java

/**
 * @return the IP address of the client on which this code is running.
 * @throws java.io.IOException//from  w  ww . j  av  a2  s . c o m
 */
private String getOriginatingIp() throws IOException {
    String ip = null;
    try {
        URL url = new URL("http://checkip.amazonaws.com/");
        ip = Resources.toString(url, Charsets.UTF_8).trim() + "/32";
    } catch (Throwable t) {
        LOGGER.warn("Failed to lookup public ip of current container.");
    }
    return ip;
}

From source file:com.palantir.typescript.services.language.LanguageService.java

private void addDefaultLibrary() {
    String libraryContents;//from  ww w .j a  va  2  s . co m
    try {
        libraryContents = Resources.toString(LanguageService.class.getResource("lib.d.ts"), Charsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    Request request = new Request(SERVICE, "addDefaultLibrary", libraryContents);
    this.bridge.call(request, Void.class);
}

From source file:org.northshore.cbri.sent.SentenceDetector_cTAKES.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {

    //------------------------------------------------------------------------------------------------------------
    // TODO: this is experimental code on injecting a Groovy script to determine
    // which Segments should be run through the sentence detector annotator.
    Collection<Segment> segs = null;
    try {//  w ww.  j  a  v a2 s. c om
        if (segmentsToParse != null) {
            CompilerConfiguration config = new CompilerConfiguration();
            config.setScriptBaseClass("org.northshore.cbri.dsl.UIMAUtil");
            ////Binding binding = new Binding();
            GroovyShell shell = new GroovyShell(config);

            System.out.println("GroovyAnnotator loading script file: " + this.segmentsToParse);
            URL url = Resources.getResource(this.segmentsToParse);
            String scriptContents = Resources.toString(url, Charsets.UTF_8);
            segs = (Collection<Segment>) shell.evaluate(scriptContents);
        } else {
            segs = JCasUtil.select(jcas, Segment.class);
        }
    } catch (CompilationFailedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //------------------------------------------------------------------------------------------------------------

    String text = jcas.getDocumentText();

    for (Segment seg : segs) {
        annotateRange(jcas, text, seg, 0);
    }
}