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 public void errorReceived(Throwable t) {
042 _log.error(t, t);
043 }
044
045 public void process(DatagramPacket packet) {
046 byte[] bytes = packet.getData();
047
048 if (_gzipData) {
049 try {
050 bytes = getUnzippedBytes(bytes);
051 }
052 catch (Exception e) {
053 _log.error(e, e);
054 }
055 }
056
057 if (_shortData) {
058 byte[] temp = new byte[96];
059
060 System.arraycopy(bytes, 0, temp, 0, 96);
061
062 bytes = temp;
063 }
064
065 StringBundler sb = new StringBundler(4);
066
067 sb.append("[");
068 sb.append(packet.getSocketAddress());
069 sb.append("] ");
070 sb.append(new String(bytes));
071
072 if (_log.isInfoEnabled()) {
073 _log.info(sb);
074 }
075 }
076
077 protected byte[] getUnzippedBytes(byte[] bytes) throws Exception {
078 InputStream is = new GZIPInputStream(
079 new UnsyncByteArrayInputStream(bytes));
080 UnsyncByteArrayOutputStream ubaos =
081 new UnsyncByteArrayOutputStream(bytes.length);
082
083 byte[] buffer = new byte[1500];
084
085 int c = 0;
086
087 while (true) {
088 if (c == -1) {
089 break;
090 }
091
092 c = is.read(buffer, 0, 1500);
093
094 if (c != -1) {
095 ubaos.write(buffer, 0, c);
096 }
097 }
098
099 is.close();
100
101 ubaos.flush();
102 ubaos.close();
103
104 return ubaos.toByteArray();
105 }
106
107 private static Log _log = LogFactory.getLog(MulticastDatagramHandler.class);
108
109 private boolean _gzipData;
110 private boolean _shortData;
111
112 }