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.reprezen.swagedit.utils.DocumentUtils.java

/**
 * Returns the swagger document if exists for the given path.
 * /*w  ww . ja va  2  s. c  o m*/
 * @param path
 * @return document
 */
public static SwaggerDocument getDocument(IPath path) {
    if (path == null || !path.getFileExtension().matches("ya?ml")) {
        return null;
    }

    InputStream content = null;
    IFile file = getWorkspaceFile(path);
    if (file == null) {
        IFileStore store = getExternalFile(path);
        if (store != null) {
            try {
                content = store.openInputStream(EFS.NONE, null);
            } catch (CoreException e) {
                content = null;
            }
        }
    } else if (file.exists()) {
        try {
            content = file.getContents();
        } catch (CoreException e) {
            content = null;
        }
    }

    if (content == null) {
        return null;
    }

    SwaggerDocument doc = new SwaggerDocument();
    try {
        doc.set(CharStreams.toString(new InputStreamReader(content)));
    } catch (IOException e) {
        return null;
    }

    return doc;
}

From source file:org.hawkular.metrics.schema.SchemaManager.java

public void createSchema(String keyspace) throws IOException {
    logger.info("Creating schema for keyspace " + keyspace);

    ResultSet resultSet = session
            .execute("SELECT * FROM system.schema_keyspaces WHERE keyspace_name = '" + keyspace + "'");
    if (!resultSet.isExhausted()) {
        logger.info("Schema already exist. Skipping schema creation.");
        return;// w  w w  .j a  v a 2  s. c om
    }

    ImmutableMap<String, String> schemaVars = ImmutableMap.of("keyspace", keyspace);

    try (InputStream inputStream = getClass().getResourceAsStream("/schema.cql");
            InputStreamReader reader = new InputStreamReader(inputStream)) {
        String content = CharStreams.toString(reader);

        for (String cql : content.split("(?m)^-- #.*$")) {
            if (!cql.startsWith("--")) {
                String updatedCQL = substituteVars(cql.trim(), schemaVars);
                logger.info("Executing CQL:\n" + updatedCQL + "\n");
                session.execute(updatedCQL);
            }
        }
    }
}

From source file:io.soabase.example.hello.HelloResourceApache.java

@GET
public String getHello(@Context HttpHeaders headers) throws Exception {
    String result = "Service Name: " + info.getServiceName() + "\nInstance Name: " + info.getInstanceName()
            + "\nRequest Id: " + SoaRequestId.get(headers) + "\n";

    URI uri = new URIBuilder().setHost(ClientUtils.serviceNameToHost("goodbye")).setPath("/goodbye").build();
    HttpGet get = new HttpGet(uri);
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override/*from   www . j a va2 s  . com*/
        public String handleResponse(HttpResponse response) throws IOException {
            return CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
        }
    };
    String value = client.execute(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), get,
            responseHandler);
    return result + "\nGoodbye app says: \n\t" + value;
}

From source file:com.github.tomakehurst.wiremock.servlet.HttpServletRequestAdapter.java

@Override
public String getBodyAsString() {
    if (cachedBody == null) {
        try {//ww w. j  a va  2s  . co m
            cachedBody = CharStreams.toString(request.getReader());
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    return cachedBody;
}

From source file:co.cask.cdap.shell.CLIConfig.java

private static String tryGetVersion() {
    try {//from  w  w  w .j a va2 s . co  m
        InputSupplier<? extends InputStream> versionFileSupplier = new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return VersionCommand.class.getClassLoader().getResourceAsStream("VERSION");
            }
        };
        return CharStreams.toString(CharStreams.newReaderSupplier(versionFileSupplier, Charsets.UTF_8));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.notifier.desktop.view.LicenseDialog.java

public void open() {
    try {//  ww  w.j av  a 2  s .co m
        Shell parent = getParent();
        dialogShell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);

        dialogShell.setLayout(new FormLayout());
        dialogShell.layout();
        dialogShell.pack();
        dialogShell.setSize(403, 353);
        dialogShell.setText("License");

        licenseTextArea = new Text(dialogShell, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
        FormData licenseTextAreaLData = new FormData();
        licenseTextAreaLData.left = new FormAttachment(0, 1000, 12);
        licenseTextAreaLData.top = new FormAttachment(0, 1000, 12);
        licenseTextAreaLData.bottom = new FormAttachment(1000, 1000, -12);
        licenseTextAreaLData.right = new FormAttachment(1000, 1000, -12);
        licenseTextArea.setLayoutData(licenseTextAreaLData);
        String license = "Copyright (c) 2010, Leandro Aparecido\nAll rights reserved.\n\n";
        try {
            license += CharStreams.toString(new InputSupplier<InputStreamReader>() {
                @Override
                public InputStreamReader getInput() throws IOException {
                    return new InputStreamReader(Application.class.getResourceAsStream(Application.LICENSE));
                }
            });
        } catch (IOException e) {
            logger.error("Could not load license");
        }
        licenseTextArea.setText(license);
        licenseTextArea.setBounds(12, 12, 256, 168);
        licenseTextArea.setEditable(false);

        Dialogs.centerDialog(dialogShell);
        dialogShell.open();
        Dialogs.bringToForeground(dialogShell);
    } catch (Exception e) {
        logger.error("Error showing license dialog", e);
    }
}

From source file:tech.tablesaw.io.fixed.FixedWidthReader.java

/**
 * Determines column types if not provided by the user
 * Reads all input into memory unless File was provided
 *//*w w  w . j  a v  a  2 s . c o  m*/
private Pair<Reader, ColumnType[]> getReaderAndColumnTypes(FixedWidthReadOptions options) throws IOException {
    ColumnType[] types = options.columnTypes();
    byte[] bytesCache = null;

    if (types == null) {
        Reader reader = options.source().createReader(bytesCache);
        if (options.source().file() == null) {
            bytesCache = CharStreams.toString(reader).getBytes();
            // create a new reader since we just exhausted the existing one
            reader = options.source().createReader(bytesCache);
        }
        types = detectColumnTypes(reader, options);
    }

    return Pair.create(options.source().createReader(bytesCache), types);
}

From source file:com.googlesource.gerrit.plugins.its.base.workflow.AddSoyComment.java

private String soyTemplate(SoyFileSet.Builder builder, String template, SanitizedContent.ContentKind kind,
        Map<String, String> properties) {
    Path templatePath = templateDir.resolve(template + ".soy");
    String content;/*  w w  w . j  ava  2 s .  co  m*/

    try (Reader r = Files.newBufferedReader(templatePath, StandardCharsets.UTF_8)) {
        content = CharStreams.toString(r);
    } catch (IOException err) {
        throw new ProvisionException("Failed to read template file " + templatePath.toAbsolutePath().toString(),
                err);
    }

    builder.add(content, templatePath.toAbsolutePath().toString());
    SoyTofu.Renderer renderer = builder.build().compileToTofu().newRenderer("etc.its.templates." + template)
            .setContentKind(kind).setData(properties);
    return renderer.render();
}

From source file:br.com.objectos.way.core.code.jdt.AstReaderResource.java

@Override
void setSource(ASTParser parser) throws Exception {
    String name = resourceName.substring(resourceName.lastIndexOf('/'));
    parser.setUnitName(name);//w  w w . j ava2s .c  o  m

    URL url = Resources.getResource(getClass(), resourceName);
    Reader reader = Resources.asCharSource(url, Charsets.UTF_8).openStream();
    String source = CharStreams.toString(reader);
    char[] chars = source.toCharArray();
    parser.setSource(chars);
}

From source file:com.google.dart.tools.ui.internal.intro.IntroEditor.java

/**
 * Reads the existing text file with give name in the package of {@link IntroEditor}.
 *///from w w w .  ja v a  2 s.  com
private static String readTemplate(String name) throws IOException {
    InputStream welcomeStream = IntroEditor.class.getResourceAsStream(name);
    try {
        return CharStreams.toString(new InputStreamReader(welcomeStream));
    } finally {
        Closeables.closeQuietly(welcomeStream);
    }
}