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.blackbear.flatworm.config.ScriptletBO.java

/**
 * Set the script file to use where the script to evaluate identity matching is kept.
 *
 * @param scriptFile The script file path (this will be loaded via the classloader.
 * @throws FlatwormConfigurationException should the file not be found, fail to be read, or contain invalid script accordingly the
 *                                        script engine specified.
 *//*from w  w w  .  ja  v a2  s.  com*/
public void setScriptFile(String scriptFile) throws FlatwormConfigurationException {
    this.scriptFile = scriptFile;
    try {
        URL url = Resources.getResource(scriptFile);
        String scriptContents = Resources.toString(url, Charsets.UTF_8);
        setScript(scriptContents);
    } catch (IOException e) {
        throw new FlatwormConfigurationException("Failed to load scriptFile: " + scriptFile, e);
    }
}

From source file:org.eclipse.xtext.xtext.wizard.ParentProjectDescriptor.java

private CharSequence loadResource(final String resourcePath) {
    try {/* w ww .ja  v  a2 s  .  c  om*/
        return Resources.toString(this.getClass().getClassLoader().getResource(resourcePath),
                Charsets.ISO_8859_1);
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:org.thingsboard.server.service.component.AnnotationComponentDiscoveryService.java

private List<ComponentDescriptor> persist(Set<BeanDefinition> filterDefs, ComponentType type) {
    List<ComponentDescriptor> result = new ArrayList<>();
    for (BeanDefinition def : filterDefs) {
        ComponentDescriptor scannedComponent = new ComponentDescriptor();
        String clazzName = def.getBeanClassName();
        try {//  ww  w .  java  2 s  .c o m
            scannedComponent.setType(type);
            Class<?> clazz = Class.forName(clazzName);
            String descriptorResourceName;
            switch (type) {
            case FILTER:
                Filter filterAnnotation = clazz.getAnnotation(Filter.class);
                scannedComponent.setName(filterAnnotation.name());
                scannedComponent.setScope(filterAnnotation.scope());
                descriptorResourceName = filterAnnotation.descriptor();
                break;
            case PROCESSOR:
                Processor processorAnnotation = clazz.getAnnotation(Processor.class);
                scannedComponent.setName(processorAnnotation.name());
                scannedComponent.setScope(processorAnnotation.scope());
                descriptorResourceName = processorAnnotation.descriptor();
                break;
            case ACTION:
                Action actionAnnotation = clazz.getAnnotation(Action.class);
                scannedComponent.setName(actionAnnotation.name());
                scannedComponent.setScope(actionAnnotation.scope());
                descriptorResourceName = actionAnnotation.descriptor();
                break;
            case PLUGIN:
                Plugin pluginAnnotation = clazz.getAnnotation(Plugin.class);
                scannedComponent.setName(pluginAnnotation.name());
                scannedComponent.setScope(pluginAnnotation.scope());
                descriptorResourceName = pluginAnnotation.descriptor();
                for (Class<?> actionClazz : pluginAnnotation.actions()) {
                    ComponentDescriptor actionComponent = getComponent(actionClazz.getName())
                            .orElseThrow(() -> {
                                log.error("Can't initialize plugin {}, due to missing action {}!",
                                        def.getBeanClassName(), actionClazz.getName());
                                return new ClassNotFoundException(
                                        "Action: " + actionClazz.getName() + "is missing!");
                            });
                    if (actionComponent.getType() != ComponentType.ACTION) {
                        log.error("Plugin {} action {} has wrong component type!", def.getBeanClassName(),
                                actionClazz.getName(), actionComponent.getType());
                        throw new RuntimeException("Plugin " + def.getBeanClassName() + "action "
                                + actionClazz.getName() + " has wrong component type!");
                    }
                }
                scannedComponent.setActions(Arrays.stream(pluginAnnotation.actions())
                        .map(action -> action.getName()).collect(Collectors.joining(",")));
                break;
            default:
                throw new RuntimeException(type + " is not supported yet!");
            }
            scannedComponent.setConfigurationDescriptor(mapper.readTree(
                    Resources.toString(Resources.getResource(descriptorResourceName), Charsets.UTF_8)));
            scannedComponent.setClazz(clazzName);
            log.info("Processing scanned component: {}", scannedComponent);
        } catch (Exception e) {
            log.error("Can't initialize component {}, due to {}", def.getBeanClassName(), e.getMessage(), e);
            throw new RuntimeException(e);
        }
        ComponentDescriptor persistedComponent = componentDescriptorService.findByClazz(clazzName);
        if (persistedComponent == null) {
            log.info("Persisting new component: {}", scannedComponent);
            scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
        } else if (scannedComponent.equals(persistedComponent)) {
            log.info("Component is already persisted: {}", persistedComponent);
            scannedComponent = persistedComponent;
        } else {
            log.info("Component {} will be updated to {}", persistedComponent, scannedComponent);
            componentDescriptorService.deleteByClazz(persistedComponent.getClazz());
            scannedComponent.setId(persistedComponent.getId());
            scannedComponent = componentDescriptorService.saveComponent(scannedComponent);
        }
        result.add(scannedComponent);
    }
    return result;
}

From source file:co.cask.cdap.format.GrokRecordFormat.java

protected void addPattern(Grok grok, String resource) {
    URL url = this.getClass().getClassLoader().getResource(resource);
    if (url == null) {
        LOG.error("Resource '{}' for grok pattern was not found", resource);
        return;/*  w  w  w . jav  a  2s.  c  om*/
    }

    try {
        String patternFile = Resources.toString(url, Charsets.UTF_8);
        try {
            grok.addPatternFromReader(new StringReader(patternFile));
        } catch (GrokException e) {
            LOG.error("Invalid grok pattern from resource '{}'", resource, e);
        }
    } catch (IOException e) {
        LOG.error("Failed to load resource '{}' for grok pattern", resource, e);
    }
}

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

public void createLogHeadUI() {
    try {/*w w w.  ja  va2s .  c  o m*/
        HashMap<String, Object> mapParams = new HashMap();
        URL urlTemplate = Resources.getResource(SUBMARINE_LOG_HEAD_JINJA);
        String template = Resources.toString(urlTemplate, Charsets.UTF_8);
        Jinjava jinjava = new Jinjava();
        String submarineUsage = jinjava.render(template, mapParams);

        InterpreterResultMessageOutput outputUI = intpContext.out.getOutputAt(1);
        outputUI.clear();
        outputUI.write(submarineUsage);
        outputUI.flush();
    } catch (IOException e) {
        LOGGER.error("Can't print usage", e);
    }
}

From source file:org.sonatype.nexus.repository.search.SearchServiceImpl.java

private void createIndex(final Repository repository, final String indexName) {
    // TODO we should calculate the checksum of index settings and compare it with a value stored in index _meta tags
    // in case that they not match (settings changed) we should drop the index, recreate it and re-index all components
    IndicesAdminClient indices = indicesAdminClient();
    if (!indices.prepareExists(indexName).execute().actionGet().isExists()) {
        // determine list of mapping configuration urls
        List<URL> urls = Lists.newArrayListWithExpectedSize(indexSettingsContributors.size() + 1);
        urls.add(Resources.getResource(getClass(), MAPPING_JSON)); // core mapping
        for (IndexSettingsContributor contributor : indexSettingsContributors) {
            URL url = contributor.getIndexSettings(repository);
            if (url != null) {
                urls.add(url);// w  w  w. j  a va  2  s . c  om
            }
        }

        try {
            // merge all mapping configuration
            String source = "{}";
            for (URL url : urls) {
                log.debug("Merging ElasticSearch mapping: {}", url);
                String contributed = Resources.toString(url, Charsets.UTF_8);
                log.trace("Contributed ElasticSearch mapping: {}", contributed);
                source = JsonUtils.merge(source, contributed);
            }
            // update runtime configuration
            log.trace("ElasticSearch mapping: {}", source);
            indices.prepareCreate(indexName).setSource(source).execute().actionGet();
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    repositoryNameMapping.put(repository.getName(), indexName);
}

From source file:org.incode.module.document.fixture.seed.DocumentTypeAndTemplatesApplicableForDemoObjectFixture.java

private static String loadResource(final String resourceName) {
    final URL templateUrl = Resources.getResource(DocumentTypeAndTemplatesApplicableForDemoObjectFixture.class,
            resourceName);//from   www.j av a  2  s.  c  om
    try {
        return Resources.toString(templateUrl, Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException(String.format("Unable to read resource URL '%s'", templateUrl));
    }
}

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

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

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

public void printHelp() {
    final URL url = Resources.getResource(Main.class, HELP);

    try {/*from  ww w . ja v a2  s .  c o m*/
        System.out.println(Resources.toString(url, Charset.defaultCharset()));
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        return;
    }
}

From source file:kina.embedded.CassandraServer.java

private boolean doStart() throws IOException {
    File dir = Files.createTempDir();
    String dirPath = dir.getAbsolutePath();
    System.out.println("Storing Cassandra files in " + dirPath);

    URL url = Resources.getResource("cassandra.yaml");
    String yaml = Resources.toString(url, Charsets.UTF_8);
    yaml = yaml.replaceAll("REPLACEDIR", dirPath);
    String yamlPath = dirPath + File.separatorChar + "cassandra.yaml";
    org.apache.commons.io.FileUtils.writeStringToFile(new File(yamlPath), yaml);

    // make a tmp dir and copy cassandra.yaml and log4j.properties to it
    try {/*w  ww. ja v a  2s .  c  o m*/
        copy("/log4j.properties", dir.getAbsolutePath());
    } catch (Exception e1) {
        logger.error("Cannot copy log4j.properties");
    }
    System.setProperty("cassandra.config", "file:" + dirPath + yamlFilePath);
    //System.setProperty("log4j.configuration", "file:" + dirPath + "/log4j.xml");
    //System.setProperty("cassandra-foreground", "true");
    //System.setProperty("cassandra.skip_wait_for_gossip_to_settle", "1");
    System.setProperty("cassandra.boot_without_jna", "true");

    cleanupAndLeaveDirs();

    try {
        executor.execute(new CassandraRunner());
    } catch (RejectedExecutionException e) {
        logger.error(e);
        return true;
    }

    try {
        logger.info("Sleeping for " + WAIT_SECONDS);
        TimeUnit.SECONDS.sleep(WAIT_SECONDS);
    } catch (InterruptedException e) {
        logger.error(e);
        throw new AssertionError(e);
    }

    initKeySpace();
    return false;
}