01: /*
02: * $Id: UdpMessageAdapter.java 10489 2008-01-23 17:53:38Z dfeist $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.transport.udp;
12:
13: import org.mule.api.ThreadSafeAccess;
14: import org.mule.api.transport.MessageTypeNotSupportedException;
15: import org.mule.transport.AbstractMessageAdapter;
16:
17: import java.net.DatagramPacket;
18: import java.net.InetAddress;
19:
20: /**
21: * <code>UdpMessageAdapter</code>
22: */
23:
24: public class UdpMessageAdapter extends AbstractMessageAdapter {
25: /**
26: * Serial version
27: */
28: private static final long serialVersionUID = -7767141617682012504L;
29:
30: public static final String ADDRESS_PROPERTY = "packet.address";
31: public static final String PORT_PROPERTY = "packet.port";
32:
33: private byte[] message;
34:
35: public UdpMessageAdapter(Object message)
36: throws MessageTypeNotSupportedException {
37: if (message instanceof DatagramPacket) {
38: DatagramPacket dp = (DatagramPacket) message;
39: this .message = new byte[dp.getLength()];
40: System.arraycopy(dp.getData(), 0, this .message, 0, dp
41: .getLength());
42:
43: InetAddress address = dp.getAddress();
44: if (address != null) {
45: setProperty(ADDRESS_PROPERTY, address);
46: }
47:
48: setProperty(PORT_PROPERTY, new Integer(dp.getPort()));
49: } else {
50: throw new MessageTypeNotSupportedException(message,
51: getClass());
52: }
53: }
54:
55: protected UdpMessageAdapter(UdpMessageAdapter template) {
56: super (template);
57: message = template.message;
58: }
59:
60: /**
61: * Converts the message implementation into a String representation
62: *
63: * @param encoding The encoding to use when transforming the message (if
64: * necessary). The parameter is used when converting from a byte array
65: * @return String representation of the message payload
66: * @throws Exception Implementation may throw an endpoint specific exception
67: */
68: public String getPayloadAsString(String encoding) throws Exception {
69: return new String(message, encoding);
70:
71: }
72:
73: public byte[] getPayloadAsBytes() throws Exception {
74: return message;
75: }
76:
77: public Object getPayload() {
78: return message;
79: }
80:
81: public ThreadSafeAccess newThreadCopy() {
82: return new UdpMessageAdapter(this);
83: }
84:
85: }
|