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.google.api.codegen.discovery.config.ruby.RubyTypeNameGenerator.java

@SuppressWarnings("unchecked")
private ImmutableMap<String, String> getMethodNameMap() throws IOException {
    String data = Resources.toString(Resources.getResource(RubyApiaryNameMap.class, "apiary_names.yaml"),
            StandardCharsets.UTF_8);
    // Unchecked cast here.
    return ImmutableMap.copyOf((Map<String, String>) (new Yaml().load(data)));
}

From source file:name.marcelomorales.siqisiqi.examples.simple.init.InitialData.java

@Inject
public InitialData(DataSource dataSource) throws SQLException, IOException {
    jdbcTemplate = new JdbcTemplate(dataSource);
    try (Connection c = dataSource.getConnection()) {
        URL resource = Resources.getResource("ddl.sql");
        String s = Resources.toString(resource, Charsets.US_ASCII);
        Iterable<String> split = Splitter.on(';').omitEmptyStrings().trimResults().split(s);
        for (String sql : split) {
            try (Statement st = c.createStatement()) {
                st.execute(sql);//from w  ww  .j  a va  2  s  .  c  o  m
            }
        }
        c.commit(); // this is needed because we don't use @TransactionAttribute
    }
}

From source file:io.airlift.jmx.MBeanResource.java

@GET
@Produces(MediaType.TEXT_HTML)/*from  w  w  w.  ja v  a2  s  .  com*/
public String getMBeansUi() throws Exception {
    return Resources.toString(getResource(getClass(), "mbeans.html"), Charsets.UTF_8);
}

From source file:org.eclipse.che.selenium.core.utils.WorkspaceDtoDeserializer.java

public WorkspaceConfigDto deserializeWorkspaceTemplate(String templateName) {
    requireNonNull(templateName);/*from   w  w  w  .  j  a v a  2 s .  c  o m*/

    try {

        URL url = Resources.getResource(WorkspaceDtoDeserializer.class,
                format("/templates/workspace/%s/%s", infrastructure, templateName));
        return DtoFactory.getInstance().createDtoFromJson(Resources.toString(url, Charsets.UTF_8),
                WorkspaceConfigDto.class);
    } catch (IOException | IllegalArgumentException | JsonSyntaxException e) {
        LOG.error("Fail to read workspace template {} for infrastructure {} because {} ", templateName,
                infrastructure, e.getMessage());
        throw new RuntimeException(e.getLocalizedMessage(), e);
    }
}

From source file:org.hawkular.metrics.api.jaxrs.swagger.filter.JaxRsFilter.java

public JaxRsFilter() {
    OverrideConverter overrideConverter = new OverrideConverter();
    String durationJson;/*from   w w  w.j  a v a2  s.  c o m*/
    String tagsJson;
    try {
        durationJson = Resources.toString(getResource("rest-doc/duration.json"), UTF_8);
        tagsJson = Resources.toString(getResource("rest-doc/tags.json"), UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    overrideConverter.add(Duration.class.getName(), durationJson);
    overrideConverter.add(Tags.class.getName(), tagsJson);
    ModelConverters.addConverter(overrideConverter, true);
}

From source file:hrytsenko.gscripts.App.java

private static void executeEmbeddedScript(GroovyShell shell, String scriptName) {
    try {/*www  .  j  ava 2 s . co  m*/
        shell.evaluate(Resources.toString(Resources.getResource(scriptName), StandardCharsets.UTF_8));
    } catch (IOException exception) {
        throw new AppException(String.format("Cannot execute embedded script %s.", scriptName), exception);
    }
}

From source file:org.mayocat.search.elasticsearch.AbstractGenericEntityMappingGenerator.java

@Override
public Map<String, Object> generateMapping() {
    ObjectMapper mapper = new ObjectMapper();
    try {//  w  ww  .  ja  v a2  s  .com
        try {
            String fullJson = Resources.toString(Resources.getResource(getMappingFileName(forClass())),
                    Charsets.UTF_8);

            // There is a full mapping JSON file

            Map<String, Object> mapping = mapper.readValue(fullJson, new TypeReference<Map<String, Object>>() {
            });

            // check if "addons" mapping present, and merge it in if not
            if (!hasAddonsMapping(mapping)) {
                insertAddonsMapping(mapping);
            }

            return mapping;
        } catch (IllegalArgumentException e) {

            // This means the full mapping has not been found
            try {
                String propertiesJson = Resources.toString(
                        Resources.getResource(getPropertiesMappingFileName(forClass())), Charsets.UTF_8);

                // There is a mapping just for properties
                final Map<String, Object> properties = mapper.readValue(propertiesJson,
                        new TypeReference<Map<String, Object>>() {
                        });

                Map<String, Object> mapping = new HashMap<String, Object>();

                Map<String, Object> entity = new HashMap<String, Object>();
                Map<String, Object> entityProperties = new HashMap<String, Object>() {
                    {
                        // the "properties" property of the properties of the product object
                        put("properties", new HashMap<String, Object>() {
                            {
                                // the "properties" of the property "properties"
                                // of the properties of the product object
                                put("properties", properties);
                            }
                        });
                    }
                };

                if (Slug.class.isAssignableFrom(this.forClass())) {
                    entityProperties.put("slug", new HashMap<String, Object>() {
                        {
                            put("index", "not_analyzed");
                            put("type", "string");
                        }
                    });
                }

                entity.put("properties", entityProperties);
                mapping.put(getEntityName(forClass()), entity);

                insertAddonsMapping(mapping);

                return mapping;
            } catch (IllegalArgumentException e1) {

                // There is no mapping at all.
                return null;
            }
        }
    } catch (IOException e1) {
        return null;
    }
}

From source file:org.immutables.generator.ExtensionLoader.java

public static Supplier<ImmutableSet<String>> findExtensions(final String resource) {
    // Provide lazy-once supplier
    return Suppliers.memoize(new Supplier<ImmutableSet<String>>() {
        @Override/* ww w. j a  va  2s.  com*/
        public ImmutableSet<String> get() {
            List<String> extensions = Lists.newArrayList();

            // best effort to read it from compilation classpath
            if (StaticEnvironment.isInitialized()) {
                try {
                    String lines = getClasspathResourceText(StaticEnvironment.processing().getFiler(),
                            resource);
                    extensions.addAll(RESOURCE_SPLITTER.splitToList(lines));
                } catch (RuntimeException | IOException cannotReadCompilationClasspath) {
                    // we ignore this as we did or best effort
                    // and there are no plans to halt whole compilation
                }
            }

            ClassLoader classLoader = ExtensionLoader.class.getClassLoader();
            try {
                Enumeration<URL> resources = classLoader.getResources(resource);
                while (resources.hasMoreElements()) {
                    URL nextElement = resources.nextElement();
                    String lines = Resources.toString(nextElement, StandardCharsets.UTF_8);
                    extensions.addAll(RESOURCE_SPLITTER.splitToList(lines));
                }
            } catch (RuntimeException | IOException cannotReadAnnotationProcessingClasspath) {
                // we ignore this as we did or best effort
                // and there are no plans to halt whole compilation
            }
            return FluentIterable.from(extensions).toSet();
        }
    });
}

From source file:org.ow2.petals.cloud.manager.core.puppet.ClasspathScriptBuilder.java

public String build(Node node, Context context) throws CloudManagerException {
    try {/*from  w  ww.  j a  va2 s  .com*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(outputStream);
        URL resource = Resources.getResource(DownloadFilesScriptBuilder.class, getTemplate());
        String content = Resources.toString(resource, Charsets.UTF_8);
        MustacheFactory factory = new DefaultMustacheFactory();
        factory.compile(new StringReader(content), resource.toString()).execute(writer,
                getScope(node, context));
        writer.close();
        return outputStream.toString();
    } catch (IOException e) {
        throw new CloudManagerException("Can not load resource", e);
    } finally {

    }
}

From source file:co.cask.cdap.gateway.handlers.VersionHandler.java

private String determineVersion() {
    try {/*from w w w. ja  va  2  s .  c  o m*/
        String version = Resources.toString(Resources.getResource("VERSION"), Charsets.UTF_8);
        if (!version.equals("${project.version}")) {
            return version.trim();
        }
    } catch (IOException e) {
        LOG.warn("Failed to determine current version", e);
    }
    return "unknown";
}