List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java
@Test public void writeBinaryData() throws Exception { byte[] binary = new byte[] { (byte) 0x05, (byte) 0xff, (byte) 0xaf, (byte) 0x30, 'A', 'B', 'C', (byte) 0x13, (byte) 0x80, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }; Map<String, Object> data = new LinkedHashMap<String, Object>(); data.put("binary", binary); //binary data has to be converted to base64 with normal JSON ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(data); assertEquals("{\"binary\":\"Bf+vMEFCQxOA/////w==\"}", jsonString); //with BSON we don't have to convert to base64 ByteArrayOutputStream baos = new ByteArrayOutputStream(); BsonFactory bsonFactory = new BsonFactory(); ObjectMapper om = new ObjectMapper(bsonFactory); om.writeValue(baos, data);//w w w . j ava 2 s . c om //document header (4 bytes) + type (1 byte) + field_name ("binary", 6 bytes) + //end_of_string (1 byte) + binary_size (4 bytes) + subtype (1 byte) + //binary_data (13 bytes) + end_of_document (1 byte) int expectedLen = 4 + 1 + 6 + 1 + 4 + 1 + 13 + 1; assertEquals(expectedLen, baos.size()); //BSON is smaller than JSON (at least in this case) assertTrue(baos.size() < jsonString.length()); //test if binary data can be parsed BSONObject obj = generateAndParse(data); byte[] objbin = (byte[]) obj.get("binary"); assertArrayEquals(binary, objbin); }
From source file:org.apache.jmeter.protocol.http.proxy.HttpRequestHdr.java
/** * Parses a http header from a stream.//from w w w. j a va 2 s. com * * @param in * the stream to parse. * @return array of bytes from client. * @throws IOException when reading the input stream fails */ public byte[] parse(InputStream in) throws IOException { boolean inHeaders = true; int readLength = 0; int dataLength = 0; boolean firstLine = true; ByteArrayOutputStream clientRequest = new ByteArrayOutputStream(); ByteArrayOutputStream line = new ByteArrayOutputStream(); int x; while ((inHeaders || readLength < dataLength) && ((x = in.read()) != -1)) { line.write(x); clientRequest.write(x); if (firstLine && !CharUtils.isAscii((char) x)) {// includes \n throw new IllegalArgumentException("Only ASCII supported in headers (perhaps SSL was used?)"); } if (inHeaders && (byte) x == (byte) '\n') { // $NON-NLS-1$ if (line.size() < 3) { inHeaders = false; firstLine = false; // cannot be first line either } final String reqLine = line.toString(); if (firstLine) { parseFirstLine(reqLine); firstLine = false; } else { // parse other header lines, looking for Content-Length final int contentLen = parseLine(reqLine); if (contentLen > 0) { dataLength = contentLen; // Save the last valid content length one } } if (log.isDebugEnabled()) { log.debug("Client Request Line: '" + reqLine.replaceFirst("\r\n$", "<CRLF>") + "'"); } line.reset(); } else if (!inHeaders) { readLength++; } } // Keep the raw post data rawPostData = line.toByteArray(); if (log.isDebugEnabled()) { log.debug("rawPostData in default JRE encoding: " + new String(rawPostData)); // TODO - charset? log.debug("Request: '" + clientRequest.toString().replaceAll("\r\n", "<CRLF>") + "'"); } return clientRequest.toByteArray(); }
From source file:com.maverick.ssl.SSLHandshakeProtocol.java
private void onServerHelloDoneMsg() throws SSLException { // Generate the premaster secret calculatePreMasterSecret();/* www .j a v a 2 s . c om*/ byte[] secret = null; try { // Encrypt the premaster secret BigInteger input = new BigInteger(1, premasterSecret); PublicKey key = x509.getPublicKey(); if (key instanceof RsaPublicKey) { BigInteger padded = Rsa.padPKCS1(input, 0x02, 128); BigInteger s = Rsa.doPublic(padded, ((RsaPublicKey) key).getModulus(), ((RsaPublicKey) key).getPublicExponent()); secret = s.toByteArray(); } else { throw new SSLException(SSLException.UNSUPPORTED_CERTIFICATE); } } catch (CertificateException ex) { throw new SSLException(SSLException.UNSUPPORTED_CERTIFICATE, ex.getMessage()); } if (secret[0] == 0) { byte[] tmp = new byte[secret.length - 1]; System.arraycopy(secret, 1, tmp, 0, secret.length - 1); secret = tmp; } sendMessage(CLIENT_KEY_EXCHANGE_MSG, secret); // Calculate the master secret calculateMasterSecret(); // #ifdef DEBUG log.debug(Messages.getString("SSLHandshakeProtocol.generatingKeyData")); //$NON-NLS-1$ // #endif // Generate the keys etc and put the cipher into use byte[] keydata; int length = 0; length += pendingCipherSuite.getKeyLength() * 2; length += pendingCipherSuite.getMACLength() * 2; length += pendingCipherSuite.getIVLength() * 2; ByteArrayOutputStream out = new ByteArrayOutputStream(); MD5Digest md5 = new MD5Digest(); SHA1Digest sha1 = new SHA1Digest(); int turn = 0; while (out.size() < length) { md5.reset(); sha1.reset(); for (int i = 0; i <= turn; i++) { sha1.update((byte) ('A' + turn)); } sha1.update(masterSecret, 0, masterSecret.length); sha1.update(serverRandom, 0, serverRandom.length); sha1.update(clientRandom, 0, clientRandom.length); md5.update(masterSecret, 0, masterSecret.length); byte[] tmp = new byte[sha1.getDigestSize()]; sha1.doFinal(tmp, 0); md5.update(tmp, 0, tmp.length); tmp = new byte[md5.getDigestSize()]; md5.doFinal(tmp, 0); // Write out a block of key data out.write(tmp, 0, tmp.length); turn++; } keydata = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(keydata); byte[] encryptKey = new byte[pendingCipherSuite.getKeyLength()]; byte[] encryptIV = new byte[pendingCipherSuite.getIVLength()]; byte[] encryptMAC = new byte[pendingCipherSuite.getMACLength()]; byte[] decryptKey = new byte[pendingCipherSuite.getKeyLength()]; byte[] decryptIV = new byte[pendingCipherSuite.getIVLength()]; byte[] decryptMAC = new byte[pendingCipherSuite.getMACLength()]; try { in.read(encryptMAC); in.read(decryptMAC); in.read(encryptKey); in.read(decryptKey); in.read(encryptIV); in.read(decryptIV); } catch (IOException ex) { throw new SSLException(SSLException.INTERNAL_ERROR, ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage()); } pendingCipherSuite.init(encryptKey, encryptIV, encryptMAC, decryptKey, decryptIV, decryptMAC); currentHandshakeStep = SERVER_HELLO_DONE_MSG; // Send the change cipher spec socket.sendCipherChangeSpec(pendingCipherSuite); // Send the finished msg sendHandshakeFinished(); }
From source file:org.ebayopensource.turmeric.policy.adminui.server.PlcImportServlet.java
/** * Parses the input stream./*from w w w . j av a2 s. c om*/ * * @param request * the request * @param response * the response * @return the byte array output stream * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ public ByteArrayOutputStream parseInputStream(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); // Process the input stream int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } int maxFileSize = 10 * (1024 * 1024); // 10 megs max if (out.size() > maxFileSize) { response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Max allowed file size: 10 Mb"); } } } catch (Exception e) { e.printStackTrace(); } return out; }
From source file:cn.ac.ncic.mastiff.io.coding.DeltaBinaryPackingStringReader.java
@Override public byte[] ensureDecompressed() throws IOException { System.out.println("280 inBuf.length " + inBuf.getLength()); FlexibleEncoding.Parquet.DeltaByteArrayReader reader = new FlexibleEncoding.Parquet.DeltaByteArrayReader(); DataOutputBuffer transfer = new DataOutputBuffer(); transfer.write(inBuf.getData(), 12, inBuf.getLength() - 12); byte[] data = transfer.getData(); System.out.println("286 byte [] data " + data.length + " numPairs " + numPairs); inBuf.close();/*w ww. j ava2 s .c om*/ Binary[] bin = new Utils().readData(reader, data, numPairs); System.out.println("2998 Binary[] bin " + bin.length); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); DataOutputStream dos1 = new DataOutputStream(bos1); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); DataOutputStream dos2 = new DataOutputStream(bos2); // DataOutputBuffer decoding = new DataOutputBuffer(); // DataOutputBuffer offset = new DataOutputBuffer(); dos1.writeInt(decompressedSize); dos1.writeInt(numPairs); dos1.writeInt(startPos); int dataoffset = 12; String str; for (int i = 0; i < numPairs; i++) { str = bin[i].toStringUsingUTF8(); dos1.writeUTF(str); dataoffset = dos1.size(); dos2.writeInt(dataoffset); } System.out.println("315 offset.size() " + bos2.size() + " decoding.szie " + bos2.toByteArray().length); System.out.println("316 dataoffet " + dataoffset); dos1.write(bos2.toByteArray(), 0, bos2.size()); inBuf.close(); System.out.println("316 bos1 " + bos1.toByteArray().length + " " + bos1.size()); byte[] bytes = bos1.toByteArray(); dos2.close(); bos2.close(); bos1.close(); dos1.close(); return bytes; }
From source file:com.agilejava.maven.docbkx.GeneratorMojo.java
/** * Returns a {@link Collection} of all parameter names defined in the * stylesheet or in one of the stylesheets imported or included in the * stylesheet./* www.j av a 2s. c om*/ * * @param url * The location of the stylesheet to analyze. * @return A {@link Collection} of all parameter names found in the * stylesheet pinpointed by the <code>url</code> argument. * * @throws MojoExecutionException * If the operation fails to detect parameter names. */ private Collection getParameterNames(String url) throws MojoExecutionException { ByteArrayOutputStream out = null; try { Transformer transformer = createParamListTransformer(); Source source = new StreamSource(url); out = new ByteArrayOutputStream(); Result result = new StreamResult(out); transformer.transform(source, result); out.flush(); if (out.size() != 0) { // at least one param has been found, because the split with return an empty string if there is no data String[] paramNames = new String(out.toByteArray()).split("\n"); return new HashSet(Arrays.asList(paramNames)); } else { // else no param found return new HashSet(); } } catch (IOException ioe) { // Impossible, but let's satisfy PMD and FindBugs getLog().warn("Failed to flush ByteArrayOutputStream."); } catch (TransformerConfigurationException tce) { throw new MojoExecutionException("Failed to create Transformer for retrieving parameter names", tce); } catch (TransformerException te) { throw new MojoExecutionException("Failed to apply Transformer for retrieving parameter names.", te); } finally { IOUtils.closeQuietly(out); } return Collections.EMPTY_SET; }
From source file:jproxy.HttpRequestHdr.java
/** * Parses a http header from a stream./*from w w w . ja v a 2 s .c o m*/ * * @param in * the stream to parse. * @return array of bytes from client. * @throws IOException when reading the input stream fails */ public byte[] parse(InputStream in) throws IOException { boolean inHeaders = true; int readLength = 0; int dataLength = 0; boolean firstLine = true; ByteArrayOutputStream clientRequest = new ByteArrayOutputStream(); ByteArrayOutputStream line = new ByteArrayOutputStream(); int x; while ((inHeaders || readLength < dataLength) && ((x = in.read()) != -1)) { line.write(x); clientRequest.write(x); if (firstLine && !CharUtils.isAscii((char) x)) {// includes \n throw new IllegalArgumentException("Only ASCII supported in headers (perhaps SSL was used?)"); } if (inHeaders && (byte) x == (byte) '\n') { // $NON-NLS-1$ if (line.size() < 3) { inHeaders = false; firstLine = false; // cannot be first line either } final String reqLine = line.toString(); if (firstLine) { parseFirstLine(reqLine); firstLine = false; } else { // parse other header lines, looking for Content-Length final int contentLen = parseLine(reqLine); if (contentLen > 0) { dataLength = contentLen; // Save the last valid content length one } } if (log.isDebugEnabled()) { log.debug("Client Request Line: '" + reqLine.replaceFirst("\r\n$", "<CRLF>") + "'"); } line.reset(); } else if (!inHeaders) { readLength++; } } // Keep the raw post data rawPostData = line.toByteArray(); if (log.isDebugEnabled()) { log.debug("rawPostData in default JRE encoding: " + new String(rawPostData)); // TODO - charset? log.debug("Request: '" + clientRequest.toString().replaceAll("\r\n", "<CRLF>") + "'"); } rawRequestData = clientRequest.toByteArray(); return clientRequest.toByteArray(); }
From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java
/** * Put a collection of captchas with his locale * * @param captchas The captchas to add/*from w w w . ja va2 s. co m*/ * @param locale The locale of the captchas */ public void putAllCaptcha(Collection captchas, Locale locale) { Connection con = null; PreparedStatement ps = null; if (captchas != null && captchas.size() > 0) { Iterator captIt = captchas.iterator(); if (log.isDebugEnabled()) { log.debug("try to insert " + captchas.size() + " captchas"); } try { con = datasource.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement("insert into " + table + "(" + timeMillisColumn + "," + hashCodeColumn + "," + localeColumn + "," + captchaColumn + ") values (?,?,?,?)"); while (captIt.hasNext()) { Captcha captcha = (Captcha) captIt.next(); try { long currenttime = System.currentTimeMillis(); long hash = captcha.hashCode(); ps.setLong(1, currenttime); ps.setLong(2, hash); ps.setString(3, locale.toString()); // Serialise the entry final ByteArrayOutputStream outstr = new ByteArrayOutputStream(); final ObjectOutputStream objstr = new ObjectOutputStream(outstr); objstr.writeObject(captcha); objstr.close(); final ByteArrayInputStream inpstream = new ByteArrayInputStream(outstr.toByteArray()); ps.setBinaryStream(4, inpstream, outstr.size()); ps.addBatch(); if (log.isDebugEnabled()) { log.debug("insert captcha added to batch : " + currenttime + ";" + hash); } } catch (IOException e) { log.warn("error during captcha serialization, " + "check your class versions. removing row from database", e); } } //exexute batch and commit() ps.executeBatch(); log.debug("batch executed"); con.commit(); log.debug("batch commited"); } catch (SQLException e) { log.error(DB_ERROR, e); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { } } if (con != null) { try { con.close(); } catch (SQLException e) { } } } } }
From source file:com.highcharts.export.controller.ExportController.java
@RequestMapping(value = "/json/{name}.{ext}", method = RequestMethod.POST) public HttpEntity<byte[]> exportFromJson(@PathVariable("name") String name, @PathVariable("ext") String extension, @RequestBody String requestBody) throws SVGConverterException, TimeoutException, NoSuchElementException, PoolException { String randomFilename;/* w w w . ja va2 s. co m*/ randomFilename = null; String json = requestBody; MimeType mime = getMime(extension); // add outfile parameter to the json with a simple string replace if (MimeType.PDF.equals(mime)) { randomFilename = createRandomFileName(mime.name().toLowerCase()); int ind = json.lastIndexOf("}"); json = new StringBuilder(json).replace(ind, ind + 1, ",\"outfile\":\"" + randomFilename).toString() + "\"}"; } String result = converter.requestServer(json); ByteArrayOutputStream stream; if (randomFilename != null && randomFilename.equals(result)) { stream = writeFileToStream(randomFilename); } else { boolean base64 = !mime.getExtension().equals("svg"); stream = outputToStream(result, base64); } HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", mime.getType() + "; charset=utf-8"); headers.add("Content-Disposition", "attachment; filename=" + name + "." + extension); headers.setContentLength(stream.size()); return new HttpEntity<byte[]>(stream.toByteArray(), headers); }
From source file:gov.utah.dts.det.ccl.actions.reports.ReportsPrintAction.java
private void generateErrorPdf() { // Generate an error pdf ByteArrayOutputStream ba = null; try {/* www.j a v a2 s . c o m*/ ba = new ByteArrayOutputStream(); Document document = new Document(PageSize.A4, 50, 50, 100, 100); @SuppressWarnings("unused") PdfWriter writer = PdfWriter.getInstance(document, ba); document.open(); document.add(new Paragraph("An error occurred while generating the report document.", FontFactory.getFont("Times-Roman", 12, Font.NORMAL))); document.close(); if (ba != null && ba.size() > 0) { sendToResponse(ba, null); } } catch (Exception e) { log.error("AN ERROR OCCURRED GENERATING ERROR PDF DOCUMENT: " + e); } }