public static byte[] decode(MessageHeader message, byte[] content) throws MessageFormatException { try { InputStream is = new ByteArrayInputStream(content); is = decode(message, is); ByteArrayOutputStream copy = new ByteArrayOutputStream(); byte[] buff = new byte[4096]; int got; while ((got = is.read(buff)) > 0) copy.write(buff, 0, got); return copy.toByteArray(); } catch (IOException ioe) { throw new MessageFormatException("Malformed encoded content: " + ioe.getMessage(), ioe); } }
public static byte[] encode(MessageHeader header, byte[] content) throws MessageFormatException { InputStream contentStream = new ByteArrayInputStream(content); contentStream = encode(header, contentStream); ByteArrayOutputStream copy = new ByteArrayOutputStream(); byte[] buff = new byte[4096]; int got; try { while ((got = contentStream.read(buff)) > 0) copy.write(buff, 0, got); } catch (IOException ioe) { throw new MessageFormatException("Error encoding content", ioe); } return copy.toByteArray(); }
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 static void buffer(StreamingMessage message, MutableBufferedMessage buffered, int max) throws IOException, SizeLimitExceededException { buffered.setHeader(message.getHeader()); InputStream in = message.getContent(); if (in != null) { ByteArrayOutputStream copy; copy = new SizeLimitedByteArrayOutputStream(max); byte[] b = new byte[1024]; int got; try { while ((got = in.read(b)) > -1) { copy.write(b, 0, got); } buffered.setContent(copy.toByteArray()); } catch (SizeLimitExceededException slee) { buffered.setContent(copy.toByteArray()); throw slee; } } }