Example usage for com.google.common.io CharStreams copy

List of usage examples for com.google.common.io CharStreams copy

Introduction

In this page you can find the example usage for com.google.common.io CharStreams copy.

Prototype

public static long copy(Readable from, Appendable to) throws IOException 

Source Link

Document

Copies all characters between the Readable and Appendable objects.

Usage

From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java

private void addToJar(JarOutputStream jarOS, VirtualFile file) throws IOException {
    JarEntry entry = new JarEntry(file.getCanonicalPath());
    entry.setTime(file.getTimeStamp());/*from w w w  .  j a  va2 s. c o  m*/
    jarOS.putNextEntry(entry);
    Reader reader = wrapWithReplacements(file.getInputStream(), file.getCharset());
    Writer writer = new OutputStreamWriter(jarOS);
    try {
        CharStreams.copy(reader, writer);
    } finally {
        Closeables.close(reader, true);
        Closeables.close(writer, true);
    }
}

From source file:eu.interedition.text.rdbms.RelationalTextRepository.java

@Override
public Text concat(Iterable<Text> texts) throws IOException {
    final FileBackedOutputStream buf = createBuffer();
    final OutputStreamWriter bufWriter = new OutputStreamWriter(buf, Text.CHARSET);
    try {//from  ww  w  .ja  v  a2  s.  c  om
        for (Text text : texts) {
            read(new ReaderCallback<Void>(text) {
                @Override
                protected Void read(Clob content) throws SQLException, IOException {
                    Reader reader = null;
                    try {
                        CharStreams.copy(reader = content.getCharacterStream(), bufWriter);
                    } finally {
                        Closeables.close(reader, false);
                    }
                    return null;
                }
            });
        }
    } finally {
        Closeables.close(bufWriter, false);
    }

    Reader reader = null;
    try {
        return create(reader = new InputStreamReader(buf.getSupplier().getInput(), Text.CHARSET));
    } finally {
        Closeables.closeQuietly(reader);
        buf.reset();
    }
}

From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java

private void postData(final String name, final Reader reader, final String contentType,
        final String extraParams) throws IOException {
    Writer writer = null;/*  w w w .  ja  v a 2s  .c om*/
    LOGGER.info("Doing HTTP POST for " + name);
    try {
        URL httpURL = buildURL(target, extraParams);

        HttpURLConnection httpConnection = (HttpURLConnection) httpURL.openConnection();
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestMethod("PUT");
        httpConnection.setRequestProperty("Content-Type", contentType);
        httpConnection.setConnectTimeout(2000);
        httpConnection.setReadTimeout(60000);
        httpConnection.connect();

        if (contentType.contains("UTF-8")) {
            copyAndFlush(reader, httpConnection.getOutputStream());
        } else {
            writer = new OutputStreamWriter(httpConnection.getOutputStream());
            CharStreams.copy(reader, writer);
            writer.flush();
        }

        int responseCode = httpConnection.getResponseCode();
        String responseMessage = httpConnection.getResponseMessage();
        if (responseCode < 200 || responseCode >= 300) {
            failureCount++;
            PPImportPlugin.doNotify("Import of " + name + " failed: " + responseCode + " - " + responseMessage
                    + "\nCheck the server log for more details.", NotificationType.ERROR);
        } else {
            successCount++;
        }
    } catch (IOException e) {
        failureCount++;
        PPImportPlugin.doNotify("Import of " + name + " failed: " + e.getMessage(), NotificationType.ERROR);
    } finally {
        Closeables.close(reader, true);
        Closeables.close(writer, true);
    }
}

From source file:org.eclipse.scada.configuration.world.lib.deployment.debian.DebianHandler.java

/**
 * This method scoops up all package scripts and create the calls in the
 * corresponding package scripts/* ww  w  .j  a v a  2  s . com*/
 *
 * @throws IOException
 */
private String createUserScriptCallbacks(final File packageFolder, final String type) throws IOException {
    final File dir = new File(packageFolder, "src" + CONTROL_SCRIPTS_DIR + "/" + getPackageName() + "/" + type); //$NON-NLS-1$ //$NON-NLS-2$

    if (!dir.isDirectory()) {
        return "";
    }

    final StringWriter sw = new StringWriter();
    final Charset cs = Charset.forName("UTF-8");

    final File[] files = dir.listFiles();
    Arrays.sort(files);
    for (final File file : files) {
        if (!file.isFile()) {
            continue;
        }

        sw.write(String.format("# ================== START - %s ==================\n", file));

        try (Reader reader = Files.newBufferedReader(file.toPath(), cs)) {
            CharStreams.copy(reader, sw);
        }

        sw.write(String.format("# ==================  END - %s  ==================\n", file));

        file.setExecutable(true);
    }

    return sw.toString();
}

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

private Sources diskBackedSource(Reader source) throws IOException {
    LOG.fine("Disk-based payload for " + source);

    // Copy the original payload to disk
    Path payload = root.resolve("original-payload.json");
    try (Writer out = Files.newBufferedWriter(payload, UTF_8)) {
        CharStreams.copy(source, out);
    }// w  ww  .j  a  v a 2s  .  co m

    try (Reader in = Files.newBufferedReader(payload); JsonInput jin = json.newInput(in)) {
        Set<Dialect> dialects = new TreeSet<>();
        Supplier<Map<String, Object>> oss = null;
        Supplier<Map<String, Object>> always = ImmutableMap::of;
        List<Supplier<Map<String, Object>>> first = new LinkedList<>();

        jin.beginObject();

        while (jin.hasNext()) {
            switch (jin.nextName()) {
            case "capabilities":
                jin.beginObject();
                while (jin.hasNext()) {
                    switch (jin.nextName()) {

                    case "alwaysMatch":
                        Path a = write("always-match.json", jin);
                        always = () -> read(a);
                        dialects.add(Dialect.W3C);
                        break;

                    case "firstMatch":
                        jin.beginArray();
                        int i = 0;
                        while (jin.hasNext()) {
                            Path f = write("first-match-" + i + ".json", jin);
                            first.add(() -> read(f));
                            i++;
                        }
                        jin.endArray();
                        dialects.add(Dialect.W3C);
                        break;

                    default:
                        jin.skipValue();
                    }
                }
                jin.endObject();
                break;

            case "desiredCapabilities":
                Path ossCaps = write("oss.json", jin);
                oss = () -> read(ossCaps);
                dialects.add(Dialect.OSS);
                break;

            default:
                jin.skipValue();
            }
        }
        jin.endObject();

        if (first.isEmpty()) {
            first.add(ImmutableMap::of);
        }

        return new Sources(() -> {
            try {
                return Files.newInputStream(payload);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }, Files.size(payload), oss, always, first, dialects);
    } finally {
        source.close();
    }
}

From source file:org.fogbowcloud.manager.core.plugins.util.CloudInitUserDataBuilder.java

/**
 * Add given file <code>in</code> to the cloud-init mime message.
 * /*  w ww  . java2s. co m*/
 * @param fileType
 * @param in
 *            file to add as readable
 * @return the builder
 * @throws IllegalArgumentException
 *             the given <code>fileType</code> was already added to this
 *             cloud-init mime message.
 */

public CloudInitUserDataBuilder addFile(FileType fileType, Readable in) throws IllegalArgumentException {
    Preconditions.checkNotNull(fileType, "'fileType' can NOT be null");
    Preconditions.checkNotNull(in, "'in' can NOT be null");
    //Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added", fileType);
    alreadyAddedFileTypes.add(fileType);

    try {
        StringWriter sw = new StringWriter();
        CharStreams.copy(in, sw);
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType());
        mimeBodyPart.setFileName((userDataCounter++) + fileType.getFileName());
        userDataMultipart.addBodyPart(mimeBodyPart);

    } catch (IOException e) {
        throw Throwables.propagate(e);
    } catch (MessagingException e) {
        throw Throwables.propagate(e);
    }
    return this;
}

From source file:fr.xebia.cloud.cloudinit.CloudInitUserDataBuilder.java

/**
 * Add given file <code>in</code> to the cloud-init mime message.
 * //from w ww . j a v a2 s.  c  o m
 * @param fileType
 * @param in
 *            file to add as readable
 * @return the builder
 * @throws IllegalArgumentException
 *             the given <code>fileType</code> was already added to this
 *             cloud-init mime message.
 */
@Nonnull
public CloudInitUserDataBuilder addFile(@Nonnull FileType fileType, @Nonnull Readable in)
        throws IllegalArgumentException {
    Preconditions.checkNotNull(fileType, "'fileType' can NOT be null");
    Preconditions.checkNotNull(in, "'in' can NOT be null");
    Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added",
            fileType);
    alreadyAddedFileTypes.add(fileType);

    try {
        StringWriter sw = new StringWriter();
        CharStreams.copy(in, sw);
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType());
        mimeBodyPart.setFileName(fileType.getFileName());
        userDataMultipart.addBodyPart(mimeBodyPart);

    } catch (IOException e) {
        throw Throwables.propagate(e);
    } catch (MessagingException e) {
        throw Throwables.propagate(e);
    }
    return this;
}

From source file:com.facebook.buck.json.ProjectBuildFileParser.java

private synchronized void generatePathToBuckPy(ImmutableSet<Description<?>> descriptions) throws IOException {
    if (pathToBuckPy.isPresent()) {
        return;// ww w.j  av  a 2  s .c o  m
    }

    // We currently create a temporary buck.py per instance of this class, rather than a single one
    // for the life of this buck invocation. We do this since this is generated in parallel we end
    // up with strange InterruptedExceptions being thrown.
    // TODO(simons): This would be the ideal thing to do.
    //    Path buckDotPy =
    //        projectRoot.toPath().resolve(BuckConstant.BIN_DIR).resolve("generated-buck.py");
    Path buckDotPy = Files.createTempFile("buck", ".py");
    Files.createDirectories(buckDotPy.getParent());

    try (Writer out = Files.newBufferedWriter(buckDotPy, UTF_8)) {
        Path original = Paths.get(PATH_TO_BUCK_PY);
        CharStreams.copy(Files.newBufferedReader(original, UTF_8), out);
        out.write("\n\n");

        // The base path doesn't matter, but should be set.
        ConstructorArgMarshaller inspector = new ConstructorArgMarshaller(projectRoot.toPath());
        BuckPyFunction function = new BuckPyFunction(inspector);
        for (Description<?> description : descriptions) {
            out.write(function.toPythonFunction(description.getBuildRuleType(),
                    description.createUnpopulatedConstructorArg()));
            out.write('\n');
        }

        out.write(Joiner.on("\n").join("if __name__ == '__main__':", "  try:", "    main()",
                "  except KeyboardInterrupt:", "    print >> sys.stderr, 'Killed by User'", ""));
    }
    pathToBuckPy = Optional.of(buckDotPy.normalize());
}

From source file:org.eclipse.che.api.environment.server.MachineService.java

private void addProcessLogsToResponse(String machineId, int pid, HttpServletResponse httpServletResponse)
        throws IOException, NotFoundException, MachineException {
    try (Reader logsReader = machineProcessManager.getProcessLogReader(machineId, pid)) {
        // Response is written directly to the servlet request stream
        httpServletResponse.setContentType("text/plain");
        CharStreams.copy(logsReader, httpServletResponse.getWriter());
        httpServletResponse.getWriter().flush();
    }/* w  ww.  jav  a  2  s.c om*/
}

From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

private static JsonObject extractObject(HttpResponse resp) throws IOException {
    try (Reader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()))) {
        StringBuilder s = new StringBuilder();
        CharStreams.copy(rd, s);
        return new JsonParser().parse(s.toString()).getAsJsonObject();
    }/*from  ww w  .java 2  s .co m*/
}