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.openqa.selenium.remote.server.NewSessionPayload.java

public NewSessionPayload(long size, Reader source) throws IOException {
    Sources sources;//  w w w .  j  a v a  2  s .co  m
    if (size > THRESHOLD || Runtime.getRuntime().freeMemory() < size) {
        this.root = Files.createTempDirectory("new-session");
        sources = diskBackedSource(source);
    } else {
        this.root = null;
        sources = memoryBackedSource(
                new JsonToBeanConverter().convert(Map.class, CharStreams.toString(source)));
    }

    validate(sources);
    this.sources = rewrite(sources);
}

From source file:com.google.gxp.compiler.fs.FileRef.java

public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
    return CharStreams.toString(openReader(ignoreEncodingErrors));
}

From source file:edu.washington.cs.cupid.usage.preferences.UsagePreferencePage.java

@Override
protected Control createContents(Composite parent) {

    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    GridLayout layout = new GridLayout();
    layout.numColumns = 2;/* w  w  w. j a v  a2  s.  co  m*/
    composite.setLayout(layout);

    Link surveyLink = new Link(composite, SWT.LEFT);
    surveyLink.setText("Help improve Cupid by completing a short survey: <a href=\""
            + SurveyDialog.DEV_SURVEY_URL + "\">Open in Browser.</a>");

    GridData dSurvey = new GridData(SWT.FILL, SWT.NONE, true, false);
    dSurvey.horizontalSpan = 2;
    surveyLink.setLayoutData(dSurvey);

    enabled = new Button(composite, SWT.CHECK);
    enabled.setText("Enable Cupid Data Reporting");
    enabled.setSelection(preferences.getBoolean(PreferenceConstants.P_ENABLE_COLLECTION));

    Button delete = new Button(composite, SWT.PUSH);
    delete.setText("Erase Workspace Usage Data");

    surveyLink.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                //  Open default external browser 
                PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text));
            } catch (Exception ex) {
                Activator.getDefault().logError("Error loading Cupid survey in browser", ex);
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            //NOP
        }
    });

    tabs = new TabFolder(composite, SWT.BOTTOM);
    consentTab = new TabItem(tabs, SWT.NONE);
    consentTab.setText("Consent Agreement");

    Browser consentText = new Browser(tabs, SWT.BORDER);

    try {
        Bundle bundle = Activator.getDefault().getBundle();
        URL fileURL = bundle.getEntry(CONSENT_AGREEMENT_PATH);

        if (fileURL == null) {
            throw new RuntimeException("Unable to locate consent agreement at " + CONSENT_AGREEMENT_PATH);
        }

        InputStream inputStream = fileURL.openStream();
        String content = CharStreams.toString(new InputStreamReader(inputStream, Charset.forName("UTF-8")));

        consentText.setText(content);
    } catch (Exception ex) {
        consentText.setText("Error loading consent form: " + ex.getLocalizedMessage());
    }

    consentTab.setControl(consentText);

    dataTab = new TabItem(tabs, SWT.NONE);
    dataTab.setText("Workspace Data Preview");

    session = new Text(tabs, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    session.setEditable(false);
    updatePreview();
    dataTab.setControl(session);

    GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
    data.horizontalSpan = 2;
    data.heightHint = 350;
    data.widthHint = 400;
    tabs.setLayoutData(data);

    delete.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            boolean confirm = MessageDialog.openConfirm(UsagePreferencePage.this.getShell(),
                    "Delete Workspace Cupid Usage Data?",
                    "Are you sure you want to delete the Cupid usage data stored for this workspace?");

            if (confirm) {
                Activator.getDefault().getCollector().deleteLocalData();
                updatePreview();
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            // NO OP
        }
    });

    return null;
}

From source file:com.googlecode.efactory.tests.util.ResourceProvider.java

public String loadAsStringFromURI(URI uri) throws IOException {
    URIConverter uriConverter = rs.getURIConverter();
    InputStream is = uriConverter.createInputStream(uri);
    String content = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
    Closeables.closeQuietly(is);//from  w w w  .j  a v a  2s  .c  o  m
    return content;
}

From source file:org.eclipse.emf.eson.tests.util.ResourceProvider.java

public String loadAsStringFromURI(URI uri) throws IOException {
    URIConverter uriConverter = rs.getURIConverter();
    Closer closer = Closer.create(); // https://code.google.com/p/guava-libraries/wiki/ClosingResourcesExplained
    try {// ww  w  .j ava  2 s  . co m
        InputStream is = closer.register(uriConverter.createInputStream(uri));
        String content = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
        return content;
    } catch (Throwable e) { // must catch Throwable
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:co.cask.cdap.client.rest.RestClient.java

/**
 * Utility method for converting {@link org.apache.http.HttpEntity} HTTP entity content to String.
 *
 * @param httpEntity {@link org.apache.http.HttpEntity}
 * @return {@link String} generated from input content stream
 * @throws IOException if HTTP entity is not available
 *//*from www  .ja  va  2 s  . c  o m*/
public static String toString(HttpEntity httpEntity) throws IOException {
    if (httpEntity == null || httpEntity.getContent() == null) {
        throw new IOException("Empty HttpEntity is received.");
    }
    Charset charset = Charsets.UTF_8;
    ContentType contentType = ContentType.get(httpEntity);
    if (contentType != null && contentType.getCharset() != null) {
        charset = contentType.getCharset();
    }
    Reader reader = new InputStreamReader(httpEntity.getContent(), charset);
    try {
        return CharStreams.toString(reader);
    } finally {
        reader.close();
    }
}

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

/**
 * <p>//  w  ww. ja  v a  2 s.c o  m
 * Method to generate Response AS a {@link String} value.
 * </p>
 *
 * @return {@link String}
 * @throws Exception
 */
@Override
public String getResponseAsString() throws Exception {
    HttpUriRequest httpMethod = this.prepareHttpMethod();
    httpMethod.addHeader("Content-Type", "application/json");
    logger.debug("#############################Executing -------------> {}\n", httpMethod.getURI().toString());
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpMethod);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    logger.debug("###############################STATUS_CODE : {} for Request : {}\n", statusCode,
            this.getClass().getSimpleName());
    this.checkHttpResponseStatus(statusCode);
    HttpEntity responseEntity = httpResponse.getEntity();
    try {
        if (responseEntity != null) {
            return CharStreams.toString(new InputStreamReader(responseEntity.getContent(), UTF_8));
        } else {
            throw new IncorrectResponseException(CONNECTION_PROBLEM_MESSAGE);
        }
    } finally {
        consume(responseEntity);
        httpResponse.close();
    }
}

From source file:com.notifier.desktop.os.OperatingSystems.java

private static File getWindowsStartupDirFromRegistry() {
    try {//from   w w w.  j a  va  2s. c  om
        ProcessBuilder builder = new ProcessBuilder("reg", "query",
                "\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"", "/v",
                "Startup");
        final Process process = builder.start();
        String result = CharStreams.toString(new InputSupplier<InputStreamReader>() {
            @Override
            public InputStreamReader getInput() throws IOException {
                return new InputStreamReader(process.getInputStream());
            }
        });
        String startupDirName = result.substring(result.indexOf("REG_SZ") + 6).trim();
        return new File(startupDirName);
    } catch (Exception e) {
        return null;
    }
}

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

/**
 * Invoke REST Service using GET method.
 *
 * @param urlStr// w  w  w .j ava 2  s  .  c  o  m
 *         the REST service URL String.
 * @return
 *         the HttpResponse.
 * @throws IOException
 */
public static HttpResponse getJson(String urlStr) throws IOException {
    URL url = new URL(urlStr);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.addRequestProperty("Accept", "application/json");

    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:io.prestosql.plugin.kafka.KafkaSplitManager.java

private static String readSchema(String dataSchemaLocation) {
    InputStream inputStream = null;
    try {//from  w w  w .j  a va2s.  c  o m
        if (isURI(dataSchemaLocation.trim().toLowerCase(ENGLISH))) {
            try {
                inputStream = new URL(dataSchemaLocation).openStream();
            } catch (MalformedURLException e) {
                // try again before failing
                inputStream = new FileInputStream(dataSchemaLocation);
            }
        } else {
            inputStream = new FileInputStream(dataSchemaLocation);
        }
        return CharStreams.toString(new InputStreamReader(inputStream, UTF_8));
    } catch (IOException e) {
        throw new PrestoException(GENERIC_INTERNAL_ERROR,
                "Could not parse the Avro schema at: " + dataSchemaLocation, e);
    } finally {
        closeQuietly(inputStream);
    }
}