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:org.jclouds.snia.cdmi.v1.options.CreateDataObjectOptions.java

/**
 * Create CDMI data object with InputStream value
 * // ww  w .j  av  a2 s.c  om
 * @param value
 *           InputSteam InputSteam is converted to a String value with charset UTF_8
 * @return CreateDataObjectOptions
 */
public CreateDataObjectOptions value(InputStream value) throws IOException {
    jsonObjectBody.addProperty("value",
            (value == null) ? "" : CharStreams.toString(new InputStreamReader(value, Charsets.UTF_8)));
    this.payload = jsonObjectBody.toString();
    return this;
}

From source file:co.cask.hydrator.plugin.realtime.HTTPPollerRealtimeSource.java

@Nullable
@Override//from  www  . j  a v  a2  s.c o m
public SourceState poll(Emitter<StructuredRecord> writer, SourceState currentState) throws Exception {
    byte[] lastPollTimeBytes = currentState.getState(POLL_TIME_STATE_KEY);
    if (lastPollTimeBytes != null) {
        long lastPollTime = Bytes.toLong(lastPollTimeBytes);
        long currentPollTime = System.currentTimeMillis();
        long diffInSeconds = (currentPollTime - lastPollTime) / 1000;
        if (config.getInterval() - diffInSeconds > 0) {
            // This is a little bit of a workaround since clicking the stop button
            // in the UI will not interrupt a sleep. See: CDAP-5631
            TimeUnit.SECONDS.sleep(1L);
            return currentState;
        }
    }
    try {
        URL url = new URL(config.getUrl());
        String response = "";
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(METHOD);
        connection.setConnectTimeout(config.getConnectTimeout());
        connection.setReadTimeout(config.getReadTimeout());
        connection.setInstanceFollowRedirects(config.shouldFollowRedirects());
        // Set additional request headers
        for (Map.Entry<String, String> requestHeader : config.getRequestHeadersMap().entrySet()) {
            connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue());
        }
        int responseCode = connection.getResponseCode();
        try {
            if (connection.getErrorStream() != null) {
                try (Reader reader = new InputStreamReader(connection.getErrorStream(), config.getCharset())) {
                    response = CharStreams.toString(reader);
                }
            } else if (connection.getInputStream() != null) {
                try (Reader reader = new InputStreamReader(connection.getInputStream(), config.getCharset())) {
                    response = CharStreams.toString(reader);
                }
            }
        } finally {
            connection.disconnect();
        }

        Map<String, List<String>> headers = connection.getHeaderFields();
        Map<String, String> flattenedHeaders = new HashMap<>();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            if (!Strings.isNullOrEmpty(entry.getKey())) {
                // If multiple values for the same header exist, concatenate them
                flattenedHeaders.put(entry.getKey(), Joiner.on(',').skipNulls().join(entry.getValue()));
            }
        }
        writer.emit(createStructuredRecord(response, flattenedHeaders, responseCode));
    } finally {
        currentState.setState(POLL_TIME_STATE_KEY, Bytes.toBytes(System.currentTimeMillis()));
    }
    return currentState;
}

From source file:com.github.sdbg.core.test.util.PlainTestProject.java

/**
 * @return the {@link String} content of the {@link IFile} with given path.
 *//*from ww w  .j  a  v a 2  s.  co  m*/
public String getFileString(String path) throws Exception {
    IFile file = getFile(path);
    Reader reader = new InputStreamReader(file.getContents(), file.getCharset());
    try {
        return CharStreams.toString(reader);
    } finally {
        reader.close();
    }
}

From source file:com.palantir.typescript.preferences.TsConfigPreferences.java

public boolean reloadTsConfigFile() {
    logInfo("reload tsconfig file");

    this.preferenceValues = Maps.newHashMap();

    IFile tsConfigFile = null;/*  w  w w  . ja  v a 2 s.c  o m*/
    InputStream tsConfigStream = null;
    boolean loaded = false;
    try {
        tsConfigFile = getTsConfigFile();
        if (tsConfigFile.exists()) {

            if (!tsConfigFile.isSynchronized(IResource.DEPTH_ZERO)) {
                tsConfigFile.refreshLocal(IResource.DEPTH_ZERO, null);
            }

            // refresh tsconfig cache infos
            IEclipsePreferences projectPreferences = this.getProjectPreferences();
            projectPreferences.put(IPreferenceConstants.PREFERENCE_STORE_TS_CONFIG_HASH,
                    getFileSHA1(tsConfigFile));
            projectPreferences.putLong(IPreferenceConstants.PREFERENCE_STORE_TS_CONFIG_LAST_MODIFICATION_TIME,
                    tsConfigFile.getModificationStamp());

            // read tsconfig JSON content
            tsConfigStream = tsConfigFile.getContents();
            String tsConfigContent = CharStreams
                    .toString(new InputStreamReader(tsConfigStream, tsConfigFile.getCharset()));

            // convert tsconfig JSON to Map
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> tsConfigEntries = mapper.readValue(tsConfigContent,
                    new TypeReference<Map<String, Object>>() {
                    });

            // resets preferences to default
            resetTsConfigDefaultPreferences();

            // reads preferences from tsconfig
            decodeTsConfigEntries("", tsConfigEntries);

            loaded = true;
        }

    } catch (Exception e) {
        logError("Cannot reload ts config file '" + tsConfigFile + "'", e);
    } finally {
        if (tsConfigStream != null) {
            try {
                tsConfigStream.close();
            } catch (IOException e) {
                System.err.println("error while releasing tsconfig stream");
            }
        }
    }

    return loaded;
}

From source file:foo.domaintest.http.HttpApiModule.java

@Provides
@Singleton/*from  ww  w  .  ja  va  2  s. c  o m*/
Multimap<String, String> provideParameterMap(@RequestData("queryString") String queryString,
        @RequestData("postBody") Lazy<String> lazyPostBody, @RequestData("charset") String requestCharset,
        FileItemIterator multipartIterator) {
    // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If
    // we got the "postpayload" param we don't want to parse the body, so use only the query params.
    // Note that specifying both "payload" and "postpayload" will result in the "payload" param
    // being honored and the POST body being completely ignored.
    ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>();
    Multimap<String, String> getParams = parseQuery(queryString);
    params.putAll(getParams);
    if (getParams.containsKey("postpayload")) {
        // Treat the POST body as if it was the "payload" param.
        return params.put("payload", nullToEmpty(lazyPostBody.get())).build();
    }
    // No "postpayload" so it's safe to consume the POST body and look for params there.
    if (multipartIterator == null) { // Handle GETs and form-urlencoded POST requests.
        params.putAll(parseQuery(nullToEmpty(lazyPostBody.get())));
    } else { // Handle multipart/form-data requests.
        try {
            while (multipartIterator != null && multipartIterator.hasNext()) {
                FileItemStream item = multipartIterator.next();
                try (InputStream stream = item.openStream()) {
                    params.put(item.isFormField() ? item.getFieldName() : item.getName(),
                            CharStreams.toString(new InputStreamReader(stream, requestCharset)));
                }
            }
        } catch (FileUploadException | IOException e) {
            // Ignore the failure and fall through to return whatever params we managed to parse.
        }
    }
    return params.build();
}

From source file:org.renjin.cran.PackageDescription.java

public static PackageDescription fromReader(Reader reader) throws IOException {
    return fromString(CharStreams.toString(reader));
}

From source file:com.cisco.oss.foundation.directory.utils.HttpUtils.java

/**
 * Invoke REST Service using PUT method.
 *
 * It accepts the JSON message./*from www . j  a v a  2  s  .  c o  m*/
 *
 * @param urlStr
 *         the REST Service URL String.
 * @param body
 *         the Http Body String.
 * @param headers
 *         the Http header Map.
 * @return
 *         the HttpResponse.
 * @throws IOException
 */
public static HttpResponse put(String urlStr, String body, Map<String, String> headers) throws IOException {
    URL url = new URL(urlStr);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.addRequestProperty("Accept", "application/json");

    urlConnection.setRequestMethod("PUT");
    if (headers != null && headers.size() > 0) {
        for (Entry<String, String> entry : headers.entrySet()) {
            urlConnection.addRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    if (body != null && body.length() > 0)
        urlConnection.addRequestProperty("Content-Length", Integer.toString(body.length()));
    else
        urlConnection.addRequestProperty("Content-Length", "0");
    urlConnection.setDoOutput(true);

    OutputStream out = urlConnection.getOutputStream();
    if (body != null && body.length() > 0)
        ByteStreams.copy(new ByteArrayInputStream(body.getBytes()), out);

    BufferedReader in = null;
    try {
        int errorCode = urlConnection.getResponseCode();
        if ((errorCode <= 202) && (errorCode >= 200)) {
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        } else {
            InputStream error = urlConnection.getErrorStream();
            if (error != null) {
                in = new BufferedReader(new InputStreamReader(error));
            }
        }

        String json = null;
        if (in != null) {
            json = CharStreams.toString(in);
        }
        return new HttpResponse(errorCode, json);
    } finally {
        if (in != null) {
            in.close();
        }
    }

}

From source file:org.lightjason.agentspeak.action.buildin.rest.IBaseRest.java

/**
 * creates a HTTP connection and reads the data
 *
 * @param p_url url//from   ww  w . j a v  a2  s.  com
 * @return url data
 *
 * @throws IOException is thrown on connection errors
 */
private static String httpdata(final String p_url) throws IOException {
    final HttpURLConnection l_connection = (HttpURLConnection) new URL(p_url).openConnection();

    // follow HTTP redirects
    l_connection.setInstanceFollowRedirects(true);

    // set a HTTP-User-Agent if not exists
    l_connection.setRequestProperty("User-Agent",
            (System.getProperty("http.agent") == null) || (System.getProperty("http.agent").isEmpty())
                    ? CCommon.PACKAGEROOT + CCommon.configuration().getString("version")
                    : System.getProperty("http.agent"));

    // read stream data
    final InputStream l_stream = l_connection.getInputStream();
    final String l_return = CharStreams.toString(new InputStreamReader(l_stream,
            (l_connection.getContentEncoding() == null) || (l_connection.getContentEncoding().isEmpty())
                    ? Charsets.UTF_8
                    : Charset.forName(l_connection.getContentEncoding())));
    Closeables.closeQuietly(l_stream);

    return l_return;
}

From source file:org.kurento.jsonrpc.internal.http.JsonRpcHttpRequestHandler.java

/**
 *
 * @param request//from   w w  w. j a v  a  2s . com
 * @return
 * @throws IOException
 */
private String getBodyAsString(final HttpServletRequest request) throws IOException {
    return CharStreams.toString(request.getReader());
}

From source file:graphql.servlet.GraphQLServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    GraphQLContext context = createContext(Optional.of(req), Optional.of(resp));
    String path = req.getPathInfo();
    if (path == null) {
        path = req.getServletPath();//w  w  w . j  a va 2s.  c om
    }
    if (path.contentEquals("/schema.json")) {
        query(CharStreams.toString(
                new InputStreamReader(GraphQLServlet.class.getResourceAsStream("introspectionQuery"))), null,
                new HashMap<>(), getSchema(), req, resp, context);
    } else {
        if (req.getParameter("q") != null) {
            query(req.getParameter("q"), null, new HashMap<>(), getReadOnlySchema(), req, resp, context);
        } else if (req.getParameter("query") != null) {
            Map<String, Object> variables = new HashMap<>();
            if (req.getParameter("variables") != null) {
                variables.putAll(new ObjectMapper().readValue(req.getParameter("variables"),
                        new TypeReference<Map<String, Object>>() {
                        }));
            }
            String operationName = null;
            if (req.getParameter("operationName") != null) {
                operationName = req.getParameter("operationName");
            }
            query(req.getParameter("query"), operationName, variables, getReadOnlySchema(), req, resp, context);
        }
    }
}