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.mayocat.shop.shipping.DefaultShippingService.java

private Map<String, Destination> getDestinations() {
    if (destinations == null) {
        ObjectMapper mapper = new ObjectMapper();
        try {/*from  w  w  w. jav  a 2 s .  c o m*/
            destinations = mapper.readValue(Resources.toString(
                    Resources.getResource("org/mayocat/shop/shipping/destinations/earth_flat.json"),
                    Charsets.UTF_8), new TypeReference<Map<String, Destination>>() {
                    });
        } catch (IOException e) {
            this.logger.error("Failed to load destinations", e);
        }
    }
    return destinations;
}

From source file:org.apache.isis.core.metamodel.services.grid.GridLoaderServiceDefault.java

private static String resourceContentOf(final Class<?> cls, final String resourceName) throws IOException {
    final URL url = Resources.getResource(cls, resourceName);
    return Resources.toString(url, Charset.defaultCharset());
}

From source file:ext.deployit.community.ci.dictionary.ScriptRunner.java

protected static String loadScriptResource(String scriptName) throws IOException {
    String scriptPath = scriptName;
    String script = Resources.toString(Resources.getResource(scriptPath), Charset.defaultCharset());
    return script;
}

From source file:playn.java.JavaAssets.java

@Override
protected void doGetText(final String path, final ResourceCallback<String> callback) {
    doResourceAction(new Runnable() {
        public void run() {
            try {
                callback.done(Resources.toString(requireResource(pathPrefix + path), Charsets.UTF_8));
            } catch (Exception e) {
                callback.error(e);//w ww.  j  ava  2 s .c  o  m
            }
        }
    });
}

From source file:com.google.template.soy.data.SanitizedContents.java

/**
 * Loads assumed-safe content from a Java resource.
 *
 * This performs ZERO VALIDATION of the data, and takes you on your word that the input is valid.
 * We assume that resources should be safe because they are part of the binary, and therefore not
 * attacker controlled, unless the source code is compromised (in which there's nothing we can
 * do)./*w  ww.j a va2 s . c  o m*/
 *
 * @param resourceName The name of the resource to be found using
 *                     {@linkplain Thread#getContextClassLoader() context class loader}.
 * @param charset The character set to use, usually Charsets.UTF_8.
 * @param kind The content kind of the resource.
 */
public static SanitizedContent fromResource(String resourceName, Charset charset, ContentKind kind)
        throws IOException {
    pretendValidateResource(resourceName, kind);
    return SanitizedContent.create(Resources.toString(Resources.getResource(resourceName), charset), kind,
            // Text resources are usually localized, so one might think that the locale direction should
            // be assumed for them. We do not do that because:
            // - We do not know the locale direction here.
            // - Some messages do not get translated.
            // - This method currently can't be used for text resources (see pretendValidateResource()).
            getDefaultDir(kind));
}

From source file:com.eucalyptus.cassandra.config.CassandraSysUtil.java

static String generateCassandraRackDcProperties(final String dc, final String rack) throws IOException {
    final String cassandraRackDcTemplate = Resources.toString(Resources.getResource(RACKDC_RESOURCE_NAME),
            StandardCharsets.UTF_8);
    return Templates.prepare(RACKDC_RESOURCE_NAME).withProperty("dc", dc).withProperty("rack", rack)
            .evaluate(cassandraRackDcTemplate);
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private String createEmailContent() throws IOException {
    int size = reportContextList.size();
    List<String> rowData = newArrayListWithCapacity(size);

    String reportRowTemplate = Resources.toString(getClass().getResource("email-report-row-template.html"),
            Charset.forName("UTF-8"));
    for (int i = 0; i < size; ++i) {
        ReportContext context = reportContextList.get(i);

        String rowContent = replacePlaceholderToken(reportRowTemplate, "counter", String.valueOf(i));
        rowContent = replacePlaceholderToken(rowContent, "start",
                TIMESTAMP_FORMAT.format(context.getStartMillis()));
        rowContent = replacePlaceholderToken(rowContent, "finish",
                TIMESTAMP_FORMAT.format(context.getStopMillis()));
        rowContent = replacePlaceholderToken(rowContent, "duration",
                DurationFormatUtils.formatDurationHMS(context.getStopMillis() - context.getStartMillis()));
        rowContent = replacePlaceholderToken(rowContent, "testobject", context.getTestObjectName());

        Throwable th = context.getThrowable();
        if (th == null) {
            rowContent = replacePlaceholderToken(rowContent, "image", "check");
            rowContent = replacePlaceholderToken(rowContent, "errormsg", "");
            rowContent = replacePlaceholderToken(rowContent, "style", "success");
        } else {/*from   w  w  w.  j a v a2 s.  c o m*/
            rowContent = replacePlaceholderToken(rowContent, "image", "error");

            String msg = th.getMessage();

            Throwable root = th;
            while (root.getCause() != null) {
                root = root.getCause();
            }

            String rootMsg = root.getMessage();
            if (rootMsg != null && !rootMsg.equals(msg)) {
                msg += " - Root Message: " + rootMsg;
            }

            if (isBlank(msg)) {
                msg = th.getClass().getName();
            }

            rowContent = replacePlaceholderToken(rowContent, "errormsg", msg);
            rowContent = replacePlaceholderToken(rowContent, "style", "error");
        }

        rowData.add(rowContent);
    }

    String reportTemplate = Resources.toString(getClass().getResource("email-report-template.html"),
            Charset.forName("UTF-8"));
    reportTemplate = replacePlaceholderToken(reportTemplate, "timestamp", TIMESTAMP_FORMAT.format(new Date()),
            false);

    String reportData = on(LINE_SEPARATOR).join(rowData);
    reportTemplate = replacePlaceholderToken(reportTemplate, "rows", reportData, false);
    return reportTemplate;
}

From source file:org.incode.module.commchannel.dom.api.GeocodingService.java

private GeocodedAddress demoResponse() {
    final URL resource = Resources.getResource(getClass(),
            "postalAddress-45+High+St%2C+Oxford%2C+Oxfordshire+OX1%2C+UK.json");
    final String json;
    try {//  w  w  w  . j ava  2 s  .  c om
        json = Resources.toString(resource, Charsets.UTF_8);
        return asGeocodedAddress(json);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.testing.pogen.GenerateCommand.java

@Override
public void execute() throws IOException {
    File rootInputDir = createDirectory(rootDirectoryPath, false, true);
    File testOutDir = createDirectory(testOutDirPath, false, true);

    // Check whether the root directory exists
    if (!rootInputDir.exists()) {
        throw new FileProcessException("Not found root intpu directory", rootInputDir);
    }//from  w  ww  .java 2  s .  c  om

    // Generate the AbstractPage class
    File newAbstractPageFile = new File(testOutDir.getPath(), ABSTRACT_PAGE_NAME);
    if (!newAbstractPageFile.exists()) {
        URL abstractPageUrl = Resources.getResource(ABSTRACT_PAGE_NAME);
        String abstractPage = Resources.toString(abstractPageUrl, Charset.defaultCharset());
        abstractPage = abstractPage.replaceAll(ABSTRACT_PAGE_PACKAGE, packageName);
        Files.write(abstractPage, newAbstractPageFile, Charset.defaultCharset());
    } else if (verbose) {
        System.err.println("Already exists: " + newAbstractPageFile.getAbsolutePath() + ".");
    }

    // Collect the template files from the arguments indicating paths of template files
    ArrayList<File> templateFiles = new ArrayList<File>();
    for (String templatePath : templatePaths) {
        File file = createFileFromFilePath(templatePath);
        templateFiles.add(file);
    }

    // Collect the template files from the specified pattern with the root directory
    if (!Strings.isNullOrEmpty(templateFilePattern)) {
        templateFiles.addAll(FileUtils.listFiles(rootInputDir, new RegexFileFilter(templateFilePattern),
                isRecusive ? FileFilterUtils.trueFileFilter() : null));
    }

    TemplateUpdater updater = TemplateUpdaters.getPreferredUpdater(attributeName);
    TestCodeGenerator generator = TestCodeGenerators.getPreferredGenerator(attributeName);
    for (File file : templateFiles) {
        checkExistenceAndPermission(file, true, true);
        try {
            TemplateParser parser = TemplateParsers.getPreferredParser(file.getPath(), attributeName);
            if (attributeName.equals("id") && parser instanceof JsfParser) {
                System.out.println("WARNING: Using id attribute is not recommmended for JSF templat engine.");
            }
            parseAndGenerate(file, rootInputDir, testOutDir, parser, updater, generator);
        } catch (TemplateParseException e) {
            throw new FileProcessException("Errors occur in parsing the specified files", file, e);
        } catch (PageObjectUpdateException e) {
            throw new FileProcessException("Errors occur in updating the specified files", file, e);
        }
    }
}

From source file:org.apache.isis.core.commons.lang.ClassExtensions.java

public static String resourceContentOf(final Class<?> cls, final String resourceName) throws IOException {
    final URL url = Resources.getResource(cls, resourceName);
    return Resources.toString(url, Charset.defaultCharset());
}