1 10 11 package org.mule.providers.streaming; 12 13 import org.mule.providers.AbstractMessageAdapter; 14 import org.mule.umo.provider.MessageTypeNotSupportedException; 15 import org.mule.util.StringMessageUtils; 16 17 import org.apache.commons.io.output.ByteArrayOutputStream; 18 import java.io.IOException ; 19 import java.io.OutputStream ; 20 21 25 public class OutStreamMessageAdapter extends AbstractMessageAdapter 26 { 27 30 private static final long serialVersionUID = -299373598028203772L; 31 32 private final OutputStream out; 33 34 public OutStreamMessageAdapter(Object message) throws MessageTypeNotSupportedException 35 { 36 try 37 { 38 if (message instanceof OutputStream) 39 { 40 out = (OutputStream)message; 41 } 42 else if (message instanceof String ) 43 { 44 out = new ByteArrayOutputStream(message.toString().length()); 45 out.write(StringMessageUtils.getBytes(message.toString())); 46 } 47 else if (message instanceof byte[]) 48 { 49 out = new ByteArrayOutputStream(((byte[])message).length); 50 out.write((byte[])message); 51 52 } 53 else 54 { 55 throw new MessageTypeNotSupportedException(message, getClass()); 56 } 57 } 58 catch (IOException e) 59 { 60 throw new MessageTypeNotSupportedException(message, getClass(), e); 61 } 62 63 } 64 65 73 public String getPayloadAsString(String encoding) throws Exception 74 { 75 if (out instanceof ByteArrayOutputStream) 76 { 77 return StringMessageUtils.getString(((ByteArrayOutputStream)out).toByteArray(), encoding); 78 } 79 else 80 { 81 logger.warn("Attempting to get the String contents of a non-ByteArray output stream"); 82 return out.toString(); 83 } 84 } 85 86 92 public byte[] getPayloadAsBytes() throws Exception 93 { 94 if (out instanceof ByteArrayOutputStream) 95 { 96 return ((ByteArrayOutputStream)out).toByteArray(); 97 } 98 else 99 { 100 logger.warn("Attempting to get the bytes of a non-ByteArray output stream"); 101 return StringMessageUtils.getBytes(out.toString()); 102 } 103 } 104 105 108 public Object getPayload() 109 { 110 return out; 111 } 112 113 public void write(String string) throws IOException 114 { 115 out.write(StringMessageUtils.getBytes(string)); 116 } 117 118 public void write(String string, int offset, int len) throws IOException 119 { 120 out.write(StringMessageUtils.getBytes(string), offset, len); 121 } 122 123 public void write(byte[] bytes) throws IOException 124 { 125 out.write(bytes); 126 } 127 128 public void write(byte[] bytes, int offset, int len) throws IOException 129 { 130 out.write(bytes, offset, len); 131 } 132 133 public OutputStream getStream() 134 { 135 return out; 136 } 137 138 public void flush() throws IOException 139 { 140 out.flush(); 141 } 142 143 public void close() throws IOException 144 { 145 out.close(); 146 } 147 } 148 | Popular Tags |