UDPService.java

Index Score
com.limegroup.gnutella
FrostWire

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0034JAVA0034 Missing braces in if statement
DECL_COMMENTSComments in declarations
JAVA0020JAVA0020 Field name does not have required form
EXITSProcedure exits
SIZESize of the file in bytes
CYCLOMATICCyclomatic complexity
UNIQUE_OPERANDSNumber of unique operands
LINE_COMMENTNumber of line comments
PROGRAM_VOCABHalstead program vocabulary
EXEC_COMMENTSComments in executable code
ELOCEffective lines of code
OPERATORSNumber of operators
RETURNSNumber of return points from functions
LINESNumber of lines in the source file
PROGRAM_LENGTHHalstead program length
INTERFACE_COMPLEXITYInterface complexity
DOC_COMMENTNumber of javadoc comment lines
LOCLines of code
LOGICAL_LINESNumber of statements
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
OPERANDSNumber of operands
COMPARISONSNumber of comparison operators
FUNCTIONSNumber of function declarations
COMMENTSComment lines
BLOCKSNumber of blocks
PARAMSNumber of formal parameter declarations
JAVA0049JAVA0049 Nested block at depth N (maximum: M)
JAVA0117JAVA0117 Missing javadoc: method 'method'
JAVA0170JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0177JAVA0177 Variable declaration missing initializer
JAVA0166JAVA0166 Generic exception caught
UNIQUE_OPERATORSNumber of unique operators
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0076JAVA0076 Use of magic number
JAVA0128JAVA0128 Public constructor in non-public class
NEST_DEPTHMaximum nesting depth
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0035JAVA0035 Missing braces in for statement
JAVA0126JAVA0126 Method declares unchecked exception in throws
WHITESPACENumber of whitespace lines
JAVA0264JAVA0264 Integer math in long context - check for overflow
JAVA0109JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0030JAVA0030 Private field not used
JAVA0013JAVA0013 Non-blank final field is not static
JAVA0100JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0130JAVA0130 Non-static method does not use instance fields
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
package com.limegroup.gnutella; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.limewire.inspection.Inspectable; import org.limewire.inspection.InspectionPoint; import org.limewire.io.ByteBufferOutputStream; import org.limewire.io.IpPort; import org.limewire.io.NetworkInstanceUtils; import org.limewire.io.NetworkUtils; import org.limewire.nio.NIODispatcher; import org.limewire.nio.observer.ReadWriteObserver; import org.limewire.security.AddressSecurityToken; import org.limewire.security.MACCalculator; import org.limewire.security.MACCalculatorRepositoryManager; import org.limewire.service.ErrorService; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.inject.name.Named; import com.limegroup.gnutella.filters.IPFilter; import com.limegroup.gnutella.guess.GUESSEndpoint; import com.limegroup.gnutella.messages.BadPacketException; import com.limegroup.gnutella.messages.Message; import com.limegroup.gnutella.messages.MessageFactory; import com.limegroup.gnutella.messages.PingReply; import com.limegroup.gnutella.messages.PingRequest; import com.limegroup.gnutella.messages.PingRequestFactory; import com.limegroup.gnutella.messages.Message.Network; import com.limegroup.gnutella.messages.vendor.ReplyNumberVendorMessage; import com.limegroup.gnutella.settings.ConnectionSettings; /** * This class handles UDP messaging services. It both sends and * receives messages, routing received messages to their appropriate * handlers. This also handles issues related to the GUESS proposal, * such as making sure that the UDP and TCP port match and sending * UDP acks for queries. * * @see UDPReplyHandler * @see MessageRouter * @see QueryUnicaster * */ @Singleton public class UDPService implements ReadWriteObserver { private static final Log LOG = LogFactory.getLog(UDPService.class); private static final MACCalculator PING_GENERATOR = MACCalculatorRepositoryManager.createDefaultCalculatorFactory().createMACCalculator(); /** * The DatagramChannel we're reading from & writing to. */ private DatagramChannel _channel; /** * The list of messages to be sent, as SendBundles. */ private final List<SendBundle> OUTGOING_MSGS; /** * The buffer that's re-used for reading incoming messages. */ private final ByteBuffer BUFFER; /** * The maximum size of a UDP message we'll accept. */ private final int BUFFER_SIZE = 1024 * 2; /** True if the UDPService has ever received a solicited incoming UDP * packet. */ private volatile boolean _acceptedSolicitedIncoming = false; /** True if the UDPService has ever received a unsolicited incoming UDP * packet. */ private volatile boolean _acceptedUnsolicitedIncoming = false; /** The last time the _acceptedUnsolicitedIncoming was set. */ private long _lastUnsolicitedIncomingTime = 0; /** * The last time we received any udp packet */ private volatile long _lastReceivedAny = 0; /** The last time we sent a UDP Connect Back. */ private long _lastConnectBackTime = System.currentTimeMillis(); void resetLastConnectBackTime() { _lastConnectBackTime = System.currentTimeMillis() - acceptor.get().getIncomingExpireTime(); } /** Whether our NAT assigns stable ports for successive connections * LOCKING: this */ private boolean _portStable = true; /** The last reported port as seen from the outside * LOCKING: this */ private int _lastReportedPort; /** * The number of pongs carrying IP:Port info we have received. * LOCKING: this */ private int _numReceivedIPPongs; /** * The GUID that we advertise out for UDPConnectBack requests. */ private final GUID CONNECT_BACK_GUID = new GUID(GUID.makeGuid()); /** * The GUID that we send for Pings, useful to test solicited support. */ private final GUID SOLICITED_PING_GUID = new GUID(GUID.makeGuid()); /** * Determines if this was ever started. */ private boolean _started = false; /** * The time between UDP pings. Used by the PeriodicPinger. This is * useful for nodes behind certain firewalls (notably the MS firewall). */ private static final long PING_PERIOD = 85 * 1000; // 85 seconds /** * A buffer used for reading the header of incoming messages. */ private static final byte[] IN_HEADER_BUF = new byte[23]; private final NetworkManager networkManager; private final Provider<MessageDispatcher> messageDispatcher; private final Provider<IPFilter> hostileFilter; private final Provider<ConnectionManager> connectionManager; private final Provider<MessageRouter> messageRouter; private final Provider<Acceptor> acceptor; private final Provider<QueryUnicaster> queryUnicaster; private final ScheduledExecutorService backgroundExecutor; private final ConnectionServices connectionServices; private final MessageFactory messageFactory; private final PingRequestFactory pingRequestFactory; private final NetworkInstanceUtils networkInstanceUtils; @InspectionPoint("udp sent messages") private final Message.MessageCounter sentMessageCounter = new Message.MessageCounter(50); @InspectionPoint("fwt capable") @SuppressWarnings("unused") private final Inspectable fwtCapable = new Inspectable() { public Object inspect() { return canDoFWT(); } }; @Inject public UDPService(NetworkManager networkManager, Provider<MessageDispatcher> messageDispatcher, @Named("hostileFilter") Provider<IPFilter> hostileFilter, Provider<ConnectionManager> connectionManager, Provider<MessageRouter> messageRouter, Provider<Acceptor> acceptor, Provider<QueryUnicaster> queryUnicaster, @Named("backgroundExecutor") ScheduledExecutorService backgroundExecutor, ConnectionServices connectionServices, MessageFactory messageFactory, PingRequestFactory pingRequestFactory, NetworkInstanceUtils networkInstanceUtils) { this.networkManager = networkManager; this.messageDispatcher = messageDispatcher; this.hostileFilter = hostileFilter; this.connectionManager = connectionManager; this.messageRouter = messageRouter; this.acceptor = acceptor; this.queryUnicaster = queryUnicaster; this.backgroundExecutor = backgroundExecutor; this.connectionServices = connectionServices; this.messageFactory = messageFactory; this.pingRequestFactory = pingRequestFactory; this.networkInstanceUtils = networkInstanceUtils; OUTGOING_MSGS = new LinkedList<SendBundle>(); byte[] backing = new byte[BUFFER_SIZE]; BUFFER = ByteBuffer.wrap(backing); scheduleServices(); } /** * Schedules IncomingValidator & PeriodicPinger for periodic use. */ protected void scheduleServices() { backgroundExecutor.scheduleWithFixedDelay(new IncomingValidator(), acceptor.get().getTimeBetweenValidates(), acceptor.get().getTimeBetweenValidates(), TimeUnit.MILLISECONDS); backgroundExecutor.scheduleWithFixedDelay(new PeriodicPinger(), 0, PING_PERIOD, TimeUnit.MILLISECONDS); } /** @return The GUID to send for UDPConnectBack attempts.... */ public GUID getConnectBackGUID() { return CONNECT_BACK_GUID; } /** @return The GUID to send for Solicited Ping attempts.... */ public GUID getSolicitedGUID() { return SOLICITED_PING_GUID; } /** * Starts listening for UDP messages & allowing UDP messages to be written. */ public void start() { DatagramChannel channel; synchronized(this) { _started = true; channel = _channel; } if(channel != null) NIODispatcher.instance().registerReadWrite(channel, this); } /** * Returns a new DatagramSocket that is bound to the given port. This * value should be passed to setListeningSocket(DatagramSocket) to commit * to the new port. If setListeningSocket is NOT called, you should close * the return socket. * @return a new DatagramSocket that is bound to the specified port. * @exception IOException Thrown if the DatagramSocket could not be * created. */ DatagramSocket newListeningSocket(int port) throws IOException { try { DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); DatagramSocket s = channel.socket(); s.setReceiveBufferSize(64*1024); s.setSendBufferSize(64*1024); s.bind(new InetSocketAddress(port)); return s; } catch (SecurityException se) { throw new IOException("security exception on port: "+port); } } /** * Changes the DatagramSocket used for sending/receiving. Typically called * by Acceptor to commit to the new port. * @param datagramSocket the new listening socket, which must be be the * return value of newListeningSocket(int). A value of null disables * UDP sending and receiving. */ void setListeningSocket(DatagramSocket datagramSocket) { if(_channel != null) { try { _channel.close(); } catch(IOException ignored) {} } if(datagramSocket != null) { boolean wasStarted; synchronized(this) { _channel = datagramSocket.getChannel(); if(_channel == null) throw new IllegalArgumentException("No channel!"); wasStarted = _started; // set the port in the FWT records _lastReportedPort=_channel.socket().getLocalPort(); _portStable=true; } // If it was already started at one point, re-start to register this new channel. if(wasStarted) start(); } } int getListeningPort() { synchronized(this) { if(_channel != null) return _channel.socket().getLocalPort(); else return -1; } } /** * Shuts down this service. */ public void shutdown() { setListeningSocket(null); } /** * Notification that a read can happen. */ public void handleRead() throws IOException { try { while (true) { BUFFER.clear(); SocketAddress from; try { from = _channel.receive(BUFFER); } catch (IOException iox) { break; } catch (Error error) { // Stupid implementations giving bogus errors. Grrr!. break; } // no packet. if (from == null) break; if (!(from instanceof InetSocketAddress)) { ErrorService.error(new RuntimeException("non-inet SocketAddress: " + from)); continue; } InetSocketAddress addr = (InetSocketAddress) from; if (!NetworkUtils.isValidAddress(addr.getAddress())) continue; if (!NetworkUtils.isValidPort(addr.getPort())) continue; // don't go further if filtered. if (!hostileFilter.get().allow(addr.getAddress().getAddress())) return; byte[] data = BUFFER.array(); int length = BUFFER.position(); try { // we do things the old way temporarily InputStream in = new ByteArrayInputStream(data, 0, length); Message message = messageFactory.read(in, Network.UDP, IN_HEADER_BUF, addr); if (message == null) continue; processMessage(message, addr); } catch (IOException ignored) { } catch (BadPacketException ignored) { } } } catch(Throwable t) { // Do not let the exceptions propogate out, as that could // close UDPService. ErrorService.error(t); } } /** * Notification that an IOException occurred while reading/writing. */ public void handleIOException(IOException iox) { if( !(iox instanceof java.nio.channels.ClosedChannelException ) ) ErrorService.error(iox, "UDP Error."); else LOG.trace("Swallowing a UDPService ClosedChannelException", iox); } /** * Processes a single message. */ protected void processMessage(Message message, InetSocketAddress addr) { if (!hostileFilter.get().allow(message)) return; if (message instanceof PingReply) mutateGUID(message.getGUID(), addr.getAddress(), addr.getPort()); updateState(message, addr); messageDispatcher.get().dispatchUDP(message, addr); } /** Updates internal state of the UDP Service. */ private void updateState(Message message, InetSocketAddress addr) { _lastReceivedAny = System.currentTimeMillis(); if (isValidForIncoming(addr)) _acceptedSolicitedIncoming = true; if (!isGUESSCapable()) { if (message instanceof PingRequest) { GUID guid = new GUID(message.getGUID()); if(CONNECT_BACK_GUID.equals(guid) && isValidForIncoming(addr)) { _acceptedUnsolicitedIncoming = true; } _lastUnsolicitedIncomingTime = _lastReceivedAny; } else if (message instanceof PingReply) { GUID guid = new GUID(message.getGUID()); if(!SOLICITED_PING_GUID.equals(guid) || !isValidForIncoming(addr )) return; PingReply r = (PingReply)message; if (r.getMyPort() != 0) { synchronized(this){ _numReceivedIPPongs++; if (_numReceivedIPPongs==1) _lastReportedPort=r.getMyPort(); else if (_lastReportedPort!=r.getMyPort()) { _portStable = false; _lastReportedPort = r.getMyPort(); } } } } } // ReplyNumberVMs are always sent in an unsolicited manner, // so we can use this fact to keep the last unsolicited up // to date if (message instanceof ReplyNumberVendorMessage) _lastUnsolicitedIncomingTime = _lastReceivedAny; } public static void mutateGUID(byte[] guid, InetAddress ip, int port) { byte[] qk = PING_GENERATOR.getMACBytes(new AddressSecurityToken.AddressTokenData(ip,port)); for (int i = 0; i < qk.length; i++) guid[i] =(byte)(guid[i] ^ qk[i]); } /** * Determines whether or not the specified message is valid for setting * LimeWire as accepting UDP messages (solicited or unsolicited). */ private boolean isValidForIncoming(InetSocketAddress addr) { String host = addr.getAddress().getHostAddress(); // If addr is connected to us, then return false. Otherwise (not connected), only return true if either: // 1) the non-connected party is NOT private // OR // 2) the non-connected party _is_ private, and the LOCAL_IS_PRIVATE is set to false return !connectionManager.get().isConnectedTo(host) && !networkInstanceUtils.isPrivateAddress(addr.getAddress()) ; } /** * Sends the specified <tt>Message</tt> to the specified host. * * @param msg the <tt>Message</tt> to send * @param host the host to send the message to */ public void send(Message msg, IpPort host) { send(msg, host.getInetSocketAddress()); } /** * Sends the <tt>Message</tt> via UDP to the port and IP address specified. * This method should not be called if the client is not GUESS enabled. * * @param msg the <tt>Message</tt> to send * @param ip the <tt>InetAddress</tt> to send to * @param port the port to send to * @param err an <tt>ErrorCallback<tt> if you want to be notified errors * @throws IllegalArgumentException if msg, ip, or err is null. */ public void send(Message msg, InetAddress ip, int port) { send(msg, new InetSocketAddress(ip, port)); } /** * Sends the specified <tt>Message</tt> to the specified host. * * @param msg the <tt>Message</tt> to send * @param host the host to send the message to */ public void send(Message msg, InetSocketAddress addr) { if (msg == null) throw new IllegalArgumentException("Null Message"); if (!NetworkUtils.isValidSocketAddress(addr)) throw new IllegalArgumentException("Invalid addr: " + addr); if(_channel == null || _channel.socket().isClosed()) return; // ignore if not open. if (LOG.isTraceEnabled()) { LOG.trace("Sending message: " + msg + "to " + addr); } int length = msg.getTotalLength(); ByteBuffer buffer = NIODispatcher.instance().getBufferCache().getHeap(length); if(buffer.remaining() != length) throw new IllegalStateException("retrieved a buffer with wrong remaining! " + "wanted: " + length + ", had: " + buffer.remaining() + ", position: " + buffer.position() + ", limit: " + buffer.limit()); ByteBufferOutputStream baos = new ByteBufferOutputStream(buffer); try { msg.writeQuickly(baos); } catch(IOException e) { // this should not happen -- we should always be able to write // to this output stream in memory ErrorService.error(e); // can't send the hit, so return return; } buffer.flip(); if (msg instanceof PingRequest) mutateGUID(buffer.array(), addr.getAddress(), addr.getPort()); sentMessageCounter.countMessage(msg); send(buffer, addr, false); } public void send(ByteBuffer buffer, InetSocketAddress addr, boolean custom) { synchronized(OUTGOING_MSGS) { OUTGOING_MSGS.add(new SendBundle(buffer, addr, custom)); if(_channel != null) NIODispatcher.instance().interestWrite(_channel, true); } } /** * Notification that a write can happen. */ public boolean handleWrite() throws IOException { try { synchronized(OUTGOING_MSGS) { while(!OUTGOING_MSGS.isEmpty()) { boolean releaseBuffer = true; SendBundle bundle = OUTGOING_MSGS.remove(0); try { if(_channel.send(bundle.buffer, bundle.addr) == 0) { // we removed the bundle from the list but couldn't send it, // so we have to put it back in. OUTGOING_MSGS.add(0, bundle); releaseBuffer = false; return true; // no room left to send. } } catch(IOException ignored) { LOG.warn("Ignoring exception on socket", ignored); } finally { if(bundle.custom) { bundle.buffer.rewind(); releaseBuffer = false; } if (releaseBuffer) NIODispatcher.instance().getBufferCache().release(bundle.buffer); } } // if there's no data left to send, we don't wanna be notified of write events. NIODispatcher.instance().interestWrite(_channel, false); return false; } } catch(Throwable t) { // Don't let it propogate, since that could close UDPService! ErrorService.error(t); return true; } } /** Wrapper for outgoing data */ private static class SendBundle { private final ByteBuffer buffer; private final SocketAddress addr; private final boolean custom; SendBundle(ByteBuffer b, InetSocketAddress addr, boolean custom) { buffer = b; this.addr = addr; this.custom = custom; } } /** * Returns whether or not this node is capable of sending its own * GUESS queries. This would not be the case only if this node * has not successfully received an incoming UDP packet. * * @return <tt>true</tt> if this node is capable of running its own * GUESS queries, <tt>false</tt> otherwise */ public boolean isGUESSCapable() { return canReceiveUnsolicited() && canReceiveSolicited(); } /** * Returns whether or not this node is capable of receiving UNSOLICITED * UDP packets. It is false until a UDP ConnectBack ping has been received. * * @return <tt>true</tt> if this node has accepted a UNSOLICITED UDP packet. */ public boolean canReceiveUnsolicited() { return _acceptedUnsolicitedIncoming; } /** * Returns whether or not this node is capable of receiving SOLICITED * UDP packets. * * @return <tt>true</tt> if this node has accepted a SOLICITED UDP packet. */ public boolean canReceiveSolicited() { return _acceptedSolicitedIncoming; } /** * * @return whether this node can do Firewall-to-firewall transfers. * Until we get back any udp packet, the answer is no. * If we have received an udp packet but are not connected, or haven't * received a pong carrying ip info yet, see if we ever disabled fwt in the * past. * If we are connected and have gotten a single ip pong, our port must be * the same as our tcp port or our forced tcp port. * If we have received more than one ip pong, they must all report the same * port. */ public boolean canDoFWT(){ // this does not affect EVER_DISABLED_FWT. if (!canReceiveSolicited()) return false; if (!connectionServices.isConnected()) return !ConnectionSettings.LAST_FWT_STATE.getValue(); boolean ret = true; synchronized(this) { if (_numReceivedIPPongs < 1) return !ConnectionSettings.LAST_FWT_STATE.getValue(); if (LOG.isTraceEnabled()) { LOG.trace("stable "+_portStable+ " last reported port "+_lastReportedPort+ " our external port "+networkManager.getPort()+ " our non-forced port "+acceptor.get().getPort(false)+ " number of received IP pongs "+_numReceivedIPPongs+ " valid external addr "+NetworkUtils.isValidAddress( networkManager.getExternalAddress())); } System.out.println("DEBUG PING PORT stable "+_portStable+ " last reported port "+_lastReportedPort+ " our external port "+networkManager.getPort()+ " our non-forced port "+acceptor.get().getPort(false)+ " number of received IP pongs "+_numReceivedIPPongs+ " valid external addr "+NetworkUtils.isValidAddress( networkManager.getExternalAddress())); ret= NetworkUtils.isValidAddress(networkManager.getExternalAddress()) && _portStable; if (_numReceivedIPPongs == 1){ ret = ret && (_lastReportedPort == acceptor.get().getPort(false) || _lastReportedPort == networkManager.getPort()); } } ConnectionSettings.LAST_FWT_STATE.setValue(!ret); return ret; } // Some getters for bug reporting public boolean portStable() { return _portStable; } public int receivedIpPong() { return _numReceivedIPPongs; } public int lastReportedPort() { return _lastReportedPort; } /** * @return the stable UDP port as seen from the outside. * If we have received more than one IPPongs and they report * the same port, we return that. * If we have received just one IPpong, and if its address * matches either our local port or external port, return that. * If we have not received any IPpongs, return whatever * RouterService thinks our port is. */ public int getStableUDPPort() { int localPort = acceptor.get().getPort(false); int forcedPort = networkManager.getPort(); synchronized(this) { if (_portStable && _numReceivedIPPongs > 1) return _lastReportedPort; if (_numReceivedIPPongs == 1 && (localPort == _lastReportedPort || forcedPort == _lastReportedPort)) return _lastReportedPort; } return forcedPort; // we haven't received an ippong. } /** * Sets whether or not this node is capable of receiving SOLICITED * UDP packets. This is useful for testing UDPConnections. * */ public void setReceiveSolicited(boolean value) { _acceptedSolicitedIncoming = value; } public long getLastReceivedTime() { return _lastReceivedAny; } /** * Returns whether or not the UDP socket is listening for incoming * messsages. * * @return <tt>true</tt> if the UDP socket is listening for incoming * UDP messages, <tt>false</tt> otherwise */ public boolean isListening() { if(_channel == null) return false; return (_channel.socket().getLocalPort() != -1); } /** * Overrides Object.toString to give more informative information * about the class. * * @return the <tt>DatagramSocket</tt> data */ public String toString() { return "UDPService::channel: " + _channel; } private static class MLImpl implements MessageListener { public boolean _gotIncoming = false; public void processMessage(Message m, ReplyHandler handler) { if ((m instanceof PingRequest)) _gotIncoming = true; } public void registered(byte[] guid) {} public void unregistered(byte[] guid) {} } private class IncomingValidator implements Runnable { public IncomingValidator() {} public void run() { // clear and revalidate if 1) we haven't had in incoming in an hour // or 2) we've never had incoming and we haven't checked in an hour final long currTime = System.currentTimeMillis(); if ( (_acceptedUnsolicitedIncoming && //1) ((currTime - _lastUnsolicitedIncomingTime) > acceptor.get().getIncomingExpireTime())) || (!_acceptedUnsolicitedIncoming && //2) ((currTime - _lastConnectBackTime) > acceptor.get().getIncomingExpireTime())) ) { final GUID cbGuid = new GUID(GUID.makeGuid()); final MLImpl ml = new MLImpl(); messageRouter.get().registerMessageListener(cbGuid.bytes(), ml); // send a connectback request to a few peers and clear if(connectionManager.get().sendUDPConnectBackRequests(cbGuid)) { _lastConnectBackTime = System.currentTimeMillis(); Runnable checkThread = new Runnable() { public void run() { if ((_acceptedUnsolicitedIncoming && (_lastUnsolicitedIncomingTime < currTime)) || (!_acceptedUnsolicitedIncoming)) { // we set according to the message listener _acceptedUnsolicitedIncoming = ml._gotIncoming; } messageRouter.get().unregisterMessageListener(cbGuid.bytes(), ml); } }; backgroundExecutor.schedule(checkThread, acceptor.get().getWaitTimeAfterRequests(), TimeUnit.MILLISECONDS); } else messageRouter.get().unregisterMessageListener(cbGuid.bytes(), ml); } } } private class PeriodicPinger implements Runnable { public void run() { // straightforward - send a UDP ping to a host. it doesn't really // matter who the guy is - we are just sending to open up any // potential firewall to UDP traffic GUESSEndpoint ep = queryUnicaster.get().getUnicastEndpoint(); if (ep == null) return; // only do this if you can receive some form of UDP traffic. if (!canReceiveSolicited() && !canReceiveUnsolicited()) return; // good to use the solicited guid PingRequest pr = pingRequestFactory.createPingRequest(getSolicitedGUID().bytes(), (byte)1, (byte)0); pr.addIPRequest(); send(pr, ep.getInetAddress(), ep.getPort()); } } }

The table below shows all metrics for UDPService.java.

MetricValueDescription
BLOCKS88.00Number of blocks
BLOCK_COMMENT 0.00Number of block comment lines
COMMENTS224.00Comment lines
COMMENT_DENSITY 0.52Comment density
COMPARISONS66.00Number of comparison operators
CYCLOMATIC121.00Cyclomatic complexity
DECL_COMMENTS44.00Comments in declarations
DOC_COMMENT191.00Number of javadoc comment lines
ELOC432.00Effective lines of code
EXEC_COMMENTS21.00Comments in executable code
EXITS105.00Procedure exits
FUNCTIONS42.00Number of function declarations
HALSTEAD_DIFFICULTY78.32Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY110.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 1.00JAVA0007 Should not declare public field
JAVA0008 1.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 1.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA002011.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 1.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA003435.00JAVA0034 Missing braces in if statement
JAVA0035 1.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 3.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 1.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 4.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 1.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 8.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 2.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 2.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 1.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 2.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 1.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 8.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 1.00JAVA0128 Public constructor in non-public class
JAVA0130 1.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 1.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145295.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 3.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 3.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 3.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 1.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 1.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 0.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES848.00Number of lines in the source file
LINE_COMMENT33.00Number of line comments
LOC510.00Lines of code
LOGICAL_LINES247.00Number of statements
LOOPS 3.00Number of loops
NEST_DEPTH 6.00Maximum nesting depth
OPERANDS1102.00Number of operands
OPERATORS2265.00Number of operators
PARAMS41.00Number of formal parameter declarations
PROGRAM_LENGTH3367.00Halstead program length
PROGRAM_VOCAB458.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS69.00Number of return points from functions
SIZE30730.00Size of the file in bytes
UNIQUE_OPERANDS401.00Number of unique operands
UNIQUE_OPERATORS57.00Number of unique operators
WHITESPACE114.00Number of whitespace lines