List of usage examples for org.apache.commons.io IOUtils write
public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException
StringBuffer
to bytes on an OutputStream
using the specified character encoding. From source file:ch.cyberduck.core.socket.HttpProxyAwareSocket.java
@Override public void connect(final SocketAddress endpoint, final int timeout) throws IOException { if (proxy.type() == Proxy.Type.HTTP) { super.connect(proxy.address(), timeout); final InetSocketAddress address = (InetSocketAddress) endpoint; final OutputStream out = this.getOutputStream(); IOUtils.write(String.format("CONNECT %s:%d HTTP/1.0\n\n", address.getHostName(), address.getPort()), out, Charset.defaultCharset()); final InputStream in = this.getInputStream(); final String response = new LineNumberReader(new InputStreamReader(in)).readLine(); if (null == response) { throw new SocketException(String.format("Empty response from HTTP proxy %s", ((InetSocketAddress) proxy.address()).getHostName())); }/*ww w. j a va 2 s . c o m*/ if (response.contains("200")) { in.skip(in.available()); } else { throw new SocketException(String.format("Invalid response %s from HTTP proxy %s", response, ((InetSocketAddress) proxy.address()).getHostName())); } } else { super.connect(endpoint, timeout); } }
From source file:ch.cyberduck.core.manta.AbstractMantaTest.java
@Before public void setup() throws Exception { final Profile profile = new ProfilePlistReader( new ProtocolFactory(Collections.singleton(new MantaProtocol()))) .read(new Local("../profiles/Joyent Triton Object Storage.cyberduckprofile")); final String hostname; final Local file; if (ObjectUtils.allNotNull(System.getProperty("manta.key_path"), System.getProperty("manta.url"))) { file = new Local(System.getProperty("manta.key_path")); hostname = new URL(System.getProperty("manta.url")).getHost(); } else {//w ww.j av a 2 s . co m final String key = System.getProperty("manta.key"); file = TemporaryFileServiceFactory.get().create(new AlphanumericRandomStringService().random()); LocalTouchFactory.get().touch(file); IOUtils.write(key, file.getOutputStream(false), Charset.defaultCharset()); hostname = profile.getDefaultHostname(); } final String user = System.getProperty("manta.user"); final Host host = new Host(profile, hostname, new Credentials(user).withIdentity(file)); session = new MantaSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager()); session.open(new DisabledHostKeyCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final String testRoot = "cyberduck-test-" + new AlphanumericRandomStringService().random(); testPathPrefix = new Path( new MantaAccountHomeInfo(host.getCredentials().getUsername(), host.getDefaultPath()) .getAccountPrivateRoot(), testRoot, EnumSet.of(Type.directory)); session.getClient().putDirectory(testPathPrefix.getAbsolute()); }
From source file:ai.api.RequestTask.java
@Override protected String doInBackground(final String... params) { final String payload = params[0]; if (TextUtils.isEmpty(payload)) { throw new IllegalArgumentException("payload argument should not be empty"); }/* w ww . jav a2 s .co m*/ String response = null; HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.connect(); final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.write(payload, outputStream, Charsets.UTF_8); outputStream.close(); final InputStream inputStream = new BufferedInputStream(connection.getInputStream()); response = IOUtils.toString(inputStream, Charsets.UTF_8); inputStream.close(); return response; } catch (final IOException e) { Log.e(TAG, "Can't make request to the Speaktoit AI service. Please, check connection settings and API access token.", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:com.formkiq.core.api.FeedsController.java
/** * Gets a Feed and transfers XML to JSON. * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} * @throws IOException IOException/*from ww w . j a va 2 s.c o m*/ * @throws InvalidFeedUrlException InvalidFeedUrlException */ @RequestMapping(value = API_FEEDS_GET) public void get(final HttpServletRequest request, final HttpServletResponse response) throws IOException, InvalidFeedUrlException { getApiVersion(request); Map<String, String[]> map = request.getParameterMap(); String url = getParameter(map, "url", true).trim(); ResponseEntity<String> entity = this.feedService.get(url); String body = entity.getBody(); if (this.feedService.isXMLContentType(entity.getHeaders())) { body = this.feedService.toJSONFromXML(body); } else if (!this.feedService.isJSONContentType(entity.getHeaders())) { List<String> contentTypes = entity.getHeaders().get("content-type"); String ct = !contentTypes.isEmpty() ? contentTypes.get(0) : "unknown content type"; throw new InvalidFeedUrlException("Invalid content-type " + ct + " for " + url); } response.setContentType("application/json"); response.setContentLengthLong(body.length()); IOUtils.write(body, response.getOutputStream(), Strings.CHARSET_UTF8); }
From source file:io.stallion.utils.ProcessHelper.java
public CommandResult run() { String cmdString = String.join(" ", args); System.out.printf("----- Execute command: %s ----\n", cmdString); ProcessBuilder pb = new ProcessBuilder(args); if (!empty(directory)) { pb.directory(new File(directory)); }/*from www .j av a 2s . c o m*/ Map<String, String> env = pb.environment(); CommandResult commandResult = new CommandResult(); Process p = null; try { if (showDotsWhileWaiting == null) { showDotsWhileWaiting = !inheritIO; } if (inheritIO) { p = pb.inheritIO().start(); } else { p = pb.start(); } BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream())); if (!empty(input)) { Log.info("Writing input to pipe {0}", input); IOUtils.write(input, p.getOutputStream(), UTF8); p.getOutputStream().flush(); } while (p.isAlive()) { p.waitFor(1000, TimeUnit.MILLISECONDS); if (showDotsWhileWaiting == true) { System.out.printf("."); } } commandResult.setErr(IOUtils.toString(err)); commandResult.setOut(IOUtils.toString(out)); commandResult.setCode(p.exitValue()); if (commandResult.succeeded()) { info("\n---- Command execution completed ----\n"); } else { Log.warn("Command failed with error code: " + commandResult.getCode()); } } catch (IOException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(999); commandResult.setEx(e); } catch (InterruptedException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(998); commandResult.setEx(e); } Log.fine( "\n\n----Start shell command result----:\nCommand: {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n", cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr()); return commandResult; }
From source file:com.adobe.acs.commons.redirectmaps.impl.RedirectEntriesUtils.java
protected static final void writeEntriesToResponse(SlingHttpServletRequest request, SlingHttpServletResponse response, String message) throws ServletException, IOException { log.trace("writeEntriesToResponse"); log.debug("Requesting redirect maps from {}", request.getResource()); RedirectMapModel redirectMap = request.getResource().adaptTo(RedirectMapModel.class); response.setContentType(MediaType.JSON_UTF_8.toString()); JsonObject res = new JsonObject(); res.addProperty("message", message); JsonElement entries = gson.toJsonTree(redirectMap.getEntries(), new TypeToken<List<MapEntry>>() { }.getType());//from w ww . ja v a 2s . co m Iterator<JsonElement> it = entries.getAsJsonArray().iterator(); for (int i = 0; it.hasNext(); i++) { it.next().getAsJsonObject().addProperty("id", i); } res.add("entries", entries); res.add("invalidEntries", gson.toJsonTree(redirectMap.getInvalidEntries(), new TypeToken<List<MapEntry>>() { }.getType())); IOUtils.write(res.toString(), response.getOutputStream(), StandardCharsets.UTF_8); }
From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.CasFlusher.java
public static void flush(File aSerializedCas, OutputStream aOutputStream, int aBegin, int aEnd) throws IOException { CAS cas = new CASImpl(); InputStream is = null;//from w ww . ja v a 2 s .c o m try { is = new FileInputStream(aSerializedCas); if (aSerializedCas.getName().endsWith(".gz")) { is = new GZIPInputStream(is); } else if (aSerializedCas.getName().endsWith(".xz")) { is = new XZInputStream(is); } is = new ObjectInputStream(new BufferedInputStream(is)); CASCompleteSerializer serializer = (CASCompleteSerializer) ((ObjectInputStream) is).readObject(); ((CASImpl) cas).reinit(serializer); } catch (ClassNotFoundException e) { throw new IOException(e); } finally { IOUtils.closeQuietly(is); } Collection<AnnotationFS> annos; if (aBegin > -1 && aEnd > -1) { annos = CasUtil.selectCovered(cas, CasUtil.getType(cas, Annotation.class), aBegin, aEnd); } else { annos = CasUtil.selectAll(cas); } for (AnnotationFS anno : annos) { StringBuilder sb = new StringBuilder(); sb.append("[" + anno.getClass().getSimpleName() + "] "); sb.append("(" + anno.getBegin() + "," + anno.getEnd() + ") "); sb.append(anno.getCoveredText() + "\n"); IOUtils.write(sb, aOutputStream, "UTF-8"); } }
From source file:com.cd.reddit.http.RedditRequestor.java
public RedditRequestResponse executePost(RedditRequestInput input) throws RedditException { HttpURLConnection connection = getConnection(input); connection.setDoOutput(true);/* www .j a v a 2 s . co m*/ try { connection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new RedditException(e); } OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); IOUtils.write(generateUrlEncodedForm(input.getFormParams()), outputStream, "UTF-8"); } catch (IOException e) { throw new RedditException(e); } finally { IOUtils.closeQuietly(outputStream); } return readResponse(connection, input); }
From source file:de.tudarmstadt.ukp.dkpro.core.io.lif.LifWriter.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { // Convert UIMA to LIF Container Container container = new Container(); new DKPro2Lif().convert(aJCas, container); try (OutputStream docOS = getOutputStream(aJCas, filenameSuffix)) { String json = Serializer.toPrettyJson(container); IOUtils.write(json, docOS, encoding); } catch (Exception e) { throw new AnalysisEngineProcessException(e); }//www. j ava2 s. c om }
From source file:com.github.sleroy.fakesmtp.model.EmailModel.java
/** * Saves the mail into an output stream like a file. * * The stream is not closed after the execution of the method. You need to * close it yourself./*from w ww . ja va2s. co m*/ * * @param outputStream * the output stream * @param charset * the charset * @throws IOException * Signals that an I/O exception has occurred. */ public void save(final OutputStream outputStream, final Charset charset) throws IOException { // Copy String to file IOUtils.write(emailStr, outputStream, charset); }