⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 globalmanagerimpl.java

📁 这是一个基于java编写的torrent的P2P源码
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
		    
		    return( false );
		    
		}finally{
			
			paused_list_mon.exit();
		}
	}
	
	public boolean 
	canPauseDownloads() 
	{
		for( Iterator i = managers_cow.iterator(); i.hasNext(); ) {
      
			DownloadManager manager = (DownloadManager)i.next();
      
			if ( canPauseDownload( manager )){
    	  
				return( true );
			}
		}
		return false;
	}


  public void 
  resumeDownload(
	DownloadManager	manager )
  {
	boolean	resume_ok 	= false;
	boolean force		= false;
		
	try {  
		paused_list_mon.enter();
		
	    for( int i=0; i < paused_list.size(); i++ ) {
	    	
	      	Object[]	data = (Object[])paused_list.get(i);
	      	
	        HashWrapper hash = (HashWrapper)data[0];
	        
	        force = ((Boolean)data[1]).booleanValue();
	        
	        DownloadManager this_manager = getDownloadManager( hash );
	      
	        if ( this_manager == manager ){
	        	
	        	resume_ok	= true;
	        	
	        	paused_list.remove(i);
	        	
	        	break;
	        }
	    }
	}finally{  
	    	
		paused_list_mon.exit();  
   	}
	    
	if ( resume_ok ){
	    	
		if ( manager.getState() == DownloadManager.STATE_STOPPED ) {
  	          
			if ( force ){
        			
        		manager.setForceStart(true);
        		
        	}else{
          	
        		manager.stopIt( DownloadManager.STATE_QUEUED, false, false );
        	}
        }   	
	}
  }
  
  public void resumeDownloads() {
    try {  paused_list_mon.enter();
      for( int i=0; i < paused_list.size(); i++ ) {     
      	Object[]	data = (Object[])paused_list.get(i);
      	
        HashWrapper hash = (HashWrapper)data[0];
        boolean		force = ((Boolean)data[1]).booleanValue();
        
        DownloadManager manager = getDownloadManager( hash );
      
        if( manager != null && manager.getState() == DownloadManager.STATE_STOPPED ) {
          
          if ( force ){
          	manager.setForceStart(true);
          }else{
          	
        	manager.stopIt( DownloadManager.STATE_QUEUED, false, false );
          }
        }
      }
      paused_list.clear();
    }
    finally {  paused_list_mon.exit();  }
  }


  public boolean canResumeDownloads() {
    try {  paused_list_mon.enter();
      for( int i=0; i < paused_list.size(); i++ ) {  
      	Object[]	data = (Object[])paused_list.get(i);
        HashWrapper hash = (HashWrapper)data[0];
        DownloadManager manager = getDownloadManager( hash );
      
        if( manager != null && manager.getState() == DownloadManager.STATE_STOPPED ) {
          return true;
        }
      }
    }
    finally {  paused_list_mon.exit();  }
    
    return false;
  }
  
  
  
  private void loadDownloads(GlobalMangerProgressListener listener) 
  {
	  try{
		  DownloadManagerStateFactory.loadGlobalStateCache();
		  
		  int triggerOnCount = 2;
		  ArrayList downloadsAdded = new ArrayList();
		  long lastListenerUpdate = 0;
		  try{
			  if (listener != null)
				  listener.reportCurrentTask(MessageText.getString("splash.loadingTorrents"));
	
			  Map map = FileUtil.readResilientConfigFile("downloads.config");
	
			  boolean debug = Boolean.getBoolean("debug");
	
			  Iterator iter = null;
			  //v2.0.3.0+ vs older mode
			  List downloads = (List) map.get("downloads");
			  int nbDownloads;
			  if (downloads == null) {
				  //No downloads entry, then use the old way
				  iter = map.values().iterator();
				  nbDownloads = map.size();
			  }
			  else {
				  //New way, downloads stored in a list
				  iter = downloads.iterator();
				  nbDownloads = downloads.size();
			  }
			  int currentDownload = 0;
			  while (iter.hasNext()) {
				  currentDownload++;        
				  Map mDownload = (Map) iter.next();
				  try {
					  byte[]	torrent_hash = (byte[])mDownload.get( "torrent_hash" );
	
					  Long	lPersistent = (Long)mDownload.get( "persistent" );
	
					  boolean	persistent = lPersistent==null || lPersistent.longValue()==1;
	
	
					  String fileName = new String((byte[]) mDownload.get("torrent"), Constants.DEFAULT_ENCODING);
	
					  if(listener != null &&  SystemTime.getCurrentTime() - lastListenerUpdate > 100) {
						  lastListenerUpdate = SystemTime.getCurrentTime();
	
						  listener.reportPercent(100 * currentDownload / nbDownloads);
						  listener.reportCurrentTask(MessageText.getString("splash.loadingTorrent") 
								  + " " + currentDownload + " "
								  + MessageText.getString("splash.of") + " " + nbDownloads
								  + " : " + fileName );
					  }
	
					  //migration from using a single savePath to a separate dir and file entry
					  String	torrent_save_dir;
					  String	torrent_save_file;
	
					  byte[] torrent_save_dir_bytes   = (byte[]) mDownload.get("save_dir");
	
					  if ( torrent_save_dir_bytes != null ){
	
						  byte[] torrent_save_file_bytes 	= (byte[]) mDownload.get("save_file");
	
						  torrent_save_dir	= new String(torrent_save_dir_bytes, Constants.DEFAULT_ENCODING);
	
						  if ( torrent_save_file_bytes != null ){
	
							  torrent_save_file	= new String(torrent_save_file_bytes, Constants.DEFAULT_ENCODING);       		
						  }else{
	
							  torrent_save_file	= null;
						  }
					  }else{
	
						  byte[] savePathBytes = (byte[]) mDownload.get("path");
						  torrent_save_dir 	= new String(savePathBytes, Constants.DEFAULT_ENCODING);
						  torrent_save_file	= null;
					  }
	
	
	
					  int state = DownloadManager.STATE_WAITING;
					  if (debug){
	
						  state = DownloadManager.STATE_STOPPED;
	
					  }else {
	
						  if (mDownload.containsKey("state")) {
							  state = ((Long) mDownload.get("state")).intValue();
							  if (state != DownloadManager.STATE_STOPPED &&
									  state != DownloadManager.STATE_QUEUED &&
									  state != DownloadManager.STATE_WAITING)
	
								  state = DownloadManager.STATE_QUEUED;
	
						  }else{
	
							  int stopped = ((Long) mDownload.get("stopped")).intValue();
	
							  if (stopped == 1){
	
								  state = DownloadManager.STATE_STOPPED;
							  }
						  } 
					  }        
	
					  Long seconds_downloading = (Long)mDownload.get("secondsDownloading");
	
					  boolean	has_ever_been_started = seconds_downloading != null && seconds_downloading.longValue() > 0;
	
					  if (torrent_hash != null) {
						  saved_download_manager_state.put(new HashWrapper(torrent_hash),
								  mDownload);
					  }
	
					  // for non-persistent downloads the state will be picked up if the download is re-added
					  // it won't get saved unless it is picked up, hence dead data is dropped as required
	
					  if ( persistent ){
	
						  List file_priorities = (List) mDownload.get("file_priorities");
	
						  final DownloadManager dm = 
							  DownloadManagerFactory.create(
									  this, torrent_hash, fileName, torrent_save_dir, torrent_save_file, 
									  state, true, true, has_ever_been_started, file_priorities );
	
						  if (addDownloadManager(dm, false, false) == dm) {
							  downloadsAdded.add(dm);
	
							  if (downloadsAdded.size() >= triggerOnCount) {
								  triggerOnCount *= 2;
								  triggerAddListener(downloadsAdded);
								  downloadsAdded.clear();
							  }
						  }
					  }
				  }
				  catch (UnsupportedEncodingException e1) {
					  //Do nothing and process next.
				  }
				  catch (Throwable e) {
					  Logger.log(new LogEvent(LOGID,
							  "Error while loading downloads.  " +
							  "One download may not have been added to the list.", e));
				  }
			  }
	
			  // This is set to true by default, but once the downloads have been loaded, we have no reason to ever
			  // to do this check again - we only want to do it once to upgrade the state of existing downloads
			  // created before this code was around.
			  COConfigurationManager.setParameter("Set Completion Flag For Completed Downloads On Start", false);
	
			  //load pause/resume state
			  ArrayList pause_data = (ArrayList)map.get( "pause_data" );
			  if( pause_data != null ) {
				  try {  paused_list_mon.enter();
				  for( int i=0; i < pause_data.size(); i++ ) {
					  Object	pd = pause_data.get(i);
	
					  byte[]		key;
					  boolean		force;
	
					  if ( pd instanceof byte[]){
						  // old style, migration purposes
						  key 	= (byte[])pause_data.get( i );
						  force	= false;
					  }else{
						  Map	m = (Map)pd;
	
						  key 	= (byte[])m.get("hash");
						  force 	= ((Long)m.get("force")).intValue() == 1;
					  }
					  paused_list.add( new Object[]{ new HashWrapper( key ), new Boolean( force )} );
				  }
				  }
				  finally {  paused_list_mon.exit();  }
			  }
	
	
			  // Someone could have mucked with the config file and set weird positions,
			  // so fix them up.
			  fixUpDownloadManagerPositions();
			  Logger.log(new LogEvent(LOGID, "Loaded " + managers_cow.size()
					  + " torrents"));
	
		  }catch( Throwable e ){
			  // there's been problems with corrupted download files stopping AZ from starting
			  // added this to try and prevent such foolishness
	
			  Debug.printStackTrace( e );
		  } finally {
			  loadingComplete = true;
			  triggerAddListener(downloadsAdded);
	
			  loadingSem.releaseForever();
		  }
			  
	  }finally{
		  
		  DownloadManagerStateFactory.discardGlobalStateCache();
	  }
  }
  
  private void triggerAddListener(List downloadsToAdd) {
		try {
			managers_mon.enter();
			List listenersCopy = listeners.getListenersCopy();

			for (int j = 0; j < listenersCopy.size(); j++) {
				GlobalManagerListener gmListener = (GlobalManagerListener) listenersCopy.get(j);
				for (int i = 0; i < downloadsToAdd.size(); i++) {
					DownloadManager dm = (DownloadManager) downloadsToAdd.get(i);
					gmListener.downloadManagerAdded(dm);
				}
			}
		} finally {

			managers_mon.exit();
		}
  }


  protected void 
  saveDownloads(
  	boolean	immediate ) 
  {
	  if ( !immediate ){
		  
		  needsSaving	= true;
		  
		  return;
	  }
	  
  	if (!loadingComplete) {
  		needsSaving = true;
  		return;
  	}

    //    if(Boolean.getBoolean("debug")) return;

	  needsSaving = false;
	  
  	try{
  		managers_mon.enter();
  		
	    Collections.sort(managers_cow, new Comparator () {
        public final int compare (Object a, Object b) {
        	return ((DownloadManager) a).getPosition()
							- ((DownloadManager) b).getPosition();
        }
      });
  	
      if (Logger.isEnabled())
				Logger.log(new LogEvent(LOGID, "Saving Download List ("
						+ managers_cow.size() + " items)"));
	    Map map = new HashMap();
	    List list = new ArrayList(managers_cow.size());
	    for (int i = 0; i < managers_cow.size(); i++) {
	      DownloadManager dm = (DownloadManager) managers_cow.get(i);
	      
	      	DownloadManagerStats dm_stats = dm.getStats();
		      Map dmMap = new HashMap();
		      TOTorrent	torrent = dm.getTorrent();
		      
		      if ( torrent != null ){
		      	try{
		      		dmMap.put( "torrent_hash", torrent.getHash());
		      		
		      	}catch( TOTorrentException e ){
		      		
		      		Debug.printStackTrace(e);
		      	}
		      }
		      
		      File	save_loc = dm.getAbsoluteSaveLocation();
		      dmMap.put("persistent", new Long(dm.isPersistent()?1:0));
		      dmMap.put("torrent", dm.getTorrentFileName());
		      dmMap.put("save_dir", save_loc.getParent());
		      dmMap.put("save_file", save_loc.getName());
		
		      dmMap.put("maxdl", new Long( dm_stats.getDownloadRateLimitBytesPerSecond() ));
		      dmMap.put("maxul", new Long( dm_stats.getUploadRateLimitBytesPerSecond() ));
		      
          int state = dm.getState();
          
          if (state == DownloadManager.STATE_ERROR ){
          
        	  	// torrents in error state always come back stopped
        	  
            state = DownloadManager.STATE_STOPPED;
            
	      }else if (	dm.getAssumedComplete() && !dm.isForceStart() && 
	    		  		state != DownloadManager.STATE_STOPPED) {
	    	  
	    	state = DownloadManager.STATE_QUEUED;
	    	  	
	      }else if (	state != DownloadManager.STATE_STOPPED &&
                  		state != DownloadManager.STATE_QUEUED &&
                  		state != DownloadManager.STATE_WAITING){
	    	  
            state = DownloadManager.STATE_WAITING;
            
	      }
          
          dmMap.put("state", new Long(state));		      
	      dmMap.put("position", new Long(dm.getPosition()));
	      dmMap.put("downloaded", new Long(dm_stats.getTotalDataBytesReceived()));
	      dmMap.put("uploaded", new Long(dm_stats.getTotalDataBytesSent()));
	      dmMap.put("completed", new Long(dm_stats.getDownloadCompleted(true)));
	      dmMap.put("discarded", new Long(dm_stats.getDiscarded()));
	      dmMap.put("hashfailbytes", new Long(dm_stats.getHashFailBytes()));
	      dmMap.put("forceStart", new Long(dm.isForceStart() && (dm.getState() != DownloadManager.STATE_CHECKING) ? 1 : 0));
	      dmMap.put("secondsDownloading", new Long(dm_stats.getSecondsDownloading()));
	      dmMap.put("secondsOnlySeeding", new Long(dm_stats.getSecondsOnlySeeding()));
      
	      	// although this has been migrated, keep storing it to allow regression for a while
	      dmMap.put("uploads", new Long(dm.getMaxUploads()));
	      
	      dmMap.put("creationTime", new Long( dm.getCreationTime()));
		      
		      //save file priorities
 
		  dm.saveDownload();
		  
          List file_priorities = (List)dm.getData( "file_priorities" );
          if ( file_priorities != null ) dmMap.put( "file_priorities" , file_priorities );

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -