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.github.cassandra.jdbc.BaseCassandraPreparedStatement.java

public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
    // FIXME Slow and will run into OOM issue
    try {//from w  w  w  . j  a v a2s.  c o m
        setString(parameterIndex, CharStreams.toString(reader).substring(0, (int) length));
    } catch (IOException e) {
        throw new SQLException(e);
    }
}

From source file:com.redhat.che.multitenant.Fabric8AuthServiceClient.java

/** Note this method is duplicated from {@link KeycloakServiceClient} */
private String doRequest(String url, String method, List<Pair<String, ?>> parameters) throws IOException,
        ServerException, ForbiddenException, NotFoundException, UnauthorizedException, BadRequestException {
    final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
    final boolean hasQueryParams = parameters != null && !parameters.isEmpty();
    if (hasQueryParams) {
        final UriBuilder ub = UriBuilder.fromUri(url);
        for (Pair<String, ?> parameter : parameters) {
            ub.queryParam(parameter.first, parameter.second);
        }/*from   w  w w. jav a2  s .c  om*/
        url = ub.build().toString();
    }
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(60000);

    try {
        conn.setRequestMethod(method);
        // drop a hint for server side that we want to receive application/json
        conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (authToken != null) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "bearer " + authToken);
        }
        final int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
            InputStream in = conn.getErrorStream();
            if (in == null) {
                in = conn.getInputStream();
            }
            final String str;
            try (Reader reader = new InputStreamReader(in)) {
                str = CharStreams.toString(reader);
            }
            final String contentType = conn.getContentType();
            if (contentType != null && (contentType.startsWith(MediaType.APPLICATION_JSON)
                    || contentType.startsWith("application/vnd.api+json"))) {
                final KeycloakErrorResponse serviceError = DtoFactory.getInstance().createDtoFromJson(str,
                        KeycloakErrorResponse.class);
                if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
                    throw new ForbiddenException(serviceError.getErrorMessage());
                } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
                    throw new NotFoundException(serviceError.getErrorMessage());
                } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
                    throw new UnauthorizedException(serviceError.getErrorMessage());
                } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
                    throw new ServerException(serviceError.getErrorMessage());
                } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) {
                    throw new BadRequestException(serviceError.getErrorMessage());
                }
                throw new ServerException(serviceError.getErrorMessage());
            }
            // Can't parse content as json or content has format other we expect for error.
            throw new IOException(String.format("Failed access: %s, method: %s, response code: %d, message: %s",
                    UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
        }
        try (Reader reader = new InputStreamReader(conn.getInputStream())) {
            return CharStreams.toString(reader);
        }
    } finally {
        conn.disconnect();
    }
}

From source file:org.geosdi.geoplatform.connector.server.request.GPPostConnectorRequest.java

@Override
public String getResponseAsString() throws ServerInternalFault, Exception, IllegalParameterFault {
    String content = null;//  www. j  a  va 2  s. c  o  m
    try {
        HttpPost httpPost = this.getPostMethod();
        HttpResponse httpResponse = super.securityConnector.secure(this, httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();

        if (responseEntity != null) {
            InputStream is = responseEntity.getContent();

            content = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));

            EntityUtils.consume(responseEntity);
        } else {
            throw new ServerInternalFault("Connector Server Error: Connection problem");
        }

    } catch (JAXBException ex) {
        logger.error("\n@@@@@@@@@@@@@@@@@@ JAXBException *** {} ***", ex.getMessage());
        throw new ServerInternalFault("*** JAXBException ***");

    } catch (ClientProtocolException ex) {
        logger.error("\n@@@@@@@@@@@@@@@@@@ ClientProtocolException *** {} ***", ex.getMessage());
        throw new ServerInternalFault("*** ClientProtocolException ***");

    }

    return content;
}

From source file:com.microsoft.tooling.msservices.helpers.azure.rest.RestServiceManagerBaseImpl.java

@NotNull
private static String readStream(@NotNull InputStream is) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(is));

    try {/*from w ww  . j a  v a 2  s.com*/
        return CharStreams.toString(in);
    } finally {
        in.close();
    }
}

From source file:com.wealdtech.hawk.jersey.HawkAuthenticator.java

/**
 * Authenticate a request from an authentication header.
 * @param request the HTTP request//from   w  w w . j ava 2s.  c o  m
 * @return the authenticated principal, or <code>Optional.absent()</code> if the request was not authenticated
 * @throws DataError if there is a problem with the data that prevents the authentication attempt
 */
private Optional<T> authenticateFromHeader(final ContainerRequest request) {
    final ImmutableMap<String, String> authorizationHeaders = server
            .splitAuthorizationHeader(request.getHeaderValue(ContainerRequest.AUTHORIZATION));
    checkNotNull(authorizationHeaders.get("id"), "Missing required Hawk authorization header \"id\"");
    checkNotNull(authorizationHeaders.get("ts"), "Missing required Hawk authorization header \"ts\"");
    checkNotNull(authorizationHeaders.get("mac"), "Missing required Hawk authorization header \"mac\"");
    checkNotNull(authorizationHeaders.get("nonce"), "Missing required Hawk authorization header \"nonce\"");
    String hash = null;
    final URI uri = request.getRequestUri();
    final String method = request.getMethod();
    final Optional<T> principal = provider.getFromKey(authorizationHeaders.get("id"));
    if (!principal.isPresent()) {
        // Could not find the principal, reject this authentication request
        return Optional.absent();
    }
    final HawkCredentials credentials = principal.get().getHawkCredentials(authorizationHeaders.get("id"));
    if (authorizationHeaders.get("hash") != null) {
        try {
            List<String> contentTypes = request.getRequestHeader(ContainerRequest.CONTENT_TYPE);
            if ((contentTypes == null) || (contentTypes.size() == 0)) {
                throw new DataError.Bad("Missing content type header for body verification");
            }
            hash = Hawk.calculateBodyMac(credentials, contentTypes.get(0),
                    CharStreams.toString(new InputStreamReader(request.getEntityInputStream(), "UTF-8")));
        } catch (IOException ioe) {
            throw new DataError.Bad("Failed to read the message body to calculate hash", ioe);
        }
    }
    final boolean hasBody = request.getHeaderValue(ContainerRequest.CONTENT_LENGTH) != null ? true : false;
    this.server.authenticate(credentials, uri, method, authorizationHeaders, hash, hasBody);
    return principal;
}

From source file:com.spotify.helios.authentication.crtauth.CrtAuthClientImpl.java

private static CrtAuthClient makeCrtAuthClient(final Path privateKeyPath, final URI authServer)
        throws CrtAuthException {
    final Signer signer;

    // Try to parse private key file if not null
    if (privateKeyPath != null) {
        try {//from  w w w  .j  a  v  a2s  .  co  m
            final String privateKeyStr = CharStreams.toString(new FileReader(privateKeyPath.toString()));
            final RSAPrivateKeySpec privateKeySpec = TraditionalKeyParser.parsePemPrivateKey(privateKeyStr);
            final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
            signer = new SingleKeySigner(privateKey);
        } catch (IOException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new CrtAuthException(String
                    .format("Couldn't parse private key %s. If it's encrypted with a passphrase, make sure "
                            + "ssh-agent is running, you've added your key to it, and don't specify your "
                            + "private key in the helios command line. This helios-crtauth auth plugin will then "
                            + "sign the CRT challenge by passing it to ssh-agent.", privateKeyPath.toString()),
                    e);
        }
    } else {
        signer = new AgentSigner();
    }

    return new CrtAuthClient(signer, authServer.getHost());
}

From source file:org.gololang.webconsole.RunServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    try (InputStreamReader reader = new InputStreamReader(request.getInputStream(), Charsets.UTF_8)) {
        String code = CharStreams.toString(reader);
        run(code, response);//from w  w  w  .j ava2  s.  c  om
    }
}

From source file:com.axmor.eclipse.typescript.core.internal.TypeScriptAPIImpl.java

@Override
public JSONObject compileTsConfig(IFile file) {
    checkBridge();//from w ww  .j  a va2s.  c o  m
    try {
        JSONObject tsConfig = new JSONObject(
                CharStreams.toString(new InputStreamReader(file.getContents(), Charsets.UTF_8)));

        JSONObject res = bridge.invokeBridgeMethod("compile", file, 0, null);
        if (tsConfig.has("compilerOptions") && tsConfig.getJSONObject("compilerOptions") != null) {
            JSONObject options = tsConfig.getJSONObject("compilerOptions");
            final AtomicReference<IResource> outResource = new AtomicReference<>();
            if (options.has("out") && options.getString("out") != null) {
                String out = options.getString("out");
                outResource.set(file.getParent().getFile(new Path(out)));
            }
            if (options.has("outDir") && options.getString("outDir") != null) {
                String out = options.getString("outDir");
                outResource.set(file.getParent().getFolder(new Path(out)));
            }
            if (outResource.get() != null) {
                new UIJob("Refresh target resources") {
                    @Override
                    public IStatus runInUIThread(IProgressMonitor monitor) {
                        try {
                            outResource.get().refreshLocal(IResource.DEPTH_INFINITE, monitor);
                        } catch (CoreException e) {
                            Activator.error(e);
                            return new Status(Status.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
                        }
                        return Status.OK_STATUS;
                    }
                }.schedule();
            }
        }
        return res;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.google.api.codegen.sync.Synchronizer.java

@Override
public FileVisitResult visitFile(Path generatedPath, BasicFileAttributes attrs) throws IOException {
    // Compute the paths to equivalent files in source and baseline.
    String relativePath = generatedPath.toString();
    Preconditions.checkState(relativePath.startsWith(options.get(GENERATED_PATH) + "/"));
    relativePath = relativePath.substring(options.get(GENERATED_PATH).length() + 1);
    Path sourcePath = Paths.get(options.get(SOURCE_PATH), relativePath);
    Path baselinePath = Paths.get(options.get(BASELINE_PATH), relativePath);

    Files.createDirectories(sourcePath.getParent());
    if (!Files.exists(sourcePath)) {
        // If the source does not yet exist, create it from generated.
        Files.copy(generatedPath, sourcePath);
    } else {/*from w w  w. j  a v a 2 s  .  c o m*/
        // Perform 3-way or 2-way merge
        List<String> cmdArgs = new ArrayList<>();
        cmdArgs.add(options.get(KDIFF3));
        cmdArgs.add("--merge");
        if (options.get(AUTO_MERGE)) {
            cmdArgs.add("--auto");
        }
        if (!options.get(AUTO_RESOLUTION)) {
            cmdArgs.add("--qall");
        }
        cmdArgs.add("--output");
        cmdArgs.add(sourcePath.toString());
        if (!options.get(IGNORE_BASE) && Files.exists(baselinePath)) {
            cmdArgs.add(baselinePath.toString());
            cmdArgs.add("--fname");
            cmdArgs.add("BASE " + relativePath);
        }
        cmdArgs.add(generatedPath.toString());
        cmdArgs.add("--fname");
        cmdArgs.add("GENERATED " + relativePath);
        cmdArgs.add(sourcePath.toString());
        cmdArgs.add("--fname");
        cmdArgs.add("EDITED " + relativePath);
        Process process = new ProcessBuilder().command(cmdArgs).redirectErrorStream(true).start();
        InputStreamReader stdout = new InputStreamReader(process.getInputStream());
        try {
            int resultCode = process.waitFor();
            if (resultCode != 0) {
                error("unresolved merge conflict for '%s', aborting. Output:%n%s", relativePath,
                        CharStreams.toString(stdout));
                return FileVisitResult.TERMINATE;
            }
            if (!Files.exists(baselinePath)) {
                // If the baseline does not yet exist, create it from output.
                Files.copy(sourcePath, baselinePath);
            }
        } catch (InterruptedException e) {
            error("interrupted during merge conflict resolution for '%s', aborting. Output:%n%s", relativePath,
                    CharStreams.toString(stdout));
            return FileVisitResult.TERMINATE;
        }
    }

    // Update the baseline.
    Files.createDirectories(baselinePath.getParent());
    Files.copy(generatedPath, baselinePath, StandardCopyOption.REPLACE_EXISTING);
    return FileVisitResult.CONTINUE;
}

From source file:com.microsoftopentechnologies.auth.AuthenticationContext.java

public ListenableFuture<AuthenticationResult> acquireTokenInteractiveAsync(final String tenantName,
        final String resource, final String clientId, final String redirectUri, 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, windowTitle, promptValue);
    Futures.addCallback(authCodeFuture, new FutureCallback<String>() {
        @Override/*from w w w.ja  v a 2 s  . c o 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(
                        JsonUtils.getJsonStringProp(root, OAuthReservedClaim.TokenType),
                        JsonUtils.getJsonStringProp(root, OAuthReservedClaim.AccessToken),
                        JsonUtils.getJsonStringProp(root, OAuthReservedClaim.RefreshToken),
                        JsonUtils.getJsonLongProp(root, OAuthReservedClaim.ExpiresOn),
                        JsonUtils.getJsonStringProp(root, OAuthReservedClaim.Resource),
                        UserInfo.parse(JsonUtils.getJsonStringProp(root, OAuthReservedClaim.IdToken)));
                future.set(result);
            } catch (Exception e) {
                future.setException(e);
            } finally {
                try {
                    if (output != null) {
                        output.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException ignored) {
                }
            }
        }

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

    return future;
}