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.google.cloud.tools.eclipse.appengine.validation.XsltSourceQuickFix.java

/**
 * Applies the provided XSLT style sheet to the {@link IDocument} in the source editor.
 *///from w w w .ja v  a 2 s.c om
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    URL xslt = ApplicationQuickFix.class.getResource(xsltPath);
    IDocument document = viewer.getDocument();
    byte[] bytes = getDocumentBytes(document);
    try (InputStream in = new ByteArrayInputStream(bytes); InputStream stylesheetStream = xslt.openStream()) {
        InputStream transformed = Xslt.applyXslt(in, stylesheetStream);
        String encoding = AbstractXmlSourceValidator.getDocumentEncoding(document);
        String result = CharStreams.toString(new InputStreamReader(transformed, encoding));
        document.set(result);
    } catch (IOException | TransformerException ex) {
        logger.log(Level.SEVERE, ex.getMessage());
    }
}

From source file:org.jahia.modules.saml2.admin.SAML2SettingsAction.java

/**
 *
 * @param request/*from  www . j a  v  a2s.co  m*/
 * @param renderContext
 * @param resource
 * @param session
 * @param parameters
 * @param urlResolver
 * @return
 * @throws Exception
 */
@Override
public ActionResult doExecute(final HttpServletRequest request, final RenderContext renderContext,
        final Resource resource, final JCRSessionWrapper session, Map<String, List<String>> parameters,
        final URLResolver urlResolver) throws Exception {
    try {
        final String responseText = CharStreams.toString(request.getReader());
        final JSONObject settings;
        final SAML2Settings serverSettings;
        final String siteKey = renderContext.getSite().getSiteKey();
        // if payload has content, it means an update.
        if (StringUtils.isNotEmpty(responseText)) {
            settings = new JSONObject(responseText);
            final SAML2Settings oldSettings = saml2SettingsService.getSettings(siteKey);
            final Boolean enabled = getSettingOrDefault(settings, SAML2Constants.ENABLED,
                    (oldSettings != null && oldSettings.getEnabled()));
            final String identityProviderUrl = getSettingOrDefault(settings,
                    SAML2Constants.IDENTITY_PROVIDER_URL,
                    (oldSettings != null ? oldSettings.getIdentityProviderUrl() : ""));
            final String relyingPartyIdentifier = getSettingOrDefault(settings,
                    SAML2Constants.RELYING_PARTY_IDENTIFIER,
                    (oldSettings != null ? oldSettings.getRelyingPartyIdentifier() : ""));
            final String incomingTargetUrl = getSettingOrDefault(settings, SAML2Constants.INCOMING_TARGET_URL,
                    (oldSettings != null ? oldSettings.getIncomingTargetUrl() : ""));
            final String spMetaDataLocation = getSettingOrDefault(settings,
                    SAML2Constants.SP_META_DATA_LOCATION,
                    (oldSettings != null ? oldSettings.getSpMetaDataLocation() : ""));
            final String keyStoreLocation = getSettingOrDefault(settings, SAML2Constants.KEY_STORE_LOCATION,
                    (oldSettings != null ? oldSettings.getKeyStoreLocation() : ""));
            final String keyStorePass = getSettingOrDefault(settings, SAML2Constants.KEY_STORE_PASS,
                    (oldSettings != null ? oldSettings.getKeyStorePass() : ""));
            final String privateKeyPass = getSettingOrDefault(settings, SAML2Constants.PRIVATE_KEY_PASS,
                    (oldSettings != null ? oldSettings.getPrivateKeyPass() : ""));
            if (enabled) {
                serverSettings = saml2SettingsService.setSAML2Settings(siteKey, identityProviderUrl,
                        relyingPartyIdentifier, incomingTargetUrl, spMetaDataLocation, keyStoreLocation,
                        keyStorePass, privateKeyPass);
            } else {
                serverSettings = null;
            }
        } else {
            serverSettings = saml2SettingsService.getSettings(siteKey);
        }

        final JSONObject resp = new JSONObject();
        if (serverSettings != null) {
            resp.put(SAML2Constants.ENABLED, serverSettings.getEnabled());
            resp.put(SAML2Constants.IDENTITY_PROVIDER_URL, serverSettings.getIdentityProviderUrl());
            resp.put(SAML2Constants.RELYING_PARTY_IDENTIFIER, serverSettings.getRelyingPartyIdentifier());
            resp.put(SAML2Constants.INCOMING_TARGET_URL, serverSettings.getIncomingTargetUrl());
            resp.put(SAML2Constants.SP_META_DATA_LOCATION, serverSettings.getSpMetaDataLocation());
            resp.put(SAML2Constants.KEY_STORE_LOCATION, serverSettings.getKeyStoreLocation());
            resp.put(SAML2Constants.KEY_STORE_PASS, serverSettings.getKeyStorePass());
            resp.put(SAML2Constants.PRIVATE_KEY_PASS, serverSettings.getPrivateKeyPass());
        }
        resp.put("noConf", serverSettings == null);
        return new ActionResult(HttpServletResponse.SC_OK, null, resp);
    } catch (Exception e) {
        JSONObject error = new JSONObject();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("error while saving settings", e);
        }
        error.put("error", e.getMessage());
        error.put("type", e.getClass().getSimpleName());
        return new ActionResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, error);
    }
}

From source file:info.magnolia.configuration.app.overview.filebrowser.FileBrowserHelper.java

private FilePopup buildDialog(Reader reader) {
    try {//from  w  w  w .java2s  .co  m
        return new FilePopup(CharStreams.toString(reader));
    } catch (IOException e) {
        return null;
    }
}

From source file:org.jahia.modules.example.settings.SettingsAction.java

/**
 * This method handles saving.//  ww w  .jav a 2  s  .  co  m
 *
 * @param request
 * @param renderContext
 * @param resource
 * @param session
 * @param parameters
 * @param urlResolver
 * @return
 * @throws Exception
 */
@Override
public ActionResult doExecute(final HttpServletRequest request, final RenderContext renderContext,
        final Resource resource, final JCRSessionWrapper session, final Map<String, List<String>> parameters,
        final URLResolver urlResolver) throws Exception {
    try {
        // Get the request chars and set to response text.
        final String responseText = CharStreams.toString(request.getReader());
        final JSONObject settings;
        final Settings serverSettings;
        final String siteKey = renderContext.getSite().getSiteKey();

        // if payload has content, it means an update.
        if (StringUtils.isNotEmpty(responseText)) {
            // Create JSONObject from responseText.
            settings = new JSONObject(responseText);

            // Get the settings from the JCR.
            final Settings oldSettings = settingsService.getSettings(siteKey);

            // Check against the settings from the JCR with the new setting property that has been posted.
            final Boolean enabled = getSettingOrDefault(settings, SettingsConstants.ENABLED,
                    (oldSettings != null && oldSettings.getEnabled()));
            final String settings1 = getSettingOrDefault(settings, SettingsConstants.SETTING_1,
                    (oldSettings != null ? oldSettings.getSetting1() : ""));

            // If service is enabled, then set the settings in the JCR.
            if (enabled) {
                serverSettings = settingsService.setSettings(siteKey, settings1);
            } else {
                serverSettings = null;
            }
        } else {
            serverSettings = settingsService.getSettings(siteKey);
        }

        // Create a JSON object to be returned as a response.
        final JSONObject resp = new JSONObject();
        if (serverSettings != null) {
            resp.put(SettingsConstants.ENABLED, serverSettings.getEnabled());
            resp.put(SettingsConstants.SETTING_1, serverSettings.getSetting1());
        }

        // If no configuration set, then set a variable noConf to true.  This value can be used to display a
        // message to the end user.
        resp.put("noConf", serverSettings == null);
        return new ActionResult(HttpServletResponse.SC_OK, null, resp);
    } catch (Exception e) {
        final JSONObject error = new JSONObject();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("error while saving settings", e);
        }
        // Set the error type and message as a response.
        error.put("error", e.getMessage());
        error.put("type", e.getClass().getSimpleName());
        return new ActionResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, error);
    }
}

From source file:de.ailis.maven.plugin.javascript.SuppressedCodeGenerator.java

/**
 * Constructs a suppressed code generator reading the source code from the specified input stream. The stream is NOT
 * closed automatically by this class and must be closed manually (You can do this right after calling this
 * constructor).//w  w  w. j av a2s . co m
 *
 * @param stream
 *            The input stream. Must be closed manually.
 * @throws IOException
 *             When stream read failed.
 */
public SuppressedCodeGenerator(final InputStream stream) throws IOException {
    this.origCode = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
}

From source file:com.google.eclipse.mechanic.samples.ShowViewScanner.java

public void processTaskRef(TaskCollector collector, IResourceTaskReference taskRef) {
    try {//  w w  w .  ja v  a2  s .com
        InputStream inputStream = taskRef.newInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream, Charsets.UTF_8);
        String inputText = CharStreams.toString(reader);
        // This example doesn't deal with Windows newlines.
        List<String> list = Lists.newArrayList();
        for (String line : Splitter.on("\n").split(inputText)) {
            line = line.trim();
            if (line.startsWith("#") || line.length() == 0) {
                continue;
            }
            list.add(line);
        }
        collector.collect(new ShowViewTask(taskRef.getName(), list));
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Can't process task " + taskRef, e);
    } catch (RuntimeException e) {
        LOG.log(Level.SEVERE, "Can't process task " + taskRef, e);
    }
}

From source file:org.jclouds.examples.glacier.MainApp.java

private static void putAndRetrieveBlobExample(BlobStore blobstore) throws IOException {
    // Create a container
    String containerName = "jclouds_putAndRetrieveBlobExample_" + UUID.randomUUID().toString();
    blobstore.createContainerInLocation(null, containerName); // Create a vault

    // Create a blob
    ByteSource payload = ByteSource.wrap("data".getBytes(Charsets.UTF_8));
    Blob blob = blobstore.blobBuilder("ignored") // The blob name is ignored in Glacier
            .payload(payload).contentLength(payload.size()).build();

    // Put the blob in the container
    String blobId = blobstore.putBlob(containerName, blob);

    // Retrieve the blob
    Blob result = blobstore.getBlob(containerName, blobId);

    // Print the result
    InputStream is = result.getPayload().openStream();
    try {//from w w  w.j  av a  2 s .  c o m
        String data = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
        System.out.println("The retrieved payload is: " + data);
    } finally {
        is.close();
    }
}

From source file:org.robotframework.ide.eclipse.main.plugin.refactoring.RedXmlEditsCollector.java

List<TextEdit> collectEditsInMovedLibraries(final String projectName, final IFile redXmlFile) {
    try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(redXmlFile.getContents()))) {

        final IDocument document = new Document(CharStreams.toString(fileReader));
        return collectEditsInMovedLibraries(projectName, new MatchesInDocumentEngine(document));
    } catch (IOException | CoreException e) {
        return new ArrayList<>();
    }//from w w  w  .j a  v  a2 s. c om
}

From source file:uk.co.flax.luwak.demo.LuwakDemo.java

static List<InputDocument> buildDocs(String inputDirectory) throws Exception {
    List<InputDocument> docs = new ArrayList<>();
    logger.info("Reading documents from {}", inputDirectory);
    for (Path filePath : Files.newDirectoryStream(FileSystems.getDefault().getPath(inputDirectory))) {
        String content;/*w ww .  j av  a 2s .  c o  m*/
        try (FileInputStream fis = new FileInputStream(filePath.toFile());
                InputStreamReader reader = new InputStreamReader(fis, Charsets.UTF_8)) {
            content = CharStreams.toString(reader);
            InputDocument doc = InputDocument.builder(filePath.toString())
                    .addField(FIELD, content, new StandardAnalyzer()).build();
            docs.add(doc);
        }
    }
    return docs;
}

From source file:de.ii.xtraplatform.ogc.api.gml.parser.OGCEntityResolver.java

@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    // TODO: temporary basic auth hack
    // protected schema files
    if (systemId != null && systemId.startsWith("https://") && useBasicAuth) {
        HttpResponse response = null;//from   ww w. j av a2  s .co  m
        LOGGER.debug("resolving protected schema: {}", systemId);
        try {
            HttpGet httpGet = new HttpGet(systemId);

            String basic_auth = new String(Base64.encodeBase64((user + ":" + password).getBytes()));
            httpGet.addHeader("Authorization", "Basic " + basic_auth);

            response = untrustedSslHttpClient.execute(httpGet, new BasicHttpContext());
            String stringFromStream = CharStreams
                    .toString(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            InputSource is = new InputSource(new StringReader(stringFromStream));
            is.setSystemId(systemId);

            return is;

        } catch (IOException ex) {
            ex.printStackTrace();
            LOGGER.error("Error parsing application schema. {}", ex);
            throw new SchemaParseException("Error parsing application schema. {}", ex.getMessage());
        } finally {
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
            }
        }
    }

    //LOGGER.info(" --- {} --- {} ", systemId, publicId);
    if (publicId != null && publicId.equals("http://www.opengis.net/gml")) {
        if (!isAvailable(systemId)) {
            return new InputSource("http://schemas.opengis.net/gml/3.1.1/base/gml.xsd");
        }
    }
    if (publicId != null && publicId.equals("http://www.opengis.net/gml/3.2")) {
        if (!isAvailable(systemId)) {
            return new InputSource("http://schemas.opengis.net/gml/3.2.1/gml.xsd");
        }
    }
    if (publicId != null && publicId.equals("http://www.w3.org/1999/xlink")) {
        if (!isAvailable(systemId)) {
            return new InputSource("http://www.w3.org/1999/xlink.xsd");
        }
    }

    if (publicId != null && publicId.equals("http://www.aixm.aero/schema/5.1")) {
        if (!isAvailable(systemId)) {
            return new InputSource("http://www.aixm.aero/gallery/content/public/schema/5.1/AIXM_Features.xsd");
        }
    }

    if (systemId != null) {
        // Workaround for broken Schema in dwd-WFS
        if (systemId.endsWith("gml.xsd") && systemId.contains("kunden.dwd.de")) {
            return new InputSource("http://schemas.opengis.net/gml/3.2.1/gml.xsd");
        }

        /*if (systemId.endsWith("basicTypes.xsd") && redirect.contains("http://www.opengis.net/gml/3.2")) {
         return new InputSource("http://schemas.opengis.net/gml/3.2.1/basicTypes.xsd");
         }
                
         if (systemId.endsWith("xlinks.xsd") && redirect.contains("http://www.w3.org/1999/xlink")) {
         return new InputSource("http://www.w3.org/1999/xlink.xsd");
         }*/
        // workaround for A4I DescribeFeatureType (seen in 10.2.1)
        // also occurs with native XtraServer, moved to general workarounds
        if (publicId == null
                && systemId.contains("&REQUEST=DescribeFeatureType&TYPENAMES=ns:AbstractFeature")) {
            return createFakeSchema("http://www.opengis.net/gml/3.2");
        }

        // A4I workarounds
        if (systemId.contains("/exts/InspireFeatureDownload/service")) {
            String url = systemId;
            // workaround for A4I 10.1 SP1 (Patch1) blank encoding bug in GET parameters
            if (url.contains("OUTPUT_FORMAT=")) {
                int start = url.indexOf("OUTPUT_FORMAT=") + 13;
                int end = url.indexOf("&", start);
                String out = url.substring(start, end).replaceAll("%20", "");
                url = url.substring(0, start) + out + url.substring(end);
            }

            if (!url.equals(systemId)) {
                LOGGER.debug("original systemId: {}", systemId);
                LOGGER.debug("changed systemId: {}", url);
                return new InputSource(url);
            }
        }
    }

    // ignore multiple imports into the same namespace
    if (publicId != null) {
        if (!uris.containsKey(publicId)) {
            uris.put(publicId, systemId);
        }
        if (systemId != null && !systemId.equals(uris.get(publicId))) {
            return createFakeSchema(publicId);
        }
    }

    return null;
}