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.zeppelin.submarine.commons.SubmarineUI.java

public void createUsageUI() {
    try {//from   w  w  w .  j av  a2  s  . com
        List<CommandlineOption> commandlineOptions = getCommandlineOptions();
        HashMap<String, Object> mapParams = new HashMap();
        mapParams.put(unifyKey(SubmarineConstants.PARAGRAPH_ID), intpContext.getParagraphId());
        mapParams.put(SubmarineConstants.COMMANDLINE_OPTIONS, commandlineOptions);

        URL urlTemplate = Resources.getResource(SUBMARINE_USAGE_JINJA);
        String template = Resources.toString(urlTemplate, Charsets.UTF_8);
        Jinjava jinjava = new Jinjava();
        String submarineUsage = jinjava.render(template, mapParams);

        InterpreterResultMessageOutput outputUI = intpContext.out.getOutputAt(0);
        outputUI.clear();
        outputUI.write(submarineUsage);
        outputUI.flush();

        // UI update, log needs to be cleaned at the same time
        InterpreterResultMessageOutput outputLOG = intpContext.out.getOutputAt(1);
        outputLOG.clear();
        outputLOG.flush();
    } catch (IOException e) {
        LOGGER.error("Can't print usage", e);
    }
}

From source file:org.verinice.persistence.VeriniceAccountDaoImpl.java

private int getScopeIdForLoginName(String loginName) {

    String fileName = SCOPEID_FOR_ACCOUNT_JPQL;

    String jpql = null;/*  ww  w  . ja va2s .  c  o m*/
    try {
        jpql = Resources.toString(Resources.getResource(fileName), Charsets.UTF_8);
    } catch (IOException ex) {
        LOG.error("Error reading JPQL query from file: " + fileName, ex);
    }

    Query query = entityManager.createQuery(jpql).setParameter("loginName", loginName);

    int scopeId = -1;
    try {
        scopeId = (Integer) query.getSingleResult();
    } catch (Exception ex) {
        LOG.error("Could not retrieve scope id for user: '" + loginName + "'", ex);
    }

    return scopeId;
}

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

public void alert(Object value, List<String> emailIds, RuleDefinition ruleDefinition) {
    Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
            AlertsUtil.getAlertGaugeName(ruleDefinition.getId()));
    if (gauge == null) {
        Gauge<Object> alertResponseGauge = AlertManagerHelper.createAlertResponseGauge(pipelineName, revision,
                metrics, value, ruleDefinition);

        eventListenerManager.broadcastAlerts(new AlertInfo(pipelineName, ruleDefinition, alertResponseGauge));

        //send email the first time alert is triggered
        if (ruleDefinition.isSendEmail()) {
            try {
                URL url = Resources.getResource(EmailConstants.METRIC_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.ALERT_VALUE_KEY, String.valueOf(value))
                        .replace(EmailConstants.TIME_KEY,
                                dateTimeFormat.format(new Date((Long) System.currentTimeMillis())))
                        .replace(EmailConstants.PIPELINE_NAME_KEY, pipelineName)
                        .replace(EmailConstants.CONDITION_KEY, ruleDefinition.getCondition())
                        .replace(EmailConstants.URL_KEY,
                                runtimeInfo.getBaseHttpUrl() + EmailConstants.PIPELINE_URL + pipelineName);

                if (ruleDefinition instanceof DataRuleDefinition) {
                    emailBody = emailBody.replace(EmailConstants.ALERT_NAME_KEY,
                            ((DataRuleDefinition) ruleDefinition).getLabel());
                } else {
                    emailBody = emailBody.replace(EmailConstants.ALERT_NAME_KEY, ruleDefinition.getAlertText());
                }//  w w  w. j  a  va 2  s.c o  m

                if (emailSender == null) {
                    LOG.error(
                            "Email Sender is not configured. Alert '{}' with message '{}' will not be sent via email.",
                            ruleDefinition.getId(), emailBody);
                } else {
                    emailSender.send(emailIds,
                            EmailConstants.STREAMSETS_DATA_COLLECTOR_ALERT + ruleDefinition.getAlertText(),
                            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.
            }
        }
    } else {
        AlertManagerHelper.updateAlertGauge(gauge, value, ruleDefinition);
    }
}

From source file:org.openqa.selenium.safari.SafariDriverChannelHandler.java

private void handleMainPageRequest(ChannelHandlerContext ctx, HttpRequest request) throws IOException {
    String url = String.format("ws://localhost:%d", port);
    QueryStringDecoder queryString = new QueryStringDecoder(request.getUri());

    HttpResponse response;//w w  w. jav  a  2  s .c  o m
    List<String> urls = queryString.getParameters().get("url");
    if (urls == null || urls.isEmpty() || !url.equals(urls.iterator().next())) {
        response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);

        QueryStringEncoder encoder = new QueryStringEncoder("/connect.html");
        encoder.addParam("url", url);
        response.addHeader("Location", encoder.toString());

    } else {
        response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");

        URL clientLibUrl = getClass().getResource(CLIENT_RESOURCE_PATH);
        String content = "<!DOCTYPE html>\n<script>" + Resources.toString(clientLibUrl, Charsets.UTF_8)
                + "</script>";

        response.setContent(ChannelBuffers.copiedBuffer(content, Charsets.UTF_8));
        response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, response.getContent().readableBytes());
    }

    sendResponse(ctx, request, response);
}

From source file:com.googlecode.jmxtrans.model.output.elastic.ElasticWriter.java

private static void createMappingIfNeeded(JestClient jestClient, String indexName, String typeName)
        throws ElasticWriterException, IOException {
    synchronized (CREATE_MAPPING_LOCK) {
        IndicesExists indicesExists = new IndicesExists.Builder(indexName).build();
        boolean indexExists = jestClient.execute(indicesExists).isSucceeded();

        if (!indexExists) {

            CreateIndex createIndex = new CreateIndex.Builder(indexName).build();
            jestClient.execute(createIndex);

            URL url = ElasticWriter.class.getResource("/elastic-mapping.json");
            String mapping = Resources.toString(url, Charsets.UTF_8);

            PutMapping putMapping = new PutMapping.Builder(indexName, typeName, mapping).build();

            JestResult result = jestClient.execute(putMapping);
            if (!result.isSucceeded()) {
                throw new ElasticWriterException(
                        String.format("Failed to create mapping: %s", result.getErrorMessage()));
            } else {
                log.info("Created mapping for index {}", indexName);
            }//  w ww . j  ava  2s  . c  o m
        }
    }
}

From source file:org.glowroot.agent.config.PluginCache.java

private static void buildPluginDescriptor(URL url, @Nullable File pluginJar,
        List<PluginDescriptor> pluginDescriptors) throws IOException {
    String content = Resources.toString(url, UTF_8);
    ImmutablePluginDescriptor pluginDescriptor;
    try {//from   w w  w. ja v a2 s.c  om
        pluginDescriptor = mapper.readValue(content, ImmutablePluginDescriptor.class);
    } catch (JsonProcessingException e) {
        logger.error("error parsing plugin descriptor: {}", url.toExternalForm(), e);
        return;
    }
    pluginDescriptors.add(pluginDescriptor.withPluginJar(pluginJar));
}

From source file:net.minecraftforge.gradle.tasks.CreateStartTask.java

private String getResource(URL resource) {
    try {/*  w ww.  ja  va2s. c o m*/
        return Resources.toString(resource, Charsets.UTF_8);
    } catch (Exception e) {
        Throwables.propagate(e);
        return "";
    }
}

From source file:annis.gui.requesthandler.LoginServletRequestHandler.java

private void doPost(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {

    response.setContentType("text/html");

    String username = request.getParameter("annis-login-user");
    String password = request.getParameter("annis-login-password");

    if (username != null && password != null) {
        // forget any old user information
        session.getSession().removeAttribute(AnnisBaseUI.USER_KEY);
        session.getSession().removeAttribute(AnnisBaseUI.USER_LOGIN_ERROR);

        // get the URL for the REST service
        Object annisServiceURLObject = session.getSession().getAttribute(AnnisBaseUI.WEBSERVICEURL_KEY);

        if (annisServiceURLObject == null || !(annisServiceURLObject instanceof String)) {
            log.warn("AnnisWebService.URL was not set as init parameter in web.xml");
        }//from  w ww . jav  a2  s .c  o m

        String webserviceURL = (String) annisServiceURLObject;

        try {
            AnnisUser user = new AnnisUser(username, password);
            WebResource res = user.getClient().resource(webserviceURL).path("admin").path("is-authenticated");
            if ("true".equalsIgnoreCase(res.get(String.class))) {
                // everything ok, save this user configuration for re-use
                Helper.setUser(user);
            }
        } catch (ClientHandlerException ex) {
            session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR,
                    "Authentification error: " + ex.getMessage());
            response.setStatus(502); // bad gateway
        } catch (LoginDataLostException ex) {
            session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR, "Lost password in memory. Sorry.");
            response.setStatus(500); // server error
        } catch (UniformInterfaceException ex) {
            if (ex.getResponse().getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) {
                session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR, "Username or password wrong");
                response.setStatus(403); // Forbidden
            } else {
                log.error(null, ex);
                session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR,
                        "Unexpected exception: " + ex.getMessage());
                response.setStatus(500);
            }
        }

        try (OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), Charsets.UTF_8)) {
            String html = Resources.toString(LoginServletRequestHandler.class.getResource("closelogin.html"),
                    Charsets.UTF_8);
            CharStreams.copy(new StringReader(html), writer);
        }

    } // end if login attempt

}

From source file:org.apache.drill.PlanningBase.java

protected String getFile(String resource) throws IOException {
    URL url = Resources.getResource(resource);
    if (url == null) {
        throw new IOException(String.format("Unable to find path %s.", resource));
    }//  w w w  .j  av  a 2 s. com
    return Resources.toString(url, Charsets.UTF_8);
}

From source file:com.stratio.deep.cassandra.embedded.CassandraServer.java

/**
 * Set embedded cassandra up and spawn it in a new thread.
 *
 * @throws TTransportException//from w w w  . ja  v a  2  s. co m
 * @throws IOException
 * @throws InterruptedException
 */
public void start() throws IOException, InterruptedException, ConfigurationException {

    File dir = Files.createTempDir();
    String dirPath = dir.getAbsolutePath();
    logger.info("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 {
        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.properties");
    System.setProperty("cassandra-foreground", "true");
    System.setProperty("cassandra.skip_wait_for_gossip_to_settle", "0");

    cleanupAndLeaveDirs();

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

    try {
        TimeUnit.SECONDS.sleep(WAIT_SECONDS);
    } catch (InterruptedException e) {
        logger.error(e);
        throw new AssertionError(e);
    }

    initKeySpace();
}