001    package biz.hammurapi.metrics;
002    
003    import java.io.ObjectOutputStream;
004    import java.net.Socket;
005    import java.util.List;
006    
007    import biz.hammurapi.config.ConfigurationException;
008    import biz.hammurapi.metrics.BatchingSliceConsumer.SliceEntry;
009    
010    /**
011     * Sends slices to remote slice consumer server.
012     * @author Pavel Vlasov
013     */
014    public class SocketSliceConsumer extends BatchingSliceConsumer {
015            
016            public static final int DEFAULT_PORT = 9814;
017            private static final String LOCALHOST = "localhost";
018            
019            private String address = LOCALHOST;
020            private int port = DEFAULT_PORT;
021            private String id = Long.toString(System.currentTimeMillis(), Character.MAX_RADIX);
022            
023            /**
024             * Sets server address. Default is "localhost"
025             * @param address
026             */
027            public void setAddress(String address) {
028                    this.address = address;
029            }
030            
031            /**
032             * Sets server port. Default is 9814
033             * @param port
034             */
035            public void setPort(int port) {
036                    this.port = port;
037            }
038            
039            /**
040             * Sets client ID to differentiate it from other clients.
041             * Defaults to 
042             * @param id
043             */
044            public void setId(String id) {
045                    this.id = id;
046            }
047            
048            public void start() throws ConfigurationException {
049                    super.start();
050                    System.out.println("[SocketSliceConsumer] ID="+id);
051            }
052            
053            /**
054             * Sends slices to a server socket.
055             */
056            protected boolean processSlices(List<SliceEntry> slices) {
057                    try {
058                            Socket socket = new Socket(address, port);
059                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
060                            oos.writeObject(id);
061                            oos.writeObject(slices);
062                            oos.close();
063                            socket.close();
064                            return true;
065                    } catch (Exception e) {
066                            System.err.println("[Socket slice consumer] ERROR: Could not send slices to the server: "+e);
067                            return false;
068                    }                               
069            }
070    
071    }