001
014
015 package com.liferay.util.transport;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
018 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
019 import com.liferay.portal.kernel.util.StringBundler;
020
021 import java.io.InputStream;
022
023 import java.net.DatagramPacket;
024
025 import java.util.zip.GZIPInputStream;
026
027 import org.apache.commons.logging.Log;
028 import org.apache.commons.logging.LogFactory;
029
030
034 public class MulticastDatagramHandler implements DatagramHandler {
035
036 public MulticastDatagramHandler(boolean gzipData, boolean shortData) {
037 _gzipData = gzipData;
038 _shortData = shortData;
039 }
040
041 @Override
042 public void errorReceived(Throwable t) {
043 _log.error(t, t);
044 }
045
046 @Override
047 public void process(DatagramPacket packet) {
048 byte[] bytes = packet.getData();
049
050 if (_gzipData) {
051 try {
052 bytes = getUnzippedBytes(bytes);
053 }
054 catch (Exception e) {
055 _log.error(e, e);
056 }
057 }
058
059 if (_shortData) {
060 byte[] temp = new byte[96];
061
062 System.arraycopy(bytes, 0, temp, 0, 96);
063
064 bytes = temp;
065 }
066
067 StringBundler sb = new StringBundler(4);
068
069 sb.append("[");
070 sb.append(packet.getSocketAddress());
071 sb.append("] ");
072 sb.append(new String(bytes));
073
074 if (_log.isInfoEnabled()) {
075 _log.info(sb);
076 }
077 }
078
079 protected byte[] getUnzippedBytes(byte[] bytes) throws Exception {
080 InputStream is = new GZIPInputStream(
081 new UnsyncByteArrayInputStream(bytes));
082 UnsyncByteArrayOutputStream ubaos = new UnsyncByteArrayOutputStream(
083 bytes.length);
084
085 byte[] buffer = new byte[1500];
086
087 int c = 0;
088
089 while (true) {
090 if (c == -1) {
091 break;
092 }
093
094 c = is.read(buffer, 0, 1500);
095
096 if (c != -1) {
097 ubaos.write(buffer, 0, c);
098 }
099 }
100
101 is.close();
102
103 ubaos.flush();
104 ubaos.close();
105
106 return ubaos.toByteArray();
107 }
108
109 private static Log _log = LogFactory.getLog(MulticastDatagramHandler.class);
110
111 private boolean _gzipData;
112 private boolean _shortData;
113
114 }