public static MessageHeader readHeader(InputStream in) throws IOException, MessageFormatException { int match = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); int i; try { do { i = in.read(); if (i == -1) { if (out.size() > 0) throw new MessageFormatException("Unexpected end of stream", out.toByteArray()); return null; } out.write(i); if (i == CRLF[match % 2]) match++; } while (match < 4); } catch (IOException e) { if (out.size() > 0) throw new MessageFormatException("Incomplete message header", e, out.toByteArray()); throw e; } MutableMessageHeader header = new MutableMessageHeader.Impl(); header.setHeader(out.toByteArray()); return header; }
private void flushRaw() throws IOException { if (currentRaw != null && currentRaw.size() > 0) { if (mode == Mode.Block) { output.writeInt(-1); } System.err.println("Writing raw chunk : " + currentRaw.size()); rawChunks += currentRaw.size(); output.writeInt(currentRaw.size()); currentRaw.writeTo(output); mode = Mode.Raw; } currentRaw = null; }
/** * Test method for {@link * org.alfresco.deployment.transformers.EncryptionTransformer#addFilter(java.io.OutputStream, * org.alfresco.deployment.DeploymentTransportTransformer.Direction, java.lang.String)}. This test * compresses a message with one transformation. Then sends the results through another instance * to give us plain text again. */ public void testAddFilter() { SampleEncryptionTransformer transformer = new SampleEncryptionTransformer(); transformer.setPassword("Welcome To Hades"); transformer.setCipherName("PBEWithMD5AndDES"); String path = "wibble"; ByteArrayOutputStream compressed = new ByteArrayOutputStream(); // A sender should encrypt the stream OutputStream out = null; // out = (OutputStream)transformer.addFilter(compressed, Direction.SENDER, path); out = (OutputStream) transformer.addFilter(compressed, path, null, null); assertNotNull("null output stream returned", compressed); String clearText = "hello world"; try { out.write(clearText.getBytes()); } catch (IOException ie) { fail("unexpected exception thrown" + ie.toString()); } try { out.flush(); out.close(); } catch (IOException ie) { fail("unexpected exception thrown, " + ie.toString()); } assert (compressed.size() > 0); // Now set up another instance to decrypt the message InputStream decompress = null; ByteArrayInputStream compressedStream = new ByteArrayInputStream(compressed.toByteArray()); ByteArrayOutputStream result = new ByteArrayOutputStream(); decompress = (InputStream) transformer.addFilter(compressedStream, "wibble", null, null); try { byte[] readBuffer = new byte[1002]; while (true) { int readLen = decompress.read(readBuffer); if (readLen > 0) { result.write(readBuffer, 0, readLen); } else { break; } } } catch (IOException ie) { fail("unexpected exception thrown, " + ie.toString()); } // now uncompress should equal clearText assertTrue(result.toString().equalsIgnoreCase(clearText)); }
int getBufferedLength() { if (ibuffer == null) { return 0; } else { return ibuffer.size(); } }
private void doTest(String prefix) throws IOException { int n = 0; int failed = 0; for (String name : myMap.keySet()) { if (prefix == null && name.contains("/")) { continue; } if (prefix != null && !name.startsWith(prefix)) { continue; } System.out.print("filename = " + name); n++; final MainParseTest.Test test = myMap.get(name); try { myFixture.testHighlighting(test.showWarnings, true, test.showInfo, name); if (test.expectedResult == Result.ERR) { System.out.println( " FAILED. Expression incorrectly parsed OK: " + FileUtil.loadFile(new File(getTestDataPath(), name))); failed++; } else { System.out.println(" OK"); } } catch (Throwable e) { if (test.expectedResult == Result.ERR) { System.out.println(" OK"); } else { e.printStackTrace(); System.out.println( " FAILED. Expression = " + FileUtil.loadFile(new File(getTestDataPath(), name))); if (myOut.size() > 0) { String line; final BufferedReader reader = new BufferedReader(new StringReader(myOut.toString())); do { line = reader.readLine(); } while (line != null && (line.trim().length() == 0 || line.trim().equals("ERROR:"))); if (line != null) { if (line.matches(".*java.lang.Error: junit.framework.AssertionFailedError:.*")) { System.out.println( "ERROR: " + line.replace( "java.lang.Error: junit.framework.AssertionFailedError:", "")); } } else { System.out.println("ERROR: " + myOut.toString()); } } failed++; } } myOut.reset(); } System.out.println(""); System.out.println(n + " Tests executed, " + failed + " failed"); assertFalse(failed > 0); }
/** * DO NOT call symbolTable.addReference in writeObject as this (may) result in a * concurrentModificationException. * * <p>All references should be created in the constructor */ public void writeObject(DataOutput out) throws IOException { boolean sgIO = node instanceof com.sun.j3d.utils.scenegraph.io.SceneGraphIO; out.writeBoolean(sgIO); out.writeInt(symbol.nodeID); int nodeClassID = control.getNodeClassID(node); out.writeShort(nodeClassID); if (nodeClassID == -1) out.writeUTF(nodeClassName); writeConstructorParams(out); if (sgIO) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream tmpOut = new DataOutputStream(byteStream); ((com.sun.j3d.utils.scenegraph.io.SceneGraphIO) node).writeSceneGraphObject(tmpOut); tmpOut.close(); out.writeInt(byteStream.size()); out.write(byteStream.toByteArray()); } writeUserData(out); writeString(node.getName(), out); writeCapabilities(out); }
private void snipRawBuffer() { if (currentRaw != null) { final byte[] buffer = currentRaw.toByteArray(); currentRaw = new ByteArrayOutputStream(); currentRaw.write(buffer, 0, buffer.length - BLOCK_SIZE); System.err.println("Snip : " + buffer.length + " : " + currentRaw.size()); } }
private int testObjectSer( ObjectWriter writer, MediaItem value, int reps, ByteArrayOutputStream result) throws Exception { for (int i = 0; i < reps; ++i) { result.reset(); writer.writeValue(result, value); } return result.size(); }
/** Save the current content of this cipher. */ void save() { processedSave = processed; sizeOfAADSave = sizeOfAAD; aadBufferSave = ((aadBuffer == null || aadBuffer.size() == 0) ? null : aadBuffer.toByteArray()); if (gctrPAndC != null) gctrPAndC.save(); if (ghashAllToS != null) ghashAllToS.save(); if (ibuffer != null) { ibufferSave = ibuffer.toByteArray(); } }
@Override public void applyTo(MutableHttpServletResponse response) throws IOException { if (responseHeaderManager().hasHeaders()) { responseHeaderManager().applyTo(response); } if (HttpStatusCode.UNSUPPORTED_RESPONSE_CODE.intValue() != status && delegatedAction != FilterAction.NOT_SET) { response.setStatus(status); } if (directorOutputStream.size() > 0) { response.setContentLength(directorOutputStream.size()); response.setHeader("Content-Length", String.valueOf(directorOutputStream.size())); RawInputStreamReader.instance() .copyTo( new ByteArrayInputStream(getResponseMessageBodyBytes()), response.getOutputStream()); } }
/** * Write the Track Chunk * * @param DataOutputStream dos * @param Track track - track to write * @exception IOException */ private void writeTrackChunk(DataOutputStream odos, Track track) throws IOException { if (VERBOSE) System.out.println("Writing MIDI Track"); // Write to temporary stream to buffer disk writes and // calculate the number of bytes written to the stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); int header = 0x4D54726B; Enumeration aEnum = track.getEvtList().elements(); aEnum = track.getEvtList().elements(); // At this stage Except that all events are NoteOn events while (aEnum.hasMoreElements()) { Event evt = (Event) aEnum.nextElement(); evt.write(dos); if (DEBUG) evt.print(); } // Write to the real stream odos.writeInt(header); odos.writeInt(baos.size()); odos.write(baos.toByteArray(), 0, baos.size()); }
/** * Writes the content of the internal ByteArrayInputStream to the given <code>OutputStream</code>. * * <p>Behaves like: <code> * os.write(content.getByteArray()); * </code> * * @param os The <code>OutputStream</code> to write to. */ @Override public void streamContent(OutputStream os) { try { // vllt mit Streamer.stream arbeiten? // os.write(content.toByteArray()); ByteArrayInputStream bais = new ByteArrayInputStream(content.toByteArray()); Streamer.stream(bais, os, UTF8SharkOutputStream.STREAM_BUFFER_SIZE, content.size()); } catch (IOException ex) { L.e(ex.getMessage(), this); } }
private FileStatus getFileStatus(FileStatus fileStatus) throws IOException { FileStatus status = new FileStatus(); buffer.reset(); DataOutputStream out = new DataOutputStream(buffer); fileStatus.write(out); in.reset(buffer.toByteArray(), 0, buffer.size()); status.readFields(in); return status; }
/** * Parses custom packet serialized by hessian marshaller. * * @param ses Session. * @param buf Buffer containing not parsed bytes. * @param state Parser state. * @return Parsed message. * @throws IOException If packet parsing or deserialization failed. */ @Nullable private GridClientMessage parseCustomPacket(GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException { assert state.packetType() == PacketType.GRIDGAIN; assert state.packet() == null; ByteArrayOutputStream tmp = state.buffer(); int len = state.index(); while (buf.remaining() > 0) { byte b = buf.get(); if (len == 0) { tmp.write(b); if (tmp.size() == 4) { len = U.bytesToInt(tmp.toByteArray(), 0); tmp.reset(); if (len == 0) return PING_MESSAGE; else if (len < 0) throw new IOException( "Failed to parse incoming packet (invalid packet length) [ses=" + ses + ", len=" + len + ']'); state.index(len); } } else { tmp.write(b); if (tmp.size() == len) return marshaller.unmarshal(tmp.toByteArray()); } } return null; }
public void write(int b) throws IOException { // Modifica per IE4.0 if (b == 0x0d) return; // System.out.println("b " + Encoder.intToHexString(b)); buffer.write(b); // strBuffer.app+= Character.to if (b == 0x0a || buffer.size() == BUFFER_SIZE) { flush(); } }
protected String readLine(DataInput in, int maxLength, String errorMessage) throws IOException { byte b; ByteArrayOutputStream baos = new ByteArrayOutputStream(maxLength); while ((b = in.readByte()) != '\n') { if (baos.size() > maxLength) { throw new ProtocolException(errorMessage, true); } baos.write(b); } byte[] sequence = baos.toByteArray(); return new String(sequence, "UTF-8"); }
private int testAvroSer(GenericRecord value, int reps, ByteArrayOutputStream result) throws Exception { BinaryEncoder avroEncoder = null; for (int i = 0; i < reps; ++i) { result.reset(); // reuse? // avroEncoder = ENCODER_FACTORY.binaryEncoder(result, null); avroEncoder = ENCODER_FACTORY.binaryEncoder(result, avroEncoder); WRITER.write(value, avroEncoder); avroEncoder.flush(); } return result.size(); // just to get some non-optimizable number }
public void addLogEntry(String id, LogEntry logEntry) { try { OutputStream outputStream = logStreamCache.getUnchecked(id); ByteArrayOutputStream baos = new ByteArrayOutputStream(); objectMapper.writer().writeValue(baos, logEntry); synchronized (outputStream) { outputStream.write(("\n" + baos.size() + "\n").getBytes()); outputStream.write(baos.toByteArray()); } } catch (Throwable ignored) { // do not log errors when logging } }
public byte[] encode(ItemQuote item) throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); OutputStreamWriter out = new OutputStreamWriter(buf, encoding); out.write(item.itemNumber + " "); if (item.itemDescription.indexOf('\n') != -1) throw new IOException("Inalid description (contains newline)"); out.write(item.itemDescription + "\n" + item.quantity + " " + item.unitPrice + " "); if (item.discounted) out.write('d'); if (item.inStock) out.write('s'); out.write('\n'); out.flush(); if (buf.size() > MAX_WIRE_LENGTH) throw new IOException("Encoded length too long"); return buf.toByteArray(); }
public static int test(int n) throws Exception { PrintStream oldOut = System.out; int sum = 0; for (int i = 0; i < 10; i++) { ByteArrayOutputStream ba = new ByteArrayOutputStream(n * 10); PrintStream newOut = new PrintStream(ba); System.setOut(newOut); doPrint(n); sum += ba.size(); } System.setOut(oldOut); return sum; }
static void testCopyFileToOuputStream(int size) throws IOException { Path source = createTempFile("blah", null); try { byte[] b = new byte[size]; rand.nextBytes(b); write(source, b); ByteArrayOutputStream out = new ByteArrayOutputStream(); long n = copy(source, out); assertTrue(n == size); assertTrue(out.size() == size); byte[] read = out.toByteArray(); assertTrue(Arrays.equals(read, b)); // check output stream is open out.write(0); assertTrue(out.size() == size + 1); } finally { delete(source); } }
@Test public void testgzip() throws Exception { ByteArrayOutputStream b = new ByteArrayOutputStream(); FastOutputStream fos = new FastOutputStream(b); GZIPOutputStream gzos = new GZIPOutputStream(fos); String ss = "Helloooooooooooooooooooo"; writeChars(gzos, ss, 0, ss.length()); gzos.close(); JavaBinCodec.writeVInt(10, fos); fos.flushBuffer(); GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(b.toByteArray(), 0, b.size())); char[] cbuf = new char[ss.length()]; readChars(gzis, cbuf, 0, ss.length()); assertEquals(new String(cbuf), ss); // System.out.println("passes w/o FastInputStream"); ByteArrayInputStream bis = new ByteArrayInputStream(b.toByteArray(), 0, b.size()); gzis = new GZIPInputStream(new FastInputStream(bis)); cbuf = new char[ss.length()]; readChars(gzis, cbuf, 0, ss.length()); assertEquals(new String(cbuf), ss); // System.out.println("passes w FastInputStream"); }
@Test public void copyToCopiesBytesToGivenOutputStream() { // Arrange: final TestContext context = new TestContext(); final WalletNamePasswordPair pair = createPair("n", "p"); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Mockito.when(context.descriptor.openRead(StorableEntityReadMode.Raw)) .thenReturn(new ByteArrayInputStream("test".getBytes())); // Act: context.walletServices.copyTo(pair, outputStream); // Assert: Assert.assertThat(outputStream.size(), IsEqual.equalTo(4)); Assert.assertThat(outputStream.toString(), IsEqual.equalTo("test")); }
// Feed the AAD data to GHASH, pad if necessary void processAAD() { if (aadBuffer != null && aadBuffer.size() > 0) { byte[] aad = aadBuffer.toByteArray(); sizeOfAAD = aad.length; aadBuffer = null; int lastLen = aad.length % AES_BLOCK_SIZE; if (lastLen != 0) { ghashAllToS.update(aad, 0, aad.length - lastLen); byte[] padded = expandToOneBlock(aad, aad.length - lastLen, lastLen); ghashAllToS.update(padded); } else { ghashAllToS.update(aad); } } }
/** code should end smoothly if it encounters no matches between bib and mhld */ @Test public void testNoOutputMessagesWhenNoMatches() throws IOException { // bib46, mhld235 String bibFilePath = testDataParentPath + File.separator + "mhldMergeBibs46.mrc"; String mhldFilePath = testDataParentPath + File.separator + "mhldMergeMhlds235.mrc"; // ensure no error message was printed ByteArrayOutputStream sysBAOS = new ByteArrayOutputStream(); mergeBibAndMhldFiles(bibFilePath, mhldFilePath, sysBAOS); // ensure no error message was printed assertTrue( "Output messages written when none were expected: " + sysBAOS.toString(), sysBAOS.size() == 0); System.out.println("Test testNoOutputMessagesWhenNoMatches() successful"); }
/** * Serializes the input and returns its size in bytes. * * @param object An object whose size we want to determine. * @return The size in bytes of the serialized object */ public static int sizeSerialized(Object... objects) { try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1); ObjectOutputStream in = new ObjectOutputStream(byteStream); for (Object object : objects) { Serializable sobj = (Serializable) object; in.writeObject(sobj); } in.close(); return byteStream.size(); } catch (IOException e) { // This should never happen, since we don't do any disk IO throw new RuntimeException(e); } }
/** * Performs decryption operation for the last time. * * <p>NOTE: For cipher feedback modes which does not perform special handling for the last few * blocks, this is essentially the same as <code>encrypt(...)</code>. Given most modes do not do * special handling, the default impl for this method is to simply call <code>decrypt(...)</code>. * * @param in the input buffer with the data to be decrypted * @param inOfs the offset in <code>cipher</code> * @param len the length of the input data * @param out the buffer for the decryption result * @param outOfs the offset in <code>plain</code> * @return the number of bytes placed into the <code>out</code> buffer */ int decryptFinal(byte[] in, int inOfs, int len, byte[] out, int outOfs) throws IllegalBlockSizeException, AEADBadTagException, ShortBufferException { if (len < tagLenBytes) { throw new AEADBadTagException("Input too short - need tag"); } if (out.length - outOfs < ((ibuffer.size() + len) - tagLenBytes)) { throw new ShortBufferException("Output buffer too small"); } processAAD(); if (len != 0) { ibuffer.write(in, inOfs, len); } // refresh 'in' to all buffered-up bytes in = ibuffer.toByteArray(); inOfs = 0; len = in.length; ibuffer.reset(); byte[] tag = new byte[tagLenBytes]; // get the trailing tag bytes from 'in' System.arraycopy(in, len - tagLenBytes, tag, 0, tagLenBytes); len -= tagLenBytes; if (len > 0) { doLastBlock(in, inOfs, len, out, outOfs, false); } byte[] lengthBlock = getLengthBlock(sizeOfAAD * 8, processed * 8); ghashAllToS.update(lengthBlock); byte[] s = ghashAllToS.digest(); byte[] sOut = new byte[s.length]; GCTR gctrForSToTag = new GCTR(embeddedCipher, this.preCounterBlock); gctrForSToTag.doFinal(s, 0, s.length, sOut, 0); for (int i = 0; i < tagLenBytes; i++) { if (tag[i] != sOut[i]) { throw new AEADBadTagException("Tag mismatch!"); } } return len; }
@Override public byte[] nextMsg() throws IOException { ByteArrayOutputStream messageBuffer = new ByteArrayOutputStream(); int nextByte; while ((nextByte = in.read()) != DELIMITER) { // 如果流已经结束还没有读取到定界符 if (nextByte == -1) { // 如果读取到的流为空,则返回null if (messageBuffer.size() == 0) { return null; } else { // 如果读取到的流不为空,则抛出异常 throw new EOFException("Non-empty message without delimiter"); } } messageBuffer.write(nextByte); } return messageBuffer.toByteArray(); }
@Test public void testContains() throws IOException { System.out.println("test contains"); MutableRoaringBitmap rbm1 = new MutableRoaringBitmap(); for (int k = 0; k < 1000; ++k) { rbm1.add(17 * k); } for (int k = 0; k < 17 * 1000; ++k) { Assert.assertTrue(rbm1.contains(k) == (k / 17 * 17 == k)); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); rbm1.serialize(dos); dos.close(); ByteBuffer bb = ByteBuffer.allocateDirect(bos.size()); bb.put(bos.toByteArray()); bb.flip(); ImmutableRoaringBitmap rrback1 = new ImmutableRoaringBitmap(bb); for (int k = 0; k < 17 * 1000; ++k) { Assert.assertTrue(rrback1.contains(k) == (k / 17 * 17 == k)); } }
private void writeImageToStream(BufferedImage image, HttpExchange exchange) { OutputStream out = null; try { // ByteArrayOutputStream exist because it is necessary to send headers before write to out ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ImageIO.write(image, "png", tmp); tmp.close(); Integer contentLength = tmp.size(); exchange.sendResponseHeaders(200, contentLength); out = exchange.getResponseBody(); out.write(tmp.toByteArray()); } catch (IOException e) { LOG.error(e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e); } } } }