List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:org.apache.taverna.scufl2.wfdesc.TestConvertToWfdesc.java
@Test public void stdin() throws Exception { byte[] input = IOUtils.toByteArray(getClass().getResourceAsStream("/" + HELLOWORLD_T2FLOW)); assertTrue(input.length > 0);//from w w w .j a va 2s.c o m InputStream in = new ByteArrayInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream outBuf = new PrintStream(out); try { System.setIn(in); System.setOut(outBuf); ConvertToWfdesc.main(new String[] {}); } finally { restoreStd(); } out.flush(); out.close(); String turtle = out.toString("utf-8"); //System.out.println(turtle); assertTrue(turtle.contains("Hello_World")); assertTrue(turtle.contains("processor/hello/out/value")); }
From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java
private byte[] getBytes(InputStream is) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead;// w ww . j av a2s .co m byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); byte[] bytes = buffer.toByteArray(); Log.i("registration", "Have " + bytes.length + " bytes"); return bytes; }
From source file:openlr.otk.binview.BinaryViewerOptions.java
/** * Reads the content of the input file.//from w w w . j a va2 s . c om * * @param isBase64 * Specifies if the content is of base-65-encoded data, or is yet * the pure binary data. * @param inputData * The input stream. * @return The binary location data. * @throws CommandLineParseException * If an error occurs. */ private byte[] readContent(final boolean isBase64, final InputStream inputData) throws CommandLineParseException { byte[] data; if (isBase64) { // read base64 encoded string and decode to binary data BufferedReader br = null; StringBuffer base64String = new StringBuffer(); try { br = new BufferedReader(new InputStreamReader(inputData, IOUtils.SYSTEM_DEFAULT_CHARSET)); String line; while ((line = br.readLine()) != null) { base64String.append(line); } } catch (FileNotFoundException e) { throw new CommandLineParseException("Error reading input from " + inputOption.getInputSource(), e); } catch (IOException e) { throw new CommandLineParseException("Error reading input from " + inputOption.getInputSource(), e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { LOG.error("cannot close input reader"); } } } data = BinaryDataViewer.transformBase64(base64String.toString().trim()); } else { try { int b; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((b = inputData.read()) != -1) { bos.write(b); } bos.flush(); data = bos.toByteArray(); } catch (FileNotFoundException fnfe) { throw new CommandLineParseException( "Error reading binary input from " + inputOption.getInputSource(), fnfe); } catch (IOException e) { throw new CommandLineParseException("the binary stream is not valid! " + e.getMessage(), e); } } return data; }
From source file:com.microsoft.office365.meetingmgr.HttpHelperBase.java
private byte[] responseToByteArray(HttpResponse response) { try {/*from w ww . ja v a2s . c o m*/ InputStream stream = response.getEntity().getContent(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[1024]; while ((nRead = stream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } catch (IOException e) { ErrorLogger.log(e); } return null; }
From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java
@Override public JobStatus updateJob(String jobId) { try {// ww w .j a v a 2s .com log.debug("Polling state for " + jobId + "..."); ExecutionHandler handler = jobIdToHandlerMap.get(jobId); if (handler == null) { return null; } JobStatus jobStatus = new JobStatus().setId(jobId); DefaultExecuteResultHandler resultHandler; ByteArrayOutputStream stdOutStream; ByteArrayOutputStream stdErrStream; stdOutStream = handler.getStdOut(); stdErrStream = handler.getStdErr(); resultHandler = handler.getResultHandler(); stdOutStream.flush(); stdErrStream.flush(); jobStatus.setStdOut(new String(stdOutStream.toByteArray())); jobStatus.setStdErr(new String(stdErrStream.toByteArray())); if (resultHandler.hasResult()) { jobStatus.setState(JobStatus.State.COMPLETED); int exitValue = resultHandler.getExitValue(); log.info(jobId + " has terminated with exit code " + exitValue); if (exitValue == 0) { jobStatus.setResult(JobStatus.Result.SUCCESS); } else { jobStatus.setResult(JobStatus.Result.FAILURE); } jobIdToHandlerMap.remove(jobId); } else { jobStatus.setState(JobStatus.State.RUNNING); } return jobStatus; } catch (Exception e) { log.warn("Failed to retrieve status of " + jobId); return null; } }
From source file:com.ikanow.infinit.e.harvest.extraction.document.file.FileHarvester.java
/** * Get a specific doc to return the bytes for * @throws Exception /*from w w w . j a v a 2 s . c o m*/ */ public static byte[] getFile(String fileURL, SourcePojo source) throws Exception { InputStream in = null; try { InfiniteFile searchFile = searchFileShare(source, fileURL); if (searchFile == null) return null; else { //found the file, return the bytes in = searchFile.getInputStream(); if (null == in) return null; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int read; byte[] data = new byte[16384]; while ((read = in.read(data, 0, data.length)) != -1) { buffer.write(data, 0, read); } buffer.flush(); return buffer.toByteArray(); } } catch (Exception e) { throw e; } finally { if (null != in) { in.close(); } } }
From source file:net.tawacentral.roger.secrets.FileUtils.java
/** * Read the secrets from the given input stream, decrypting with the given * cipher.//from w w w . j av a 2s . c o m * * @param input * The input stream to read the secrets from. * @param cipher * The cipher to decrypt the secrets with. * @return The secrets read from the stream. * @throws IOException * @throws ClassNotFoundException */ private static ArrayList<Secret> readSecrets(InputStream input, Cipher cipher, byte[] salt, int rounds) throws IOException, ClassNotFoundException { SaltAndRounds pair = getSaltAndRounds(input); if (!Arrays.equals(pair.salt, salt) || pair.rounds != rounds) { return null; } BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { // read the whole stream into the buffer int nRead; byte[] data = new byte[4096]; while ((nRead = bis.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return FileUtils.fromEncryptedJSONSecretsStream(cipher, buffer.toByteArray()); } finally { try { if (null != bis) bis.close(); } catch (IOException ex) { } } }
From source file:com.example.cognitive.personality.DemoServlet.java
private String getDefaultText() { if (mobydickcp1 == null) { byte[] encoded; // try { // Path path = Paths.get(this.getClass().getResource("mobydick.txt").toURI()); // encoded = Files.readAllBytes(path); // mobydickcp1 = new String(encoded, StandardCharsets.UTF_8); // System.out.println(mobydickcp1); // } catch (Exception e) { // logger.log(Level.SEVERE, "mobidick.txt file not found: " + e.getMessage(), e); // } try {/*www. j a v a 2s. co m*/ //URI uri = this.getClass().getResource("mobydick.txt").toURI(); //String fileName = uri.getPath(); //System.out.println(getClass()+" "+fileName); InputStream is = getServletContext().getResourceAsStream("/pi/mobydick.txt"); System.out.println(getClass() + " is=" + is); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); encoded = buffer.toByteArray(); // RandomAccessFile f = new RandomAccessFile(fileName, "r"); // encoded = new byte[(int)f.length()]; // f.read(encoded); // f.close(); mobydickcp1 = new String(encoded, "UTF8"); System.out.println(mobydickcp1); } catch (Exception e) { logger.log(Level.SEVERE, "mobidick.txt could not be read: " + e.getMessage(), e); } } return mobydickcp1; }
From source file:org.apache.apex.malhar.sql.FileEndpointTest.java
private boolean waitTillStdoutIsPopulated(ByteArrayOutputStream baos, int timeout) throws InterruptedException, IOException { long now = System.currentTimeMillis(); Collection<String> filter = Lists.newArrayList(); while (System.currentTimeMillis() - now < timeout) { baos.flush(); String[] sout = baos.toString().split(System.lineSeparator()); filter = Collections2.filter(Arrays.asList(sout), Predicates.containsPattern("Delta Record:")); if (filter.size() != 0) { break; }/*ww w . ja v a2 s . c om*/ Thread.sleep(500); } return (filter.size() != 0); }
From source file:org.jsnap.http.base.HttpServlet.java
protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response) throws HttpException, IOException { // Client might keep the executing thread blocked for very long unless this header is added. response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); // Create a wrapped request object. String uri, data;/*w ww .jav a 2 s. c o m*/ String method = request.getRequestLine().getMethod(); if (method.equals(HttpGet.METHOD_NAME)) { BasicHttpRequest get = (BasicHttpRequest) request; data = get.getRequestLine().getUri(); int ix = data.indexOf('?'); uri = (ix < 0 ? data : data.substring(0, ix)); data = (ix < 0 ? "" : data.substring(ix + 1)); } else if (method.equals(HttpPost.METHOD_NAME)) { BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request; HttpEntity postedEntity = post.getEntity(); uri = post.getRequestLine().getUri(); data = EntityUtils.toString(postedEntity); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); response.setHeader(new Header(HTTP.CONTENT_LEN, "0")); return; } String cookieLine = ""; if (request.containsHeader(COOKIE)) { Header[] cookies = request.getHeaders(COOKIE); for (Header cookie : cookies) { if (cookieLine.length() > 0) cookieLine += "; "; cookieLine += cookie.getValue(); } } HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine); // Create a wrapped response object. ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE); HttpResponse resp = new HttpResponse(out); // Do implementation specific processing. doServiceImpl(req, resp); out.flush(); // It's good practice to do this. // Do the actual writing to the actual response object. if (resp.redirectTo != null) { // Redirection is requested. resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY; response.setStatusCode(resp.statusCode); Header redirection = new Header(LOCATION, resp.redirectTo); response.setHeader(redirection); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, "Status Code: " + Integer.toString(resp.statusCode)); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString()); } else { // There will be a response entity. response.setStatusCode(resp.statusCode); HttpEntity entity; Header contentTypeHeader; boolean text = resp.contentType.startsWith(Formatter.TEXT); if (text) { // text/* ... entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet); contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet); } else { // application/octet-stream, image/* ... entity = new ByteArrayEntity(out.toByteArray()); contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType); } boolean acceptsGzip = clientAcceptsGzip(request); long contentLength = entity.getContentLength(); // If client accepts gzipped content, the implementing object requested that response // gets gzipped and size of the response exceeds implementing object's size threshold // response entity will be gzipped. boolean gzipped = false; if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) { ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE); GZIPOutputStream gzos = new GZIPOutputStream(zipped); entity.writeTo(gzos); gzos.close(); entity = new ByteArrayEntity(zipped.toByteArray()); contentLength = zipped.size(); gzipped = true; } // This is where true writes are made. Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength)); Header contentEncodingHeader = null; response.setHeader(contentTypeHeader); response.setHeader(contentLengthHeader); if (gzipped) { contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP); response.setHeader(contentEncodingHeader); } response.setEntity(entity); // Log critical headers. Logger.getLogger(HttpServlet.class).log(Level.DEBUG, "Status Code: " + Integer.toString(resp.statusCode)); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString()); if (gzipped) Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString()); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString()); } // Log cookies. for (Cookie cookie : resp.cookies) { if (cookie.valid()) { Header h = new Header(SET_COOKIE, cookie.toString()); response.addHeader(h); Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString()); } } }