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.microsoft.azure.management.appservice.implementation.FunctionDeploymentSlotImpl.java

public Observable<PublishingProfile> getPublishingProfileAsync() {
    return manager()
            .inner().webApps().listPublishingProfileXmlWithSecretsSlotAsync(resourceGroupName(),
                    this.parent().name(), name(), new CsmPublishingProfileOptionsInner())
            .map(new Func1<InputStream, PublishingProfile>() {
                @Override//from w w w  .  j a  va  2 s  .co  m
                public PublishingProfile call(InputStream stream) {
                    try {
                        String xml = CharStreams.toString(new InputStreamReader(stream));
                        return new PublishingProfileImpl(xml, FunctionDeploymentSlotImpl.this);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
}

From source file:org.eclipse.xtend.core.parser.JFlexGeneratorFragment.java

private String read(final String path) {
    if (path != null) {
        try {/*  ww  w  .  j a v  a  2 s  .  c o  m*/
            InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(path),
                    "ISO-8859-1");
            try {
                String patterns = CharStreams.toString(reader);
                return patterns;
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

From source file:org.languagetool.rules.OpenNMTRule.java

@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
    // TODO: send all sentences at once for less overhead?
    String json = createJson(sentence);
    URL url = new URL(serverUrl);
    HttpURLConnection conn = postToServer(json, url);
    int responseCode = conn.getResponseCode();
    if (responseCode == 200) {
        InputStream inputStr = conn.getInputStream();
        JsonNode response = mapper.readTree(inputStr);
        String translation = response.get(0).get(0).get("tgt").textValue();
        if (translation.contains("<unk>")) {
            throw new RuntimeException(
                    "'<unk>' found in translation - please start the OpenNMT server with the -replace_unk option");
        }//ww w. j  av a 2  s . c  om
        // TODO: whitespace is introduced and needs to be properly removed - we should use the 'src'
        // key for comparison, but we'll still need to clean up when using the suggestion...
        translation = detokenize(translation);
        String cleanTranslation = translation.replaceAll(" ([.,;:])", "$1");
        String sentenceText = sentence.getText();
        if (!cleanTranslation.trim().equals(sentenceText.trim())) {
            List<RuleMatch> ruleMatches = new ArrayList<>();
            int from = getLeftWordBoundary(sentenceText, getFirstDiffPosition(sentenceText, cleanTranslation));
            int to = getRightWordBoundary(sentenceText, getLastDiffPosition(sentenceText, cleanTranslation));
            int replacementTo = getRightWordBoundary(cleanTranslation,
                    getLastDiffPosition(cleanTranslation, sentenceText));
            String message = "OpenNMT suggests that this might(!) be better phrased differently, please check.";
            RuleMatch ruleMatch = new RuleMatch(this, sentence, from, to, message);
            ruleMatch.setSuggestedReplacement(cleanTranslation.substring(from, replacementTo));
            ruleMatches.add(ruleMatch);
            return toRuleMatchArray(ruleMatches);
        }
        return new RuleMatch[0];
    } else {
        InputStream inputStr = conn.getErrorStream();
        String error = CharStreams.toString(new InputStreamReader(inputStr, Charsets.UTF_8));
        throw new RuntimeException("Got error " + responseCode + " from " + url + ": " + error);
    }
}

From source file:tds.shared.spring.interceptors.RestTemplateLoggingInterceptor.java

private void logResponse(final ClientHttpResponse response, final String traceId) {
    String bodyString = "";
    final MediaType contentType = response.getHeaders().getContentType();

    if (contentType != null && contentType.equals(MediaType.APPLICATION_OCTET_STREAM)) {
        bodyString = "<BINARY>";
    } else {/*  www  . j  av a 2  s. c  om*/
        try (final InputStream in = response.getBody()) {
            bodyString = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
        } catch (IOException e) {
            // An IOException will be thrown when the body is zero-length (e.g. a 404 response)
            log.debug("Unable to open response body", e);
        }

        if (!bodyString.isEmpty() && prettyPrintJson
                && contentType.getSubtype().equals(CONTENT_TYPE_SUBTYPE_JSON)) {
            try {
                final Object json = objectMapper.readValue(bodyString, Object.class);
                bodyString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
            } catch (IOException e) {
                log.debug("Unable to parse the response as JSON.", e);
            }
        }
    }

    try {
        log.debug(
                "\n=========================================* RESPONSE *========================================= \n"
                        + " Trace ID    :   {} \n" + " Status Code :   {} \n" + " Status Text :   {} \n"
                        + " Headers     :   {} \n" + " Body        :   {} \n"
                        + "==============================================================================================",
                traceId, response.getStatusCode(), response.getStatusText(), response.getHeaders(),
                bodyString.isEmpty() ? "<no body>" : bodyString);
    } catch (IOException e) {
        log.warn("Exception occurred while logging rest response.", e);
    }
}

From source file:ru.runa.notifier.util.ResourcesManager.java

private static String applyPattern(String pattern) {
    Matcher matcher = VARIABLE_REGEXP.matcher(pattern);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        String name = matcher.group(1);
        String value = PROPERTIES.getStringPropertyNotNull(name);
        if ("server.version".equals(name) && "auto".equals(value)) {
            String versionUrl = getHttpServerUrl() + "/version";
            try {
                InputStreamReader reader = new InputStreamReader(new URL(versionUrl).openStream());
                value = CharStreams.toString(reader);
                int colonIndex = value.indexOf(":");
                if (colonIndex != -1) {
                    value = value.substring(colonIndex + 1);
                }/*  ww  w  .ja va2s . c  o  m*/
                reader.close();
            } catch (Exception e) {
                throw new RuntimeException("Unable to acquire version using " + versionUrl);
            }
        }
        matcher.appendReplacement(buffer, Matcher.quoteReplacement(value));
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:com.google.zxing.web.ChartServlet.java

private static ChartServletRequestParameters doParseParameters(ServletRequest request, boolean readBody)
        throws IOException {

    Preconditions.checkArgument("qr".equals(request.getParameter("cht")), "Bad type");

    String widthXHeight = request.getParameter("chs");
    Preconditions.checkNotNull(widthXHeight, "No size");
    int xIndex = widthXHeight.indexOf('x');
    Preconditions.checkArgument(xIndex >= 0, "Bad size");

    int width = Integer.parseInt(widthXHeight.substring(0, xIndex));
    int height = Integer.parseInt(widthXHeight.substring(xIndex + 1));
    Preconditions.checkArgument(width > 0 && height > 0, "Bad size");
    Preconditions.checkArgument(width <= MAX_DIMENSION && height <= MAX_DIMENSION, "Bad size");

    String outputEncodingName = request.getParameter("choe");
    Charset outputEncoding = StandardCharsets.UTF_8;
    if (outputEncodingName != null) {
        outputEncoding = Charset.forName(outputEncodingName);
        Preconditions.checkArgument(SUPPORTED_OUTPUT_ENCODINGS.contains(outputEncoding), "Bad output encoding");
    }/*from   w w  w . j  a v  a2s  . c o m*/

    ErrorCorrectionLevel ecLevel = ErrorCorrectionLevel.L;
    int margin = 4;

    String ldString = request.getParameter("chld");
    if (ldString != null) {
        int pipeIndex = ldString.indexOf('|');
        if (pipeIndex < 0) {
            // Only an EC level
            ecLevel = ErrorCorrectionLevel.valueOf(ldString);
        } else {
            ecLevel = ErrorCorrectionLevel.valueOf(ldString.substring(0, pipeIndex));
            margin = Integer.parseInt(ldString.substring(pipeIndex + 1));
            Preconditions.checkArgument(margin > 0, "Bad margin");
        }
    }

    String text;
    if (readBody) {
        text = CharStreams.toString(request.getReader());
    } else {
        text = request.getParameter("chl");
    }
    Preconditions.checkArgument(text != null && !text.isEmpty(), "No input");

    return new ChartServletRequestParameters(width, height, outputEncoding, ecLevel, margin, text);
}

From source file:org.openqa.selenium.remote.server.Passthrough.java

@Override
public void handle(HttpRequest req, HttpResponse resp) throws IOException {
    URL target = new URL(upstream.toExternalForm() + req.getUri());
    HttpURLConnection connection = (HttpURLConnection) target.openConnection();
    connection.setInstanceFollowRedirects(true);
    connection.setRequestMethod(req.getMethod().toString());
    connection.setDoInput(true);/*from  w w w .j a v  a  2s . c om*/
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    for (String name : req.getHeaderNames()) {
        if (IGNORED_REQ_HEADERS.contains(name.toLowerCase())) {
            continue;
        }

        for (String value : req.getHeaders(name)) {
            connection.addRequestProperty(name, value);
        }
    }
    // None of this "keep alive" nonsense.
    connection.setRequestProperty("Connection", "close");

    if (POST == req.getMethod()) {
        // We always transform to UTF-8 on the way up.
        String contentType = req.getHeader("Content-Type");
        contentType = contentType == null ? JSON_UTF_8.toString() : contentType;

        MediaType type = MediaType.parse(contentType);
        connection.setRequestProperty("Content-Type", type.withCharset(UTF_8).toString());

        Charset charSet = req.getContentEncoding();

        StringWriter logWriter = new StringWriter();
        try (InputStream is = req.consumeContentStream();
                Reader reader = new InputStreamReader(is, charSet);
                Reader in = new TeeReader(reader, logWriter);
                OutputStream os = connection.getOutputStream();
                Writer out = new OutputStreamWriter(os, UTF_8)) {
            CharStreams.copy(in, out);
        }
        LOG.info("To upstream: " + logWriter.toString());
    }

    resp.setStatus(connection.getResponseCode());
    // clear response defaults.
    resp.setHeader("Date", null);
    resp.setHeader("Server", null);

    connection.getHeaderFields().entrySet().stream()
            .filter(entry -> entry.getKey() != null && entry.getValue() != null)
            .filter(entry -> !IGNORED_REQ_HEADERS.contains(entry.getKey().toLowerCase())).forEach(entry -> {
                entry.getValue().stream().filter(Objects::nonNull)
                        .forEach(value -> resp.addHeader(entry.getKey(), value));
            });
    InputStream in = connection.getErrorStream();
    if (in == null) {
        in = connection.getInputStream();
    }

    String charSet = connection.getContentEncoding() != null ? connection.getContentEncoding() : UTF_8.name();
    try (Reader reader = new InputStreamReader(in, charSet)) {
        String content = CharStreams.toString(reader);
        LOG.info("To downstream: " + content);
        resp.setContent(content.getBytes(charSet));
    } finally {
        in.close();
    }
}

From source file:com.proofpoint.galaxy.coordinator.HttpServiceInventory.java

private List<ServiceDescriptor> getServiceInventory(SlotStatus slotStatus) {
    Assignment assignment = slotStatus.getAssignment();
    if (assignment == null) {
        return null;
    }//from w w w  .  j  av a  2s.  com

    String config = assignment.getConfig();

    File cacheFile = getCacheFile(config);
    if (cacheFile.canRead()) {
        try {
            String json = CharStreams.toString(Files.newReaderSupplier(cacheFile, Charsets.UTF_8));
            List<ServiceDescriptor> descriptors = descriptorsJsonCodec.fromJson(json);
            invalidServiceInventory.remove(config);
            return descriptors;
        } catch (Exception ignored) {
            // delete the bad cache file
            cacheFile.delete();
        }
    }

    InputSupplier<? extends InputStream> configFile = ConfigUtils.newConfigEntrySupplier(repository, config,
            "galaxy-service-inventory.json");
    if (configFile == null) {
        return null;
    }

    try {
        String json;
        try {
            json = CharStreams.toString(CharStreams.newReaderSupplier(configFile, Charsets.UTF_8));
        } catch (FileNotFoundException e) {
            // no service inventory in the config, so replace with json null so caching works
            json = "null";
        }
        invalidServiceInventory.remove(config);

        // cache json
        cacheFile.getParentFile().mkdirs();
        Files.write(json, cacheFile, Charsets.UTF_8);

        List<ServiceDescriptor> descriptors = descriptorsJsonCodec.fromJson(json);
        return descriptors;
    } catch (Exception e) {
        if (invalidServiceInventory.add(config)) {
            log.error(e, "Unable to read service inventory for %s" + config);
        }
    }
    return null;
}

From source file:google.registry.tools.AppEngineConnection.java

@Override
public String send(String endpoint, Map<String, ?> params, MediaType contentType, byte[] payload)
        throws IOException {
    GenericUrl url = new GenericUrl(String.format("%s%s", getServerUrl(), endpoint));
    url.putAll(params);/*  w w  w .j  ava2 s  .c  o m*/
    HttpRequest request = requestFactory.buildPostRequest(url,
            new ByteArrayContent(contentType.toString(), payload));
    HttpHeaders headers = request.getHeaders();
    headers.setCacheControl("no-cache");
    headers.put(X_CSRF_TOKEN, ImmutableList.of(xsrfToken.get()));
    headers.put(X_REQUESTED_WITH, ImmutableList.of("RegistryTool"));
    request.setHeaders(headers);
    request.setFollowRedirects(false);
    request.setThrowExceptionOnExecuteError(false);
    request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {
        @Override
        public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
                throws IOException {
            String errorTitle = extractHtmlTitle(getErrorHtmlAsString(response));
            throw new IOException(String.format("Error from %s: %d %s%s", request.getUrl().toString(),
                    response.getStatusCode(), response.getStatusMessage(),
                    (errorTitle == null ? "" : ": " + errorTitle)));
        }
    });
    HttpResponse response = null;
    try {
        response = request.execute();
        return CharStreams.toString(new InputStreamReader(response.getContent(), UTF_8));
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }
}

From source file:foo.domaintest.action.RequestModule.java

/** Provides the POST body. Note that this consumes the request's input stream. */
@Provides// ww w  .j a va 2s.  com
@RequestData("postBody")
String providePostBody(HttpServletRequest request, @RequestData("charset") String requestCharset) {
    try {
        return CharStreams.toString(request.getReader());
    } catch (IOException e) {
        return "";
    }
}