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.pesegato.MonkeySheet.MonkeySheetAppState.java

protected void logBuildInfo() {
    try {// w ww . j ava 2s. c o  m
        java.net.URL u = Resources.getResource(LIBNAME + ".build.date");
        String build = Resources.toString(u, Charsets.UTF_8);
        log.info("MonkeySheet build date: " + build);
        log.info("MonkeySheet build version: "
                + Resources.toString(Resources.getResource(LIBNAME + ".build.version"), Charsets.UTF_8));
    } catch (java.io.IOException e) {
        log.error("Error reading build info", e);
    }
}

From source file:com.nesscomputing.migratory.jdbi.MigratoryStatementLocator.java

@Override
public String locate(final String statementName, final StatementContext context) throws Exception {
    context.setAttribute(MigratoryStatementRewriter.SKIP_REWRITE, null);

    if (StringUtils.isEmpty(statementName)) {
        throw new IllegalStateException("Statement Name can not be empty/null!");
    }/*from  w w  w.  jav  a 2s .  c om*/

    // This is a recorded statement that comes from some loader. This needs
    // to be preregistered using addTemplate, so look there.
    if (statementName.charAt(0) == '@') {
        LOG.trace("Retrieving statement: %s", statementName);
        final String rawSql = sql.get(statementName);

        if (rawSql == null) {
            throw new IllegalStateException("Statement '" + statementName + "' not registered!");
        }

        // @T is a template.
        if (statementName.charAt(1) == 'T') {
            return templatize(rawSql, context);
        } else {
            context.setAttribute(MigratoryStatementRewriter.SKIP_REWRITE, Boolean.TRUE);
            return rawSql;
        }
    }
    // Or is it one of the internal statements used by
    // migratory to do its housekeeping? If yes, load it from the
    // predefined location on the class path.
    else if (statementName.charAt(0) == '#') {
        // Multiple templates can be in a string template group. In that case, the name is #<template-group:<statement name>
        final String[] statementNames = StringUtils.split(statementName.substring(1), ":");

        final String sqlLocation = SQL_LOCATION + context.getAttribute("db_type") + "/" + statementNames[0]
                + ".st";

        LOG.trace("Loading SQL: %s", sqlLocation);
        final URL location = Resources.getResource(MigratoryStatementLocator.class, sqlLocation);
        if (location == null) {
            throw new IllegalArgumentException("Location '" + sqlLocation + "' does not exist!");
        }
        final String rawSql = Resources.toString(location, Charsets.UTF_8);

        if (statementNames.length == 1) {
            // Plain string template file. Just run it.
            return templatize(rawSql, context);
        } else {
            final StringTemplateGroup group = new StringTemplateGroup(new StringReader(rawSql),
                    AngleBracketTemplateLexer.class);
            LOG.trace("Found %s in %s", group.getTemplateNames(), location);

            final StringTemplate template = group.getInstanceOf(statementNames[1]);
            template.setAttributes(context.getAttributes());
            final String sql = template.toString();

            LOG.trace("SQL: %s", sql);
            return sql;
        }
    }
    // Otherwise, it is raw SQL that was run on the database. Pass it through.
    else {
        context.setAttribute(MigratoryStatementRewriter.SKIP_REWRITE, Boolean.TRUE);
        return statementName;
    }
}

From source file:bear.main.ProjectGenerator.java

public static String readResource(String path) throws IOException {
    return Resources.toString(ProjectGenerator.class.getResource(path), Charsets.UTF_8);
}

From source file:com.eucalyptus.cassandra.CassandraKeyspaces.java

private static Stream<String> scripts(final String keyspace) {
    // discover and sort cql scriptFilenames
    final List<String> scripts = Lists.newArrayList();
    final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
            CassandraKeyspaces.class.getClassLoader());
    try {//from ww  w .ja  va 2 s  . c  o  m
        final String pattern = String.format(KEYSPACE_RESOURCE_TEMPLATE, scriptName(keyspace));
        final Resource[] resources = resolver.getResources(pattern);
        final List<String> scriptFilenames = Lists.newArrayList();
        for (final Resource resource : resources) {
            scriptFilenames.add(resource.getFilename());
        }
        Collections.sort(scriptFilenames);
        for (final String resourceName : scriptFilenames) {
            scripts.add(Resources.toString(Resources.getResource(resourceName), StandardCharsets.UTF_8));
        }
    } catch (IOException e) {
        throw Exceptions.toUndeclared(e);
    }

    return scripts.stream();
}

From source file:com.streamsets.datacollector.execution.alerts.AlertManager.java

public void alert(List<String> emailIds, Throwable throwable) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    throwable.printStackTrace(printWriter);
    String description = stringWriter.toString();
    String subject = "ERROR: " + throwable;
    long timestamp = System.currentTimeMillis();
    String errorCode = "UNKNOWN";
    if (throwable instanceof PipelineException) {
        PipelineException pipelineException = (PipelineException) throwable;
        timestamp = pipelineException.getErrorMessage().getTimestamp();
        subject = "ERROR: " + pipelineException.getLocalizedMessage();
        errorCode = pipelineException.getErrorCode().getCode();
    }//from  ww w  .j  av  a2  s  . c  o m
    try {
        URL url = Resources.getResource(EmailConstants.ALERT_ERROR_EMAIL_TEMPLATE);
        String emailBody = Resources.toString(url, Charsets.UTF_8);
        java.text.DateFormat dateTimeFormat = new SimpleDateFormat(EmailConstants.DATE_MASK, Locale.ENGLISH);
        emailBody = emailBody.replace(EmailConstants.ERROR_CODE, errorCode)
                .replace(EmailConstants.TIME_KEY, dateTimeFormat.format(new Date(timestamp)))
                .replace(EmailConstants.PIPELINE_NAME_KEY, pipelineName)
                .replace(EmailConstants.DESCRIPTION_KEY, description).replace(EmailConstants.URL_KEY,
                        runtimeInfo.getBaseHttpUrl() + EmailConstants.PIPELINE_URL + pipelineName);
        subject = EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + subject;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Email Alert: subject = " + subject + ", body = " + emailBody);
        }
        if (emailSender == null) {
            LOG.error("Email Sender is not configured. Alert with message '{}' will not be sent via email:",
                    emailBody, throwable);
        } else {
            emailSender.send(emailIds, subject, emailBody);
        }
    } catch (EmailException | IOException e) {
        LOG.error("Error sending alert email, reason: {}", e.toString(), e);
        //Log error and move on. This should not stop the pipeline.
    }
}

From source file:org.apache.samza.sql.bench.utils.DataVerifier.java

public static String loadSchema(SchemaType type) throws IOException {
    switch (type) {
    case ORDERS://from   w  w w  .  j  a  va2 s  . c o  m
        return Resources.toString(TestDataGenerator.class.getResource("/benchorders.avsc"),
                Charset.defaultCharset());
    case PROJECT:
        return Resources.toString(TestDataGenerator.class.getResource("/projectout.avsc"),
                Charset.defaultCharset());
    case SLIDINGWINDOW:
        return Resources.toString(TestDataGenerator.class.getResource("/slidingwindowout.avsc"),
                Charset.defaultCharset());
    case FILTER:
        return Resources.toString(TestDataGenerator.class.getResource("/benchorders.avsc"),
                Charset.defaultCharset());
    case JOIN:
        return Resources.toString(TestDataGenerator.class.getResource("/joinout.avsc"),
                Charset.defaultCharset());
    case PRODUCT:
        return Resources.toString(TestDataGenerator.class.getResource("/product.avsc"),
                Charset.defaultCharset());
    default:
        throw new RuntimeException("Unknown verifier type: " + type);
    }
}

From source file:org.obm.sync.H2GuiceServletContextListener.java

private String readResourceAsString(String resource) throws IOException {
    return Resources.toString(Resources.getResource(resource), Charsets.UTF_8);
}

From source file:org.apache.provisionr.amazon.activities.RunInstances.java

private AmazonWebServiceRequest createRequest(Pool pool, DelegateExecution execution, boolean spot)
        throws IOException {
    final String businessKey = execution.getProcessBusinessKey();

    final String securityGroupName = SecurityGroups.formatNameFromBusinessKey(businessKey);
    final String keyPairName = KeyPairs.formatNameFromBusinessKey(businessKey);

    final String instanceType = pool.getHardware().getType();
    final String imageId = getImageIdFromPoolConfigurationOrQueryImageTable(pool, pool.getProvider(),
            instanceType);//from ww  w . j  av  a  2 s.  c om

    final String userData = Resources.toString(
            Resources.getResource(RunInstances.class, "/org/apache/provisionr/amazon/userdata.sh"),
            Charsets.UTF_8);

    List<BlockDevice> blockDevices = pool.getHardware().getBlockDevices();
    List<BlockDeviceMapping> blockDeviceMappings = Lists.newArrayList();
    if (blockDevices != null && blockDevices.size() > 0) {
        for (BlockDevice device : blockDevices) {
            blockDeviceMappings.add(new BlockDeviceMapping().withDeviceName(device.getName()).withEbs(
                    new EbsBlockDevice().withVolumeSize(device.getSize()).withDeleteOnTermination(true)));
        }
    }

    if (spot) {
        Calendar validUntil = Calendar.getInstance();
        validUntil.add(Calendar.MINUTE, 10);

        final String spotPrice = checkNotNull(pool.getProvider().getOption(ProviderOptions.SPOT_BID),
                "The bid for spot instances was not specified");

        LaunchSpecification ls = new LaunchSpecification().withInstanceType(instanceType)
                .withKeyName(keyPairName).withImageId(imageId).withBlockDeviceMappings(blockDeviceMappings)
                .withSecurityGroups(Lists.newArrayList(securityGroupName))
                .withUserData(Base64.encodeBytes(userData.getBytes(Charsets.UTF_8)));

        return new RequestSpotInstancesRequest().withSpotPrice(spotPrice).withLaunchSpecification(ls)
                .withLaunchGroup(businessKey).withInstanceCount(pool.getExpectedSize())
                .withType(SpotInstanceType.OneTime).withValidUntil(validUntil.getTime());

    } else {
        return new RunInstancesRequest().withClientToken(businessKey).withSecurityGroups(securityGroupName)
                .withKeyName(keyPairName).withInstanceType(instanceType).withImageId(imageId)
                .withBlockDeviceMappings(blockDeviceMappings).withMinCount(pool.getMinSize())
                .withMaxCount(pool.getExpectedSize())
                .withUserData(Base64.encodeBytes(userData.getBytes(Charsets.UTF_8)));
    }
}

From source file:com.optimizely.ab.event.internal.serializer.SerializerTestUtils.java

static String generateImpressionWithSessionIdJson() throws IOException {
    String impressionJson = Resources.toString(Resources.getResource("serializer/impression-session-id.json"),
            Charsets.UTF_8);//from  w  w w  .j av  a 2s.  c o m
    return impressionJson.replaceAll("\\s+", "");
}

From source file:org.saintandreas.util.XmlUtil.java

public static Document parseXmlResource(URL resource, Charset charset)
        throws SAXException, IOException, ParserConfigurationException {
    return parseXmlString(Resources.toString(resource, charset));
}