HTTPUploadManager.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
EXITSProcedure exits
LINE_COMMENTNumber of line comments
JAVA0143JAVA0143 Synchronized method
EXEC_COMMENTSComments in executable code
SIZESize of the file in bytes
UNIQUE_OPERANDSNumber of unique operands
PROGRAM_VOCABHalstead program vocabulary
COMPARISONSNumber of comparison operators
LOGICAL_LINESNumber of statements
DECL_COMMENTSComments in declarations
CYCLOMATICCyclomatic complexity
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
OPERATORSNumber of operators
PROGRAM_LENGTHHalstead program length
LINESNumber of lines in the source file
ELOCEffective lines of code
OPERANDSNumber of operands
LOCLines of code
INTERFACE_COMPLEXITYInterface complexity
RETURNSNumber of return points from functions
DOC_COMMENTNumber of javadoc comment lines
BLOCKSNumber of blocks
COMMENTSComment lines
FUNCTIONSNumber of function declarations
PARAMSNumber of formal parameter declarations
UNIQUE_OPERATORSNumber of unique operators
WHITESPACENumber of whitespace lines
JAVA0130JAVA0130 Non-static method does not use instance fields
JAVA0008JAVA0008 Empty catch block
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
JAVA0100JAVA0100 Class contains N non-final fields (maximum: M)
LOOPSNumber of loops
JAVA0068JAVA0068 Modifiers not declared in recommended order
JAVA0145JAVA0145 Tab character used in source file
package com.limegroup.gnutella; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpException; import org.apache.http.HttpInetConnection; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.nio.NHttpConnection; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.limewire.collection.Buffer; import org.limewire.collection.FixedsizeForgetfulHashMap; import org.limewire.http.HttpAcceptorListener; import org.limewire.util.FileLocker; import org.limewire.util.FileUtils; import org.limewire.util.Objects; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.limegroup.gnutella.Uploader.UploadStatus; import com.limegroup.gnutella.auth.ContentManager; import com.limegroup.gnutella.http.HttpContextParams; import com.limegroup.gnutella.settings.ConnectionSettings; import com.limegroup.gnutella.settings.UploadSettings; import com.limegroup.gnutella.statistics.TcpBandwidthStatistics; import com.limegroup.gnutella.uploader.FileRequestHandler; import com.limegroup.gnutella.uploader.HTTPUploadSession; import com.limegroup.gnutella.uploader.HTTPUploadSessionManager; import com.limegroup.gnutella.uploader.HTTPUploader; import com.limegroup.gnutella.uploader.HttpRequestHandlerFactory; import com.limegroup.gnutella.uploader.UploadSlotManager; import com.limegroup.gnutella.uploader.UploadType; /** * Manages {@link HTTPUploader} objects that are created by * {@link HttpRequestHandler}s through the {@link HTTPUploadSessionManager} * interface. Since HTTP 1.1 allows multiple requests for a single connection an * {@link HTTPUploadSession} is created for each connection. It keeps track of * queuing (which is per connection) and bandwidth and has a reference to the * {@link HTTPUploader} that represents the current request. * <p> * The state of <code>HTTPUploader</code> follows this pattern: * * <pre> * |-&gt;---- THEX_REQUEST -------&gt;--| * |-&gt;---- UNAVAILABLE_RANGE --&gt;--| * |-&gt;---- PUSH_PROXY ---------&gt;--| * /--&gt;---- FILE NOT FOUND -----&gt;--| * /---&gt;---- MALFORMED REQUEST --&gt;--| * /----&gt;---- BROWSE HOST --------&gt;--| * /-----&gt;---- UPDATE FILE --------&gt;--| * /------&gt;---- QUEUED -------------&gt;--| * /-------&gt;---- LIMIT REACHED ------&gt;--| * /--------&gt;---- UPLOADING ----------&gt;--| * --&gt;--CONNECTING--&gt;--/ | * | \|/ * | | * /|\ |---&gt;INTERRUPTED * |--------&lt;---COMPLETE-&lt;------&lt;-------&lt;-------&lt;------/ (done) * | * | * (done) * </pre> * * COMPLETE uploaders may be using HTTP/1.1, in which case the HTTPUploader * recycles back to CONNECTING upon receiving the next GET/HEAD request and * repeats. * <p> * INTERRUPTED HTTPUploaders are never reused. However, it is possible that the * socket may be reused. This case is only possible when a requester is queued * for one file and sends a subsequent request for another file. The first * <code>HTTPUploader</code> is set as interrupted and a second one is created * for the new file, using the same connection as the first one. * <p> * To initialize the upload manager {@link #start(HTTPAcceptor)} needs to be * invoked which registers handlers with an {@link HTTPAcceptor}. * * @see com.limegroup.gnutella.uploader.HTTPUploader * @see com.limegroup.gnutella.HTTPAcceptor */ @Singleton public class HTTPUploadManager implements FileLocker, BandwidthTracker, UploadManager, HTTPUploadSessionManager { /** The key used to store the {@link HTTPUploadSession} object. */ private final static String SESSION_KEY = "org.limewire.session"; private static final Log LOG = LogFactory.getLog(HTTPUploadManager.class); /** * This is a <code>List</code> of all of the current <code>Uploader</code> * instances (all of the uploads in progress that are not queued). */ private List<HTTPUploader> activeUploadList = new LinkedList<HTTPUploader>(); /** A manager for the available upload slots */ private final UploadSlotManager slotManager; /** Set to true when an upload has been successfully completed. */ private volatile boolean hadSuccesfulUpload = false; /** Number of force-shared active uploads. */ private int forcedUploads; private final HttpRequestHandler freeLoaderRequestHandler; private final ResponseListener responseListener = new ResponseListener(); /** * Number of active uploads that are not accounted in the slot manager but * whose bandwidth is counted. (i.e. Multicast) */ private final Set<HTTPUploader> localUploads = new CopyOnWriteArraySet<HTTPUploader>(); /** * LOCKING: obtain this' monitor before modifying any of the data structures */ /** * The number of uploads considered when calculating capacity, if possible. * BearShare uses 10. Settings it too low causes you to be fooled be a * streak of slow downloaders. Setting it too high causes you to be fooled * by a number of quick downloads before your slots become filled. */ private static final int MAX_SPEED_SAMPLE_SIZE = 5; /** * The min number of uploads considered to give out your speed. Same * criteria needed as for MAX_SPEED_SAMPLE_SIZE. */ private static final int MIN_SPEED_SAMPLE_SIZE = 5; /** The minimum number of bytes transferred by an uploadeder to count. */ private static final int MIN_SAMPLE_BYTES = 200000; // 200KB public static final int TRANSFER_SOCKET_TIMEOUT = 2 * 60 * 1000; /** The average speed in kiloBITs/second of the last few uploads. */ private Buffer<Integer> speeds = new Buffer<Integer>(MAX_SPEED_SAMPLE_SIZE); /** * The highestSpeed of the last few downloads, or -1 if not enough downloads * have been down for an accurate sample. INVARIANT: highestSpeed>=0 ==> * highestSpeed==max({i | i in speeds}) INVARIANT: speeds.size()<MIN_SPEED_SAMPLE_SIZE * <==> highestSpeed==-1 */ private volatile int highestSpeed = -1; /** * The number of measureBandwidth's we've had */ private int numMeasures = 0; /** * The current average bandwidth. * * This is only counted while uploads are active. */ private float averageBandwidth = 0f; /** The last value that getMeasuredBandwidth created. */ private volatile float lastMeasuredBandwidth; /** * Remembers uploaders to disadvantage uploaders that hammer us for download * slots. Stores up to 250 entries Maps IP String to RequestCache */ private final Map<String, RequestCache> REQUESTS = new FixedsizeForgetfulHashMap<String, RequestCache>( 250); private volatile Provider<ActivityCallback> activityCallback; private volatile Provider<FileManager> fileManager; private volatile boolean started; private final HttpRequestHandlerFactory httpRequestHandlerFactory; private final Provider<ContentManager> contentManager; private final Provider<HTTPAcceptor> httpAcceptor; private final TcpBandwidthStatistics tcpBandwidthStatistics; @Inject public HTTPUploadManager(UploadSlotManager slotManager, HttpRequestHandlerFactory httpRequestHandlerFactory, Provider<ContentManager> contentManager, Provider<HTTPAcceptor> httpAcceptor, Provider<FileManager> fileManager, Provider<ActivityCallback> activityCallback, TcpBandwidthStatistics tcpBandwidthStatistics) { this.slotManager = Objects.nonNull(slotManager, "slotManager"); this.httpRequestHandlerFactory = httpRequestHandlerFactory; this.contentManager = contentManager; this.freeLoaderRequestHandler = httpRequestHandlerFactory.createFreeLoaderRequestHandler(); this.httpAcceptor = Objects.nonNull(httpAcceptor, "httpAcceptor"); this.fileManager = Objects.nonNull(fileManager, "fileManager"); this.activityCallback = Objects.nonNull(activityCallback, "activityCallback"); this.tcpBandwidthStatistics = Objects.nonNull(tcpBandwidthStatistics, "tcpBandwidthStatistics"); } /** * Registers the upload manager at <code>acceptor</code>. * * @throws IllegalStateException if uploadmanager was already started * @see #stop(HTTPAcceptor) */ public void start() { if (started) { throw new IllegalStateException(); } FileUtils.addFileLocker(this); httpAcceptor.get().addAcceptorListener(responseListener); // browse httpAcceptor.get().registerHandler("/", httpRequestHandlerFactory.createBrowseRequestHandler()); // push-proxy requests HttpRequestHandler pushProxyHandler = httpRequestHandlerFactory.createPushProxyRequestHandler(); httpAcceptor.get().registerHandler("/gnutella/push-proxy", pushProxyHandler); httpAcceptor.get().registerHandler("/gnet/push-proxy", pushProxyHandler); // uploads FileRequestHandler fileRequestHandler = httpRequestHandlerFactory.createFileRequestHandler(); httpAcceptor.get().registerHandler("/get*", fileRequestHandler); httpAcceptor.get().registerHandler("/uri-res/*", fileRequestHandler); started = true; } /** * Unregisters the upload manager at <code>acceptor</code>. * * @see #start(HTTPAcceptor) */ public void stop() { if (!started) { throw new IllegalStateException(); } httpAcceptor.get().unregisterHandler("/"); httpAcceptor.get().unregisterHandler("/update.xml"); httpAcceptor.get().unregisterHandler("/gnutella/push-proxy"); httpAcceptor.get().unregisterHandler("/gnet/push-proxy"); httpAcceptor.get().unregisterHandler("/get*"); httpAcceptor.get().unregisterHandler("/uri-res/*"); httpAcceptor.get().removeAcceptorListener(responseListener); FileUtils.removeFileLocker(this); started = false; } public void handleFreeLoader(HttpRequest request, HttpResponse response, HttpContext context, HTTPUploader uploader) throws HttpException, IOException { assert started; uploader.setState(UploadStatus.FREELOADER); freeLoaderRequestHandler.handle(request, response, context); } /** * Determines whether or not this uploader should bypass queuing, (meaning * that it will always work immediately, and will not use up slots for other * uploaders). */ private boolean shouldBypassQueue(HttpRequest request, HTTPUploader uploader) { assert uploader.getState() == UploadStatus.CONNECTING; return "HEAD".equals(request.getRequestLine().getMethod()) || uploader.isForcedShare(); } /** * Cleans up a finished uploader. This does the following: * <ol> * <li>Reports the speed at which this upload occured. * <li>Removes the uploader from the active upload list * <li>Increments the completed uploads in the FileDesc * <li>Removes the uploader from the GUI * </ol> */ public void cleanupFinishedUploader(HTTPUploader uploader) { assert started; if (LOG.isTraceEnabled()) LOG.trace("Cleaning uploader " + uploader); UploadStatus state = uploader.getState(); UploadStatus lastState = uploader.getLastTransferState(); // assertAsFinished(state); long finishTime = System.currentTimeMillis(); synchronized (this) { // Report how quickly we uploaded the data. if (uploader.getStartTime() > 0) { reportUploadSpeed(finishTime - uploader.getStartTime(), uploader.getTotalAmountUploaded()); } removeFromList(uploader); localUploads.remove(uploader); } if (uploader.getUploadType() != null && !uploader.getUploadType().isInternal()) { FileDesc fd = uploader.getFileDesc(); if (fd != null && state == UploadStatus.COMPLETE && (lastState == UploadStatus.UPLOADING || lastState == UploadStatus.THEX_REQUEST)) { fd.incrementCompletedUploads(); activityCallback.get().handleSharedFileUpdate(fd.getFile()); } } activityCallback.get().removeUpload(uploader); } public synchronized void addAcceptedUploader(HTTPUploader uploader, HttpContext context) { assert started; if (uploader.isForcedShare()) forcedUploads++; else if (HttpContextParams.isLocal(context)) localUploads.add(uploader); activeUploadList.add(uploader); uploader.setStartTime(System.currentTimeMillis()); } public void sendResponse(HTTPUploader uploader, HttpResponse response) { assert started; uploader.setLastResponse(response); if (uploader.isVisible()) { return; } // We are going to notify the gui about the new upload, and let // it decide what to do with it - will act depending on it's // state activityCallback.get().addUpload(uploader); uploader.setVisible(true); if (!uploader.getUploadType().isInternal()) { FileDesc fd = uploader.getFileDesc(); if (fd != null) { fd.incrementAttemptedUploads(); activityCallback.get().handleSharedFileUpdate(fd.getFile()); } } } public synchronized boolean isServiceable() { if (!started) { return false; } return slotManager.hasHTTPSlot(uploadsInProgress() + getNumQueuedUploads()); } public synchronized boolean mayBeServiceable() { if (!started) { return false; } if (fileManager.get().hasApplicationSharedFiles()) return slotManager.hasHTTPSlotForMeta(uploadsInProgress() + getNumQueuedUploads()); return isServiceable(); } public synchronized int uploadsInProgress() { return activeUploadList.size() - forcedUploads; } public synchronized int getNumQueuedUploads() { return slotManager.getNumQueued(); } public boolean hadSuccesfulUpload() { return hadSuccesfulUpload; } public synchronized boolean isConnectedTo(InetAddress addr) { if (slotManager.getNumUsersForHost(addr.getHostAddress()) > 0) return true; for (HTTPUploader uploader : activeUploadList) { InetAddress host = uploader.getConnectedHost(); if (host != null && host.equals(addr)) return true; } return false; } public boolean releaseLock(File file) { assert started; FileDesc fd = fileManager.get().getFileDescForFile(file); if (fd != null) return killUploadsForFileDesc(fd); else return false; } public synchronized boolean killUploadsForFileDesc(FileDesc fd) { boolean ret = false; for (HTTPUploader uploader : activeUploadList) { FileDesc upFD = uploader.getFileDesc(); if (upFD != null && upFD.equals(fd)) { ret = true; uploader.stop(); } } return ret; } /** * Checks whether the given upload may proceed based on number of slots, * position in upload queue, etc. Updates the upload queue as necessary. * * @return ACCEPTED if the download may proceed, QUEUED if this is in the * upload queue, REJECTED if this is flat-out disallowed (and hence * not queued) and BANNED if the downloader is hammering us, and * BYPASS_QUEUE if this is a File-View request that isn't hammering * us. If REJECTED, <code>uploader</code>'s state will be set to * LIMIT_REACHED. If BANNED, the <code>Uploader</code>'s state * will be set to BANNED_GREEDY. */ private synchronized QueueStatus checkAndQueue(HTTPUploadSession session) { RequestCache rqc = REQUESTS.get(session.getHost()); if (rqc == null) rqc = new RequestCache(); // make sure we don't forget this RequestCache too soon! REQUESTS.put(session.getHost(), rqc); rqc.countRequest(); if (rqc.isHammering()) { if (LOG.isWarnEnabled()) LOG.warn(session.getUploader() + " banned."); return QueueStatus.BANNED; } FileDesc fd = session.getUploader().getFileDesc(); if (!contentManager.get().isVerified(fd.getSHA1Urn())) // spawn a validation fileManager.get().validate(fd); URN sha1 = fd.getSHA1Urn(); if (rqc.isDupe(sha1)) return QueueStatus.REJECTED; // check the host limit unless this is a poll if (slotManager.positionInQueue(session) == -1 && hostLimitReached(session.getHost())) { if (LOG.isDebugEnabled()) LOG.debug("host limit reached for " + session.getHost()); return QueueStatus.REJECTED; } int queued = slotManager.pollForSlot(session, session.getUploader() .supportsQueueing(), session.getUploader().isPriorityShare()); if (LOG.isDebugEnabled()) LOG.debug("queued at " + queued); if (queued == -1) // not accepted nor queued. return QueueStatus.REJECTED; if (queued > 0 && session.poll()) { slotManager.cancelRequest(session); // TODO we used to just drop the connection return QueueStatus.BANNED; } if (queued > 0) { return QueueStatus.QUEUED; } else { rqc.startedTransfer(sha1); return QueueStatus.ACCEPTED; } } /** * Decrements the number of active uploads for the host specified in the * <code>host</code> argument, removing that host from the * <code>Map</code> if this was the only upload allocated to that host. * <p> * This method also removes <code>uploader</code> from the * <code>List</code> of active uploads. */ private synchronized void removeFromList(HTTPUploader uploader) { // if the uploader is not in the active list, we should not // try remove the urn from the map of unique uploaded files for that // host. if (activeUploadList.remove(uploader)) { if (uploader.isForcedShare()) forcedUploads--; // at this point it is safe to allow other uploads from the same // host RequestCache rcq = REQUESTS.get(uploader.getHost()); // check for nulls so that unit tests pass if (rcq != null && uploader.getFileDesc() != null) rcq.transferDone(uploader.getFileDesc().getSHA1Urn()); } // Enable auto shutdown if (activeUploadList.size() == 0) activityCallback.get().uploadsComplete(); } /** * @return false if the number of uploads from the host is strictly LESS * than the MAX, although we want to allow exactly MAX uploads from * the same host. This is because this method is called BEFORE we * add/allow the. upload. */ private synchronized boolean hostLimitReached(String host) { return slotManager.getNumUsersForHost(host) >= UploadSettings.UPLOADS_PER_PERSON .getValue(); } // //////////////// Bandwidth Allocation and Measurement/////////////// /** * Calculates the appropriate burst size for the allocating bandwidth on the * upload. * * @return burstSize. if it is the special case, in which we want to upload * as quickly as possible. */ public int calculateBandwidth() { // public int calculateBurstSize() { float totalBandwith = getTotalBandwith(); float burstSize = totalBandwith / uploadsInProgress(); return (int) burstSize; } /** * @return the total bandwith available for uploads */ private float getTotalBandwith() { // To calculate the total bandwith available for // uploads, there are two properties. The first // is what the user *thinks* their connection // speed is. Note, that they may have set this // wrong, but we have no way to tell. float connectionSpeed = ConnectionSettings.CONNECTION_SPEED.getValue() / 8.0f; // the second number is the speed that they have // allocated to uploads. This is really a percentage // that the user is willing to allocate. float speed = UploadSettings.UPLOAD_SPEED.getValue(); // the total bandwith available then, is the percentage // allocated of the total bandwith. float totalBandwith = connectionSpeed * speed / 100.0f; return totalBandwith; } public int measuredUploadSpeed() { // Note that no lock is needed. return highestSpeed; } /** * Notes that some uploader has uploaded the given number of BYTES in the * given number of milliseconds. If bytes is too small, the data may be * ignored. * * @requires this' lock held * @modifies this.speed, this.speeds */ private void reportUploadSpeed(long milliseconds, long bytes) { // This is critical for ignoring 404's messages, etc. if (bytes < MIN_SAMPLE_BYTES) return; // Calculate the bandwidth in kiloBITS/s. We just assume that 1 kilobyte // is 1000 (not 1024) bytes for simplicity. int bandwidth = 8 * (int) ((float) bytes / (float) milliseconds); synchronized (speeds) { speeds.add(bandwidth); // Update maximum speed if possible if (speeds.size() >= MIN_SPEED_SAMPLE_SIZE) { int max = 0; for (int i = 0; i < speeds.size(); i++) max = Math.max(max, speeds.get(i)); this.highestSpeed = max; } } } public void measureBandwidth() { slotManager.measureBandwidth(); for (HTTPUploader active : localUploads) { active.measureBandwidth(); } } public float getMeasuredBandwidth() { float bw = 0; try { bw += slotManager.getMeasuredBandwidth(); } catch (InsufficientDataException notEnough) { } for (HTTPUploader forced : localUploads) { try { bw += forced.getMeasuredBandwidth(); } catch (InsufficientDataException e) { } } synchronized (this) { averageBandwidth = ((averageBandwidth * numMeasures) + bw) / ++numMeasures; } lastMeasuredBandwidth = bw; return bw; } public synchronized float getAverageBandwidth() { return averageBandwidth; } public float getLastMeasuredBandwidth() { return lastMeasuredBandwidth; } public UploadSlotManager getSlotManager() { return slotManager; } public HTTPUploadSession getOrCreateSession(HttpContext context) { assert started; HTTPUploadSession session = (HTTPUploadSession) context .getAttribute(SESSION_KEY); if (session == null) { HttpInetConnection conn = (HttpInetConnection) context .getAttribute(ExecutionContext.HTTP_CONNECTION); InetAddress host; if (conn != null) { host = conn.getRemoteAddress(); } else { // XXX this is a bad work around to make request processing // testable without having an underlying connection try { host = InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } session = new HTTPUploadSession(getSlotManager(), host, HttpContextParams.getIOSession(context)); context.setAttribute(SESSION_KEY, session); } return session; } /** * Returns the session stored in <code>context</code>. * * @return null, if no session exists */ public HTTPUploadSession getSession(HttpContext context) { assert started; HTTPUploadSession session = (HTTPUploadSession) context .getAttribute(SESSION_KEY); return session; } public HTTPUploader getOrCreateUploader(HttpRequest request, HttpContext context, UploadType type, String filename) { assert started; HTTPUploadSession session = getOrCreateSession(context); HTTPUploader uploader = session.getUploader(); if (uploader != null) { if (!uploader.getFileName().equals(filename) || !uploader.getMethod().equals( request.getRequestLine().getMethod())) { // start new file slotManager.requestDone(session); // Because queuing is per-socket (and not per file), // we do not want to reset the queue status if they're // requesting a new file. if (session.isQueued()) { // However, we DO want to make sure that the old file // is interpreted as interrupted. Otherwise, // the GUI would show two lines with the the same slot // until the newer line finished, at which point // the first one would display as a -1 queue position. uploader.setState(UploadStatus.INTERRUPTED); } else { slotManager.requestDone(session); } cleanupFinishedUploader(uploader); uploader = new HTTPUploader(filename, session, tcpBandwidthStatistics); } else { // reuse existing uploader object uploader.reinitialize(); } } else { // first request for this session uploader = new HTTPUploader(filename, session); } String method = request.getRequestLine().getMethod(); uploader.setMethod(method); uploader.setUploadType("HEAD".equals(method) ? UploadType.HEAD_REQUEST : type); session.setUploader(uploader); return uploader; } public HTTPUploader getUploader(HttpContext context) { assert started; HTTPUploadSession session = getSession(context); HTTPUploader uploader = session.getUploader(); assert uploader != null; return uploader; } public QueueStatus enqueue(HttpContext context, HttpRequest request) { assert started; HTTPUploadSession session = getSession(context); assert !session.isAccepted(); if (shouldBypassQueue(request, session.getUploader())) { session.setQueueStatus(QueueStatus.BYPASS); } else if (HttpContextParams.isLocal(context)) { session.setQueueStatus(QueueStatus.ACCEPTED); } else { session.setQueueStatus(checkAndQueue(session)); } if (LOG.isDebugEnabled()) LOG.debug("Queued upload: " + session); return session.getQueueStatus(); } /** For testing: removes all uploaders and clears the request cache. */ public void cleanup() { assert started; for (HTTPUploader uploader : activeUploadList .toArray(new HTTPUploader[0])) { uploader.stop(); slotManager.cancelRequest(uploader.getSession()); removeFromList(uploader); } slotManager.cleanup(); REQUESTS.clear(); } /** * Manages the {@link HTTPUploadSession} associated with a connection. */ private class ResponseListener implements HttpAcceptorListener { public void connectionOpen(NHttpConnection conn) { } public void connectionClosed(NHttpConnection conn) { assert started; HTTPUploadSession session = getSession(conn.getContext()); if (session != null) { HTTPUploader uploader = session.getUploader(); if (uploader != null) { if (LOG.isDebugEnabled()) LOG.debug("Closing session for " + session.getHost()); boolean stillInQueue = slotManager.positionInQueue(session) > -1; slotManager.cancelRequest(session); if (stillInQueue) { // If it was queued, also set the state to INTERRUPTED // (changing from COMPLETE) uploader.setState(UploadStatus.INTERRUPTED); } else if (uploader.getState() != UploadStatus.COMPLETE) { // the complete state may have been set by // responseSent() already uploader.setState(UploadStatus.COMPLETE); } uploader.setLastResponse(null); cleanupFinishedUploader(uploader); session.setUploader(null); } } } public void requestReceived(NHttpConnection conn, HttpRequest request) { } public void responseSent(NHttpConnection conn, HttpResponse response) { assert started; HTTPUploadSession session = getSession(conn.getContext()); if (session != null) { HTTPUploader uploader = session.getUploader(); if (uploader != null && uploader.getLastResponse() == response) { uploader.setLastResponse(null); uploader.setState(UploadStatus.COMPLETE); } if (session.getQueueStatus() == QueueStatus.QUEUED) { session.getIOSession().setSocketTimeout( HTTPUploadSession.MAX_POLL_TIME); } } } } }

The table below shows all metrics for HTTPUploadManager.java.

MetricValueDescription
BLOCKS89.00Number of blocks
BLOCK_COMMENT 0.00Number of block comment lines
COMMENTS223.00Comment lines
COMMENT_DENSITY 0.55Comment density
COMPARISONS76.00Number of comparison operators
CYCLOMATIC106.00Cyclomatic complexity
DECL_COMMENTS31.00Comments in declarations
DOC_COMMENT171.00Number of javadoc comment lines
ELOC406.00Effective lines of code
EXEC_COMMENTS29.00Comments in executable code
EXITS134.00Procedure exits
FUNCTIONS38.00Number of function declarations
HALSTEAD_DIFFICULTY79.30Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY100.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 0.00JAVA0007 Should not declare public field
JAVA0008 2.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 0.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
JAVA0020 0.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 0.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
JAVA003421.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 0.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 0.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 1.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 0.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 9.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 1.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 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 1.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 4.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 0.00JAVA0128 Public constructor in non-public class
JAVA0130 2.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
JAVA014311.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.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 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.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 1.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 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.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
LINES840.00Number of lines in the source file
LINE_COMMENT52.00Number of line comments
LOC486.00Lines of code
LOGICAL_LINES264.00Number of statements
LOOPS 1.00Number of loops
NEST_DEPTH 4.00Maximum nesting depth
OPERANDS1163.00Number of operands
OPERATORS2212.00Number of operators
PARAMS41.00Number of formal parameter declarations
PROGRAM_LENGTH3375.00Halstead program length
PROGRAM_VOCAB475.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS59.00Number of return points from functions
SIZE31643.00Size of the file in bytes
UNIQUE_OPERANDS418.00Number of unique operands
UNIQUE_OPERATORS57.00Number of unique operators
WHITESPACE131.00Number of whitespace lines