RDResumeHandler.java

Index Score
org.gudy.azureus2.core3.disk.impl.resume
Azureus

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
LOOPSNumber of loops
JAVA0145JAVA0145 Tab character used in source file
EXEC_COMMENTSComments in executable code
LINE_COMMENTNumber of line comments
WHITESPACENumber of whitespace lines
JAVA0049JAVA0049 Nested block at depth N (maximum: M)
JAVA0034JAVA0034 Missing braces in if statement
CYCLOMATICCyclomatic complexity
LINESNumber of lines in the source file
COMPARISONSNumber of comparison operators
BLOCKSNumber of blocks
LOGICAL_LINESNumber of statements
ELOCEffective lines of code
LOCLines of code
OPERATORSNumber of operators
SIZESize of the file in bytes
PROGRAM_LENGTHHalstead program length
JAVA0117JAVA0117 Missing javadoc: method 'method'
OPERANDSNumber of operands
JAVA0119JAVA0119 Control variable changed within body of for loop
UNIQUE_OPERANDSNumber of unique operands
PROGRAM_VOCABHalstead program vocabulary
EXITSProcedure exits
JAVA0166JAVA0166 Generic exception caught
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
NEST_DEPTHMaximum nesting depth
JAVA0170JAVA0170 Caught exception not derived from java.lang.Exception
PARAMSNumber of formal parameter declarations
INTERFACE_COMPLEXITYInterface complexity
UNIQUE_OPERATORSNumber of unique operators
JAVA0254JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0036JAVA0036 Missing braces in while statement
JAVA0144JAVA0144 Line exceeds maximum M characters
FUNCTIONSNumber of function declarations
JAVA0076JAVA0076 Use of magic number
PROGRAM_VOLUMEHalstead program volume
JAVA0035JAVA0035 Missing braces in for statement
RETURNSNumber of return points from functions
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0061JAVA0061 Inaccessible member in anonymous class
JAVA0100JAVA0100 Class contains N non-final fields (maximum: M)
DOC_COMMENTNumber of javadoc comment lines
DECL_COMMENTSComments in declarations
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
/* * Created on 31-Jul-2004 * Created by Paul Gardner * Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * AELITIS, SAS au capital de 46,603.30 euros * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France. * */ package org.gudy.azureus2.core3.disk.impl.resume; import java.util.*; import org.gudy.azureus2.core3.config.COConfigurationManager; import org.gudy.azureus2.core3.config.ParameterListener; import org.gudy.azureus2.core3.disk.DiskManagerCheckRequest; import org.gudy.azureus2.core3.disk.DiskManagerCheckRequestListener; import org.gudy.azureus2.core3.disk.DiskManagerFileInfo; import org.gudy.azureus2.core3.disk.DiskManagerPiece; import org.gudy.azureus2.core3.disk.impl.DiskManagerFileInfoImpl; import org.gudy.azureus2.core3.disk.impl.DiskManagerImpl; import org.gudy.azureus2.core3.disk.impl.DiskManagerRecheckInstance; import org.gudy.azureus2.core3.disk.impl.access.DMChecker; import org.gudy.azureus2.core3.disk.impl.piecemapper.DMPieceList; import org.gudy.azureus2.core3.disk.impl.piecemapper.DMPieceMapEntry; import org.gudy.azureus2.core3.download.DownloadManager; import org.gudy.azureus2.core3.download.DownloadManagerState; import org.gudy.azureus2.core3.logging.LogEvent; import org.gudy.azureus2.core3.logging.LogIDs; import org.gudy.azureus2.core3.logging.Logger; import org.gudy.azureus2.core3.torrent.TOTorrent; import org.gudy.azureus2.core3.util.AESemaphore; import org.gudy.azureus2.core3.util.Debug; import com.aelitis.azureus.core.diskmanager.cache.CacheFileManagerException; /** * @author parg * */ public class RDResumeHandler { private static final LogIDs LOGID = LogIDs.DISK; private static final byte PIECE_NOT_DONE = 0; private static final byte PIECE_DONE = 1; private static final byte PIECE_RECHECK_REQUIRED = 2; private static final byte PIECE_STARTED = 3; private static boolean use_fast_resume; private static boolean use_fast_resume_recheck_all; static{ COConfigurationManager.addAndFireParameterListeners( new String[]{ "Use Resume", "On Resume Recheck All" }, new ParameterListener() { public void parameterChanged( String str ) { use_fast_resume = COConfigurationManager.getBooleanParameter("Use Resume"); use_fast_resume_recheck_all = COConfigurationManager.getBooleanParameter("On Resume Recheck All"); } }); } private DiskManagerImpl disk_manager; private DMChecker checker; private volatile boolean started; private volatile boolean stopped; private volatile boolean stopped_for_close; private volatile boolean check_in_progress; private volatile boolean check_resume_was_valid; private volatile boolean check_is_full_check; private volatile boolean check_interrupted; private volatile int check_position; public RDResumeHandler( DiskManagerImpl _disk_manager, DMChecker _writer_and_checker ) { disk_manager = _disk_manager; checker = _writer_and_checker; } public void start() { if ( started ){ Debug.out( "RDResumeHandler: reuse not supported" ); } started = true; } public void stop( boolean closing ) { stopped_for_close = stopped_for_close | closing; // can get in here > once during close if ( check_in_progress ){ check_interrupted = true; } stopped = true; } public void checkAllPieces( boolean newfiles ) { //long start = System.currentTimeMillis(); DiskManagerRecheckInstance recheck_inst = disk_manager.getRecheckScheduler().register( disk_manager, false ); final AESemaphore run_sem = new AESemaphore( "RDResumeHandler::checkAllPieces:runsem", 2 ); try{ boolean resume_data_complete = false; try{ check_in_progress = true; boolean resumeEnabled = use_fast_resume; //disable fast resume if a new file was created if ( newfiles ){ resumeEnabled = false; } final AESemaphore pending_checks_sem = new AESemaphore( "RD:PendingChecks" ); int pending_check_num = 0; DiskManagerPiece[] pieces = disk_manager.getPieces(); // calculate the current file sizes up front for performance reasons DiskManagerFileInfo[] files = disk_manager.getFiles(); Map file_sizes = new HashMap(); for (int i=0;i<files.length;i++){ try{ Long len = new Long(((DiskManagerFileInfoImpl)files[i]).getCacheFile().getLength()); file_sizes.put( files[i], len ); }catch( CacheFileManagerException e ){ Debug.printStackTrace(e); } } if ( resumeEnabled ){ boolean resumeValid = false; byte[] resume_pieces = null; Map partialPieces = null; Map resume_data = getResumeData(); if ( resume_data != null ){ try { resume_pieces = (byte[])resume_data.get("resume data"); if ( resume_pieces != null ){ if ( resume_pieces.length != pieces.length ){ Debug.out( "Resume data array length mismatch: " + resume_pieces.length + "/" + pieces.length ); resume_pieces = null; } } partialPieces = (Map)resume_data.get("blocks"); resumeValid = ((Long)resume_data.get("valid")).intValue() == 1; // if the torrent download is complete we don't need to invalidate the // resume data if ( isTorrentResumeDataComplete( disk_manager.getDownloadManager().getDownloadState(), resume_data )){ resume_data_complete = true; }else{ // set it so that if we crash the NOT_DONE pieces will be // rechecked resume_data.put("valid", new Long(0)); saveResumeData( resume_data ); } }catch(Exception ignore){ // ignore.printStackTrace(); } } if ( resume_pieces == null ){ check_is_full_check = true; resumeValid = false; resume_pieces = new byte[pieces.length]; Arrays.fill( resume_pieces, PIECE_RECHECK_REQUIRED ); } check_resume_was_valid = resumeValid; boolean recheck_all = use_fast_resume_recheck_all; if ( !recheck_all ){ // override if not much left undone long total_not_done = 0; int piece_size = disk_manager.getPieceLength(); for (int i = 0; i < pieces.length; i++){ if ( resume_pieces[i] != PIECE_DONE ){ total_not_done += piece_size; } } if ( total_not_done < 64*1024*1024 ){ recheck_all = true; } } if (Logger.isEnabled()){ int total_not_done = 0; int total_done = 0; int total_started = 0; int total_recheck = 0; for (int i = 0; i < pieces.length; i++){ byte piece_state = resume_pieces[i]; if ( piece_state == PIECE_NOT_DONE ){ total_not_done++; }else if ( piece_state == PIECE_DONE ){ total_done++; }else if ( piece_state == PIECE_STARTED ){ total_started++; }else{ total_recheck++; } } String str = "valid=" + resumeValid + ",not done=" + total_not_done + ",done=" + total_done + ",started=" + total_started + ",recheck=" + total_recheck + ",rc all=" + recheck_all + ",full=" + check_is_full_check; Logger.log(new LogEvent(disk_manager, LOGID, str )); } for (int i = 0; i < pieces.length; i++){ check_position = i; DiskManagerPiece dm_piece = pieces[i]; disk_manager.setPercentDone(((i + 1) * 1000) / disk_manager.getNbPieces() ); boolean pieceCannotExist = false; byte piece_state = resume_pieces[i]; // valid resume data means that the resume array correctly represents // the state of pieces on disk, be they done or not if ( piece_state == PIECE_DONE || !resumeValid || recheck_all ){ // at least check that file sizes are OK for this piece to be valid DMPieceList list = disk_manager.getPieceList(i); for (int j=0;j<list.size();j++){ DMPieceMapEntry entry = list.get(j); Long file_size = (Long)file_sizes.get(entry.getFile()); if ( file_size == null ){ piece_state = PIECE_NOT_DONE; pieceCannotExist = true; if (Logger.isEnabled()) Logger.log(new LogEvent(disk_manager, LOGID, LogEvent.LT_WARNING, "Piece #" + i + ": file is missing, " + "fails re-check.")); break; } long expected_size = entry.getOffset() + entry.getLength(); if ( file_size.longValue() < expected_size ){ piece_state = PIECE_NOT_DONE; pieceCannotExist = true; if (Logger.isEnabled()) Logger.log(new LogEvent(disk_manager, LOGID, LogEvent.LT_WARNING, "Piece #" + i + ": file is too small, fails re-check. File size = " + file_size + ", piece needs " + expected_size)); break; } } } if ( piece_state == PIECE_DONE ){ dm_piece.setDone( true ); }else if ( piece_state == PIECE_NOT_DONE && !recheck_all ){ // if the piece isn't done and we haven't been asked to recheck all pieces // on restart (only started pieces) then just set as not done }else{ // We only need to recheck pieces that are marked as not-ok // if the resume data is invalid or explicit recheck needed if(pieceCannotExist) { dm_piece.setDone( false ); } else if ( piece_state == PIECE_RECHECK_REQUIRED || !resumeValid ){ run_sem.reserve(); while( !stopped ){ if ( recheck_inst.getPermission()){ break; } } if ( stopped ){ break; }else{ try{ DiskManagerCheckRequest request = disk_manager.createCheckRequest( i, null ); request.setLowPriority( true ); checker.enqueueCheckRequest( request, new DiskManagerCheckRequestListener() { public void checkCompleted( DiskManagerCheckRequest request, boolean passed ) { complete(); } public void checkCancelled( DiskManagerCheckRequest request ) { complete(); } public void checkFailed( DiskManagerCheckRequest request, Throwable cause ) { complete(); } protected void complete() { run_sem.release(); pending_checks_sem.release(); } }); pending_check_num++; }catch( Throwable e ){ Debug.printStackTrace(e); } } } } } while( pending_check_num > 0 ){ pending_checks_sem.reserve(); pending_check_num--; } if ( partialPieces != null ){ Iterator iter = partialPieces.entrySet().iterator(); while (iter.hasNext()) { Map.Entry key = (Map.Entry)iter.next(); int pieceNumber = Integer.parseInt((String)key.getKey()); DiskManagerPiece dm_piece = pieces[ pieceNumber ]; if ( !dm_piece.isDone()){ List blocks = (List)partialPieces.get(key.getKey()); Iterator iterBlock = blocks.iterator(); while (iterBlock.hasNext()) { dm_piece.setWritten(((Long)iterBlock.next()).intValue()); } } } } }else{ // resume not enabled, recheck everything for (int i = 0; i < pieces.length; i++){ check_position = i; disk_manager.setPercentDone(((i + 1) * 1000) / disk_manager.getNbPieces() ); boolean pieceCannotExist = false; // check if there is an underlying file for this piece, if not set it to not done DMPieceList list = disk_manager.getPieceList(i); for (int j=0;j<list.size();j++){ DMPieceMapEntry entry = list.get(j); Long file_size = (Long)file_sizes.get(entry.getFile()); if ( file_size == null ){ pieceCannotExist = true; break; } long expected_size = entry.getOffset() + entry.getLength(); if ( file_size.longValue() < expected_size ){ pieceCannotExist = true; break; } } if(pieceCannotExist) { disk_manager.getPiece(i).setDone(false); continue; } run_sem.reserve(); while( ! stopped ){ if ( recheck_inst.getPermission()){ break; } } if ( stopped ){ break; } try{ DiskManagerCheckRequest request = disk_manager.createCheckRequest( i, null ); request.setLowPriority( true ); checker.enqueueCheckRequest( request, new DiskManagerCheckRequestListener() { public void checkCompleted( DiskManagerCheckRequest request, boolean passed ) { complete(); } public void checkCancelled( DiskManagerCheckRequest request ) { complete(); } public void checkFailed( DiskManagerCheckRequest request, Throwable cause ) { complete(); } protected void complete() { run_sem.release(); pending_checks_sem.release(); } }); pending_check_num++; }catch( Throwable e ){ Debug.printStackTrace(e); } } while( pending_check_num > 0 ){ pending_checks_sem.reserve(); pending_check_num--; } } }finally{ check_in_progress = false; } //dump the newly built resume data to the disk/torrent if ( !( stopped || resume_data_complete )){ try{ saveResumeData( true ); }catch( Exception e ){ Debug.out( "Failed to dump initial resume data to disk" ); Debug.printStackTrace( e ); } } }catch( Throwable e ){ // if something went wrong then log and continue. Debug.printStackTrace(e); }finally{ recheck_inst.unregister(); // System.out.println( "Check of '" + disk_manager.getDownloadManager().getDisplayName() + "' completed in " + (System.currentTimeMillis() - start)); } } public void saveResumeData( boolean interim_save ) // data is marked as "invalid" if this is true to enable checking on pieces on crash restart throws Exception { if ( check_in_progress && interim_save ){ // while we are rechecking it is important that an interim save doesn't come // along and overwite the persisted resume data. This is because should we crash // while rechecking we need the persisted state to be unchanged so that on // restart the rechecking occurs again // a non-interim save means that the user has decided to stop the download (or some // other such significant event) so we just persist the current state return; } // if file caching is enabled then this is an important time to ensure that the cache is // flushed as we are going to record details about the accuracy of written data. // First build the resume map from the data (as updates can still be goin on) // Then, flush the cache. This means that on a successful flush the built resume // data matches at least the valid state of the data // Then update the torrent DiskManagerFileInfo[] files = disk_manager.getFiles(); if ( !use_fast_resume ){ // flush cache even if resume disable as this is a good point to ensure that data // is persisted anyway for (int i=0;i<files.length;i++){ files[i].flushCache(); } return; } boolean was_complete = isTorrentResumeDataComplete( disk_manager.getDownloadManager().getDownloadState()); DiskManagerPiece[] pieces = disk_manager.getPieces(); //build the piece byte[] byte[] resume_pieces = new byte[pieces.length]; for (int i = 0; i < resume_pieces.length; i++) { DiskManagerPiece piece = pieces[i]; // if we are terminating due to az closure and this has interrupted a recheck then // make sure that the recheck continues appropriately on restart if ( stopped_for_close && check_interrupted && check_is_full_check && i >= check_position ){ resume_pieces[i] = PIECE_RECHECK_REQUIRED; }else if ( piece.isDone()){ resume_pieces[i] = PIECE_DONE; }else if ( piece.getNbWritten() > 0 ){ resume_pieces[i] = PIECE_STARTED; }else{ resume_pieces[i] = PIECE_NOT_DONE; } } Map resume_data = new HashMap(); resume_data.put( "resume data", resume_pieces ); Map partialPieces = new HashMap(); for (int i = 0; i < pieces.length; i++) { DiskManagerPiece piece = pieces[i]; // save the partial pieces for any pieces that have not yet been completed // and are in-progress (i.e. have at least one block downloaded) boolean[] written = piece.getWritten(); if (( !piece.isDone()) && piece.getNbWritten() > 0 && written != null ){ boolean all_written = true; for (int j = 0; j < written.length; j++) { if ( !written[j] ){ all_written = false; break; } } if ( all_written ){ // just mark the entire piece for recheck as we've stopped the torrent at the // point where a check-piece was, or was about to be, scheduled resume_pieces[ i ] = PIECE_RECHECK_REQUIRED; }else{ List blocks = new ArrayList(); for (int j = 0; j < written.length; j++) { if (written[j]){ blocks.add(new Long(j)); } } partialPieces.put("" + i, blocks); } } } resume_data.put("blocks", partialPieces); long lValid; if ( check_interrupted ){ // set validity to what it was before the check started lValid = check_resume_was_valid?1:0; }else if ( interim_save ){ // set invalid so that not-done pieces get rechecked on startup lValid = 0; }else{ lValid = 1; } resume_data.put("valid", new Long(lValid)); for (int i=0;i<files.length;i++){ files[i].flushCache(); } // OK, we've got valid resume data and flushed the cache boolean is_complete = isTorrentResumeDataComplete( disk_manager.getDownloadManager().getDownloadState(), resume_data ); if ( was_complete && is_complete ){ // no change, no point in writing }else{ saveResumeData( resume_data ); } } protected Map getResumeData() { return( getResumeData( disk_manager.getDownloadManager())); } protected static Map getResumeData( DownloadManager download_manager) { return( getResumeData( download_manager.getDownloadState())); } protected static Map getResumeData( DownloadManagerState download_manager_state ) { Map resume_map = download_manager_state.getResumeData(); if ( resume_map != null ){ Map resume_data = (Map)resume_map.get( "data" ); return( resume_data ); }else{ return( null ); } } protected void saveResumeData( Map resume_data ) { saveResumeData( disk_manager.getDownloadManager().getDownloadState(), resume_data ); } protected static void saveResumeData( DownloadManagerState download_manager_state, Map resume_data ) { Map resume_map = new HashMap(); resume_map.put( "data", resume_data ); download_manager_state.setResumeData( resume_map ); } public static void setTorrentResumeDataComplete( DownloadManagerState download_manager_state ) { TOTorrent torrent = download_manager_state.getTorrent(); int piece_count = torrent.getNumberOfPieces(); byte[] resume_pieces = new byte[piece_count]; Arrays.fill( resume_pieces, PIECE_DONE ); Map resume_data = new HashMap(); resume_data.put( "resume data", resume_pieces ); Map partialPieces = new HashMap(); resume_data.put("blocks", partialPieces ); resume_data.put("valid", new Long(1)); saveResumeData( download_manager_state, resume_data ); } protected static int clearResumeDataSupport( DownloadManager download_manager, DiskManagerFileInfo file, boolean recheck, boolean onlyClearUnsharedFirstLast ) { DownloadManagerState download_manager_state = download_manager.getDownloadState(); Map resume_data = getResumeData( download_manager ); if ( resume_data == null ){ return(0); } int pieces_cleared = 0; // clear any affected pieces byte[] resume_pieces = (byte[])resume_data.get("resume data"); int firstPiece = file.getFirstPieceNumber(); int lastPiece = file.getLastPieceNumber(); if ( onlyClearUnsharedFirstLast ){ DiskManagerFileInfo[] files = download_manager.getDiskManagerFileInfo(); boolean firstPieceShared = false; boolean lastPieceShared = false; int firstFile = findFirstFileWithPieceN(firstPiece, files); for(int i = firstFile;i<files.length;i++) { DiskManagerFileInfo currentFile = files[i]; if(currentFile.getLastPieceNumber() < firstPiece) continue; if(currentFile.getIndex() == file.getIndex()) continue; if(currentFile.getFirstPieceNumber() > lastPiece) break; if(currentFile.getFirstPieceNumber() <= firstPiece && firstPiece <= currentFile.getLastPieceNumber()) firstPieceShared |= !currentFile.isSkipped(); if(currentFile.getFirstPieceNumber() <= lastPiece && lastPiece <= currentFile.getLastPieceNumber()) lastPieceShared |= !currentFile.isSkipped(); } if(firstPieceShared) firstPiece++; if(lastPieceShared) lastPiece--; } if ( resume_pieces != null ){ for (int i=firstPiece;i<=lastPiece;i++){ if ( i >= resume_pieces.length ){ break; } if ( resume_pieces[i] == PIECE_DONE ){ pieces_cleared++; } resume_pieces[i] = recheck?PIECE_RECHECK_REQUIRED:PIECE_NOT_DONE; } } // clear any affected partial pieces Map partial_pieces = (Map)resume_data.get("blocks"); if ( partial_pieces != null ){ Iterator iter = partial_pieces.keySet().iterator(); while (iter.hasNext()) { int piece_number = Integer.parseInt((String)iter.next()); if ( piece_number >= firstPiece && piece_number <= lastPiece ){ iter.remove(); } } } // either way we're valid as // 1) clear -> pieces are set as not done // 2) recheck -> pieces are set as "recheck" and will be checked on restart resume_data.put( "valid", new Long(1)); saveResumeData( download_manager_state, resume_data ); return( pieces_cleared ); } /** * finds the first affected file via binary search, this is necessary as some methods might be * invoked for all files, which would result in O(n²) if we'd scan the whole file array every * time */ private static int findFirstFileWithPieceN(int firstPiece, DiskManagerFileInfo[] files) { int start = 0; int end = files.length-1; int pivot = 0; while (start <= end) { pivot = (start + end) >>> 1; int midVal = files[pivot].getLastPieceNumber(); if (midVal < firstPiece) start = pivot + 1; else if (midVal > firstPiece) end = pivot - 1; else { // some matching file, now slide leftwards to find the first one, shouldn't be that many while(pivot > 0 && files[pivot-1].getLastPieceNumber() == firstPiece) pivot--; break; } } return pivot; } public static boolean fileMustExist(DownloadManager download_manager, DiskManagerFileInfo file) { Map resumeData = getResumeData( download_manager ); byte[] resumePieces = resumeData != null ? (byte[])resumeData.get("resume data") : null; boolean sharesAnyNeededPieces = false; DiskManagerFileInfo[] files = download_manager.getDiskManagerFileInfo(); int firstPiece = file.getFirstPieceNumber(); int lastPiece = file.getLastPieceNumber(); int firstFile = findFirstFileWithPieceN(firstPiece, files); // we must sweep over the files, as any number of files could share the first/last piece of the file we're probing for (int i = firstFile; i < files.length && !sharesAnyNeededPieces; i++) { DiskManagerFileInfo currentFile = files[i]; if(currentFile.getLastPieceNumber() < firstPiece) continue; if (currentFile.getIndex() == file.getIndex() && resumePieces != null && file.getStorageType() != DiskManagerFileInfo.ST_COMPACT) for (int j = firstPiece; j <= lastPiece && !sharesAnyNeededPieces; j++) sharesAnyNeededPieces |= resumePieces[j] != PIECE_NOT_DONE; if (currentFile.getFirstPieceNumber() > lastPiece) break; if (currentFile.getFirstPieceNumber() <= firstPiece && firstPiece <= currentFile.getLastPieceNumber()) sharesAnyNeededPieces |= !currentFile.isSkipped(); if (currentFile.getFirstPieceNumber() <= lastPiece && lastPiece <= currentFile.getLastPieceNumber()) sharesAnyNeededPieces |= !currentFile.isSkipped(); } return sharesAnyNeededPieces; } public static int storageTypeChanged( DownloadManager download_manager, DiskManagerFileInfo file ) { return( clearResumeDataSupport( download_manager, file, false, true )); } public static void clearResumeData( DownloadManager download_manager, DiskManagerFileInfo file ) { clearResumeDataSupport( download_manager, file, false, false ); } public static void recheckFile( DownloadManager download_manager, DiskManagerFileInfo file ) { clearResumeDataSupport( download_manager, file, true, false ); } public static void setTorrentResumeDataNearlyComplete( DownloadManagerState download_manager_state ) { // backwards compatability, resume data key is the dir TOTorrent torrent = download_manager_state.getTorrent(); long piece_count = torrent.getNumberOfPieces(); byte[] resume_pieces = new byte[(int)piece_count]; Arrays.fill( resume_pieces, PIECE_DONE ); // randomly clear some pieces for (int i=0;i<3;i++){ int piece_num = (int)(Math.random()*piece_count); resume_pieces[piece_num]= PIECE_RECHECK_REQUIRED; } Map resumeMap = new HashMap(); resumeMap.put( "resume data", resume_pieces); Map partialPieces = new HashMap(); resumeMap.put("blocks", partialPieces); resumeMap.put("valid", new Long(0)); // recheck the not-done pieces saveResumeData(download_manager_state,resumeMap); } public static boolean isTorrentResumeDataComplete( DownloadManagerState dms ) { // backwards compatability, resume data key is the dir Map resume_data = getResumeData( dms ); return( isTorrentResumeDataComplete( dms, resume_data )); } protected static boolean isTorrentResumeDataComplete( DownloadManagerState download_manager_state, Map resume_data ) { try{ int piece_count = download_manager_state.getTorrent().getNumberOfPieces(); if ( resume_data != null ){ byte[] pieces = (byte[])resume_data.get("resume data"); Map blocks = (Map)resume_data.get("blocks"); boolean valid = ((Long)resume_data.get("valid")).intValue() == 1; // any partial pieced -> not complete if ( blocks == null || blocks.size() > 0 ){ return( false ); } if ( valid && pieces != null && pieces.length == piece_count ){ for (int i=0;i<pieces.length;i++){ if ( pieces[i] != PIECE_DONE ){ // missing piece or recheck outstanding return( false ); } } return( true ); } } }catch( Throwable e ){ Debug.printStackTrace( e ); } return( false ); } }

The table below shows all metrics for RDResumeHandler.java.

MetricValueDescription
BLOCKS141.00Number of blocks
BLOCK_COMMENT21.00Number of block comment lines
COMMENTS88.00Comment lines
COMMENT_DENSITY 0.16Comment density
COMPARISONS101.00Number of comparison operators
CYCLOMATIC163.00Cyclomatic complexity
DECL_COMMENTS 3.00Comments in declarations
DOC_COMMENT 9.00Number of javadoc comment lines
ELOC547.00Effective lines of code
EXEC_COMMENTS38.00Comments in executable code
EXITS76.00Procedure exits
FUNCTIONS29.00Number of function declarations
HALSTEAD_DIFFICULTY112.14Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY79.00Interface complexity
JAVA0001 1.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 0.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
JAVA003416.00JAVA0034 Missing braces in if statement
JAVA0035 1.00JAVA0035 Missing braces in for statement
JAVA0036 1.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'
JAVA004918.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 2.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 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 1.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 2.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 0.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 0.00JAVA0116 Missing javadoc: field 'field'
JAVA011721.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 5.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 0.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 0.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.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 2.00JAVA0144 Line exceeds maximum M characters
JAVA01455139.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 6.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 4.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 2.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 5.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
LINES1140.00Number of lines in the source file
LINE_COMMENT58.00Number of line comments
LOC698.00Lines of code
LOGICAL_LINES342.00Number of statements
LOOPS28.00Number of loops
NEST_DEPTH10.00Maximum nesting depth
OPERANDS1383.00Number of operands
OPERATORS2819.00Number of operators
PARAMS40.00Number of formal parameter declarations
PROGRAM_LENGTH4202.00Halstead program length
PROGRAM_VOCAB430.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS39.00Number of return points from functions
SIZE29796.00Size of the file in bytes
UNIQUE_OPERANDS370.00Number of unique operands
UNIQUE_OPERATORS60.00Number of unique operators
WHITESPACE354.00Number of whitespace lines