List of usage examples for com.google.common.io CharStreams copy
public static long copy(Readable from, Appendable to) throws IOException
From source file:com.google.dart.compiler.backend.doc.DartDocumentationVisitor.java
private void readSource(Source source) { try {/* www .ja va 2 s.c o m*/ Reader reader = source.getSourceReader(); CharArrayWriter writer = new CharArrayWriter(); CharStreams.copy(reader, writer); unitSource = writer.toCharArray(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.outerspacecat.json.JsonProvider.java
@Override public Object readFrom(final Class<Object> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException { Parser p = new Parser(false); CharStreams.copy(new InputStreamReader(entityStream, getCharset(mediaType)), p); p.flush();//from w ww . j a v a 2s . c o m p.close(); try { return marshaler.marshalJsonTypeToJavaType(p.lift()); } catch (MarshalerException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } }
From source file:org.zalando.logbook.servlet.example.ExampleController.java
@RequestMapping(value = "/reader", produces = MediaType.TEXT_PLAIN_VALUE) public void reader(final HttpServletRequest request, final HttpServletResponse response) throws IOException { try (PrintWriter writer = response.getWriter()) { CharStreams.copy(request.getReader(), writer); }//from w w w . ja va 2 s . com }
From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java
/** * Merges a list of files into a single one by appending the contents of each file. If * {@code headerLines} is greater than zero, the header from the first file is written to the * destination file. The same number of lines is skipped in all other file, i. e. all files are * expected to have the same header.//from w ww . j a v a 2 s .c o m * * @param sourceFiles * the list of source files * @param destFile * the destination file * @param headerLines * the number of header lines * @param charset * the character set to use */ public static void merge(final File sourceDir, final List<PerfAlyzerFile> sourceFiles, final File destFile, final int headerLines, final Charset charset) throws IOException { Files.createParentDirs(destFile); // simply copy the first file copyFile(new File(sourceDir, get(sourceFiles, 0).getFile().getPath()), destFile); if (sourceFiles.size() > 1) { // append all other files skipping headers try (Writer w = Files.newWriter(destFile, charset)) { for (PerfAlyzerFile paf : sourceFiles.subList(1, sourceFiles.size())) { try (BufferedReader br = Files.newReader(new File(sourceDir, paf.getFile().getPath()), charset)) { // skip headers for (int i = 0; i < headerLines; ++i) { br.readLine(); } // copy the rest CharStreams.copy(br, w); } } } } }
From source file:org.openqa.selenium.remote.server.Passthrough.java
@Override public void handle(HttpRequest req, HttpResponse resp) throws IOException { URL target = new URL(upstream.toExternalForm() + req.getUri()); HttpURLConnection connection = (HttpURLConnection) target.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(req.getMethod().toString()); connection.setDoInput(true);// w w w . ja v a2 s .c o m connection.setDoOutput(true); connection.setUseCaches(false); for (String name : req.getHeaderNames()) { if (IGNORED_REQ_HEADERS.contains(name.toLowerCase())) { continue; } for (String value : req.getHeaders(name)) { connection.addRequestProperty(name, value); } } // None of this "keep alive" nonsense. connection.setRequestProperty("Connection", "close"); if (POST == req.getMethod()) { // We always transform to UTF-8 on the way up. String contentType = req.getHeader("Content-Type"); contentType = contentType == null ? JSON_UTF_8.toString() : contentType; MediaType type = MediaType.parse(contentType); connection.setRequestProperty("Content-Type", type.withCharset(UTF_8).toString()); Charset charSet = req.getContentEncoding(); StringWriter logWriter = new StringWriter(); try (InputStream is = req.consumeContentStream(); Reader reader = new InputStreamReader(is, charSet); Reader in = new TeeReader(reader, logWriter); OutputStream os = connection.getOutputStream(); Writer out = new OutputStreamWriter(os, UTF_8)) { CharStreams.copy(in, out); } LOG.info("To upstream: " + logWriter.toString()); } resp.setStatus(connection.getResponseCode()); // clear response defaults. resp.setHeader("Date", null); resp.setHeader("Server", null); connection.getHeaderFields().entrySet().stream() .filter(entry -> entry.getKey() != null && entry.getValue() != null) .filter(entry -> !IGNORED_REQ_HEADERS.contains(entry.getKey().toLowerCase())).forEach(entry -> { entry.getValue().stream().filter(Objects::nonNull) .forEach(value -> resp.addHeader(entry.getKey(), value)); }); InputStream in = connection.getErrorStream(); if (in == null) { in = connection.getInputStream(); } String charSet = connection.getContentEncoding() != null ? connection.getContentEncoding() : UTF_8.name(); try (Reader reader = new InputStreamReader(in, charSet)) { String content = CharStreams.toString(reader); LOG.info("To downstream: " + content); resp.setContent(content.getBytes(charSet)); } finally { in.close(); } }
From source file:eu.interedition.text.rdbms.RelationalTextRepository.java
public Text write(Text text, Reader content) throws IOException { final FileBackedOutputStream buf = createBuffer(); CountingWriter tempWriter = null;/*from w w w . j a v a2 s. c om*/ try { CharStreams.copy(content, tempWriter = new CountingWriter(new OutputStreamWriter(buf, Text.CHARSET))); } finally { Closeables.close(tempWriter, false); } Reader bufReader = null; try { return write(text, bufReader = new InputStreamReader(buf.getSupplier().getInput(), Text.CHARSET), tempWriter.length); } finally { Closeables.close(bufReader, false); } }
From source file:eu.interedition.web.text.TextController.java
@RequestMapping(value = "/{id}", produces = "text/plain") public void readText(@PathVariable("id") Text text, @RequestParam(value = "r", required = false) TextRange range, HttpServletResponse response) throws IOException { response.setCharacterEncoding(Text.CHARSET.name()); response.setContentType(MediaType.TEXT_PLAIN.toString()); final PrintWriter responseWriter = response.getWriter(); range = (range == null ? new TextRange(0, text.getLength()) : range); CharStreams.copy(text.read(range), responseWriter); }
From source file:eu.interedition.web.text.TextController.java
@RequestMapping(value = "/{id}", produces = "text/html") public ModelAndView readHTML(@PathVariable("id") Text text) throws IOException { final StringWriter textContents = new StringWriter(); CharStreams.copy(text.read(new TextRange(0, Math.min(MAX_TEXT_LENGTH, text.getLength()))), textContents); return new ModelAndView("text").addObject("text", text).addObject("textContents", textContents); }
From source file:io.soabase.web.assets.InternalAssetServlet.java
private void serveTemplate(HttpServletRequest request, HttpServletResponse response, String path) { try {//from w w w . ja va2 s . c om Template template = getTemplate(path); String content = template .apply(contextCache.getContext(request, requestLanguage.getLanguageCode(request))); String mimeTypeOfExtension = request.getServletContext().getMimeType(request.getRequestURI()); MediaType mediaType = MediaType.parse(mimeTypeOfExtension); response.setContentType(mediaType.type() + '/' + mediaType.subtype()); if (mediaType.type().equals("text") || mediaType.subtype().equals("javascript")) { response.setCharacterEncoding(Charsets.UTF_8.name()); } response.setContentLength(content.length()); CharStreams.copy(new StringReader(content), response.getWriter()); } catch (Exception e) { log.error("Could not serve template: " + path, e); } }
From source file:com.facebook.presto.cli.QueryPreprocessor.java
private static String preprocessQueryInternal(Optional<String> catalog, Optional<String> schema, String query, List<String> preprocessorCommand, Duration timeout) throws QueryPreprocessorException { // execute the process in a child thread so we can better handle interruption and timeouts AtomicReference<Process> processReference = new AtomicReference<>(); Future<String> task = executeInNewThread("Query preprocessor", () -> { String result;//w ww . j a v a 2 s .co m int exitCode; Future<String> readStderr; try { ProcessBuilder processBuilder = new ProcessBuilder(preprocessorCommand); processBuilder.environment().put(ENV_PRESTO_CATALOG, catalog.orElse("")); processBuilder.environment().put(ENV_PRESTO_SCHEMA, schema.orElse("")); Process process = processBuilder.start(); processReference.set(process); Future<?> writeOutput = null; try { // write query to process standard out writeOutput = executeInNewThread("Query preprocessor output", () -> { try (OutputStream outputStream = process.getOutputStream()) { outputStream.write(query.getBytes(UTF_8)); } return null; }); // read stderr readStderr = executeInNewThread("Query preprocessor read stderr", () -> { StringBuilder builder = new StringBuilder(); try (InputStream inputStream = process.getErrorStream()) { CharStreams.copy(new InputStreamReader(inputStream, UTF_8), builder); } catch (IOException | RuntimeException ignored) { } return builder.toString(); }); // read response try (InputStream inputStream = process.getInputStream()) { result = CharStreams.toString(new InputStreamReader(inputStream, UTF_8)); } // verify output was written successfully try { writeOutput.get(); } catch (ExecutionException e) { throw e.getCause(); } // wait for process to finish exitCode = process.waitFor(); } finally { process.destroyForcibly(); if (writeOutput != null) { writeOutput.cancel(true); } } } catch (QueryPreprocessorException e) { throw e; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new QueryPreprocessorException("Interrupted while preprocessing query"); } catch (Throwable e) { throw new QueryPreprocessorException("Error preprocessing query: " + e.getMessage(), e); } // check we got a valid exit code if (exitCode != 0) { Optional<String> errorMessage = tryGetFutureValue(readStderr, 100, MILLISECONDS) .flatMap(value -> Optional.ofNullable(emptyToNull(value.trim()))); throw new QueryPreprocessorException("Query preprocessor exited " + exitCode + errorMessage.map(message1 -> "\n===\n" + message1 + "\n===").orElse("")); } return result; }); try { return task.get(timeout.toMillis(), MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new QueryPreprocessorException("Interrupted while preprocessing query"); } catch (ExecutionException e) { Throwable cause = e.getCause(); propagateIfPossible(cause, QueryPreprocessorException.class); throw new QueryPreprocessorException("Error preprocessing query: " + cause.getMessage(), cause); } catch (TimeoutException e) { throw new QueryPreprocessorException("Timed out waiting for query preprocessor after " + timeout); } finally { Process process = processReference.get(); if (process != null) { process.destroyForcibly(); } task.cancel(true); } }