Example usage for com.google.common.io CharStreams toString

List of usage examples for com.google.common.io CharStreams toString

Introduction

In this page you can find the example usage for com.google.common.io CharStreams toString.

Prototype

public static String toString(Readable r) throws IOException 

Source Link

Document

Reads all characters from a Readable object into a String .

Usage

From source file:com.cloudera.whirr.cm.handler.CmServerHandler.java

@Override
protected void beforeConfigure(ClusterActionEvent event) throws IOException, InterruptedException {
    CmServerClusterInstance.logHeader(logger, "HostConfigure");
    CmServerClusterInstance.logLineItemAsync(logger, "HostConfigureInit");
    super.beforeConfigure(event);
    URL licenceConfigUri = null;//  w w w  .  j av  a  2 s.c o  m
    if ((licenceConfigUri = Utils.urlForURI(CmServerClusterInstance.getConfiguration(event.getClusterSpec())
            .getString(CONFIG_WHIRR_CM_LICENSE_URI))) != null) {
        addStatement(event, createOrOverwriteFile("/tmp/" + CM_LICENSE_FILE, Splitter.on('\n')
                .split(CharStreams.toString(Resources.newReaderSupplier(licenceConfigUri, Charsets.UTF_8)))));
    }
    addStatement(event,
            call("configure_cm_server", "-t",
                    CmServerClusterInstance.getClusterConfiguration(event.getClusterSpec(),
                            CmServerClusterInstance.getMounts(event.getClusterSpec(), event.getCluster()),
                            CmServerServiceTypeCms.CM.getId(), null, CONFIG_CM_DB_SUFFIX_TYPE)));
    CmServerClusterInstance.logLineItemFooterAsync(logger, "HostConfigureInit");
    CmServerClusterInstance.logLineItemAsync(logger, "HostConfigureExecute");
}

From source file:com.ritesh.idea.plugin.util.HttpRequestBuilder.java

public String asString() throws IOException, URISyntaxException {
    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .build()) {/*  www.  j  a  va 2  s  . c  om*/
        HttpRequestBase request = getHttpRequest();
        CloseableHttpResponse response = client.execute(request);
        return CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
    }
}

From source file:com.microsoft.azure.management.appservice.implementation.WebAppImpl.java

@Override
public PublishingProfile getPublishingProfile() {
    InputStream stream = this.manager().inner().webApps()
            .listPublishingProfileXmlWithSecrets(resourceGroupName(), name());
    try {//from ww  w  .j  a va 2 s  .  c  om
        String xml = CharStreams.toString(new InputStreamReader(stream));
        return new PublishingProfileImpl(xml, this);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.microsoftopentechnologies.intellij.helpers.aadauth.AuthenticationContext.java

public ListenableFuture<AuthenticationResult> acquireTokenInteractiveAsync(final String tenantName,
        final String resource, final String clientId, final String redirectUri, final Project project,
        final String windowTitle, final String promptValue) throws IOException {

    final SettableFuture<AuthenticationResult> future = SettableFuture.create();

    // get the auth code
    ListenableFuture<String> authCodeFuture = acquireAuthCodeInteractiveAsync(tenantName, resource, clientId,
            redirectUri, project, windowTitle, promptValue);
    Futures.addCallback(authCodeFuture, new FutureCallback<String>() {
        @Override//from  w  w w  . j a  v  a  2s. co  m
        public void onSuccess(String code) {
            OutputStream output = null;
            BufferedReader reader = null;

            try {
                // if code is null then the user cancelled the auth
                if (code == null) {
                    future.set(null);
                    return;
                }

                URL adAuthEndpointUrl = new URL(
                        TOKEN_ENDPOINT_TEMPLATE.replace("{host}", authority).replace("{tenant}", tenantName));

                // build the a/d auth params
                Map<String, String> params = new HashMap<String, String>();
                params.put(OAuthParameter.clientId, clientId);
                params.put(OAuthParameter.code, code);
                params.put(OAuthParameter.grantType, OAuthGrantType.AuthorizationCode);
                params.put(OAuthParameter.redirectUri, redirectUri);
                params.put(OAuthParameter.resource, resource);
                byte[] requestData = EncodingHelper.toQueryString(params).getBytes(Charsets.UTF_8);

                // make a POST request to the endpoint with this data
                HttpURLConnection connection = (HttpURLConnection) adAuthEndpointUrl.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded; charset=" + Charsets.UTF_8.name());
                connection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
                output = connection.getOutputStream();
                output.write(requestData);
                output.close();
                output = null;

                // read the response
                int statusCode = connection.getResponseCode();
                if (statusCode != HttpURLConnection.HTTP_OK) {
                    // TODO: Is IOException the right exception type to raise?
                    String err = CharStreams.toString(new InputStreamReader(connection.getErrorStream()));
                    future.setException(new IOException("AD Auth token endpoint returned HTTP status code "
                            + Integer.toString(statusCode) + ". Error info: " + err));
                    return;
                }

                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                reader.close();
                reader = null;

                // parse the JSON
                String response = sb.toString();
                JsonParser parser = new JsonParser();
                JsonObject root = (JsonObject) parser.parse(response);

                // construct the authentication result object
                AuthenticationResult result = new AuthenticationResult(
                        getJsonStringProp(root, OAuthReservedClaim.TokenType),
                        getJsonStringProp(root, OAuthReservedClaim.AccessToken),
                        getJsonStringProp(root, OAuthReservedClaim.RefreshToken),
                        getJsonLongProp(root, OAuthReservedClaim.ExpiresOn),
                        UserInfo.parse(getJsonStringProp(root, OAuthReservedClaim.IdToken)));
                future.set(result);

            } catch (MalformedURLException e) {
                future.setException(e);
            } catch (ProtocolException e) {
                future.setException(e);
            } catch (IOException e) {
                future.setException(e);
            } catch (ParseException e) {
                future.setException(e);
            } finally {
                try {
                    if (output != null) {
                        output.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException ignored) {
                }
            }
        }

        @Override
        public void onFailure(@NotNull Throwable throwable) {
            future.setException(throwable);
        }
    });

    return future;
}

From source file:com.rapid7.conqueso.client.metadata.EC2InstanceMetadataProvider.java

private String readResponse(HttpURLConnection connection) throws IOException {
    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
        throw new IllegalArgumentException("The requested metadata is not found at " + connection.getURL());
    }//from w ww . j  a v  a 2 s. com

    InputStreamReader reader = new InputStreamReader(connection.getInputStream(), Charsets.UTF_8);
    try {
        return CharStreams.toString(reader);
    } finally {
        reader.close();
    }
}

From source file:zipkin2.storage.cassandra.Schema.java

static void applyCqlFile(String keyspace, Session session, String resource) {
    try (Reader reader = new InputStreamReader(Schema.class.getResourceAsStream(resource), UTF_8)) {
        for (String cmd : CharStreams.toString(reader).split(";")) {
            cmd = cmd.trim().replace(" " + DEFAULT_KEYSPACE, " " + keyspace);
            if (!cmd.isEmpty()) {
                session.execute(cmd);//from w w w.j a v  a 2 s.  c o  m
            }
        }
    } catch (IOException ex) {
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:com.eviware.soapui.impl.rest.mock.RestMockAction.java

@Override
public void setExampleScript() {
    if (getScript() == null) {
        try {//  w  w  w.j  a v  a 2  s. co  m
            String groovyScriptName = "com/eviware/soapui/impl/rest/mock/dispatching-script-sample.groovy";
            InputStream groovyStream = getClass().getClassLoader().getResourceAsStream(groovyScriptName);
            InputStreamReader groovyReader = new InputStreamReader(groovyStream);
            String groovyScript = CharStreams.toString(groovyReader);

            setScript(groovyScript);
        } catch (IOException e) {
            SoapUI.logError(e);
        }
    }
}

From source file:com.vilt.minium.impl.JQueryInvoker.java

protected static String getFileContent(String filename) {
    InputStream in = null;/*from  w  ww.  j  a va 2 s.  com*/
    try {
        in = getClasspathFileInputStream(filename);
        return CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
    } catch (IOException e) {
        throw new WebElementsException(format("Could not load %s from classpath", filename), e);
    } finally {
        try {
            Closeables.close(in, true);
        } catch (IOException e) {
        }
    }
}

From source file:co.freeside.betamax.tape.MemoryTape.java

private static RecordedRequest recordRequest(Request request) {
    try {/*from   w w  w. j  a va 2s  . com*/
        final RecordedRequest recording = new RecordedRequest();
        recording.setMethod(request.getMethod());
        recording.setUri(request.getUri());

        for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
            if (!header.getKey().equals(VIA)) {
                recording.getHeaders().put(header.getKey(), header.getValue());
            }
        }

        if (request.hasBody()) {
            recording.setBody(CharStreams.toString(request.getBodyAsText()));
        }

        return recording;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:uk.co.armedpineapple.cth.Files.java

/**
 * Returns a string containing the text from a raw resource
 *
 * @param ctx      a activityContext//ww  w. j  a  v  a2s  .c  om
 * @param resource the resource to read
 * @return a String containing the text contents of the resource
 * @throws IOException if the resource cannot be found or read
 */
public static String readTextFromResource(Context ctx, int resource) throws IOException {

    InputStream inputStream = null;
    try {
        inputStream = ctx.getResources().openRawResource(resource);
        String r = CharStreams.toString(new InputStreamReader(inputStream));
        return r;
    } finally {
        if (inputStream != null)
            inputStream.close();

    }
}