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

📄 plugininitializer.java

📁 这是一个基于java编写的torrent的P2P源码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
				Logger.log(new LogEvent(LOGID, "Loading plugin "
						+ pluginsDirectory[i].getName()));

	    if(core_operation != null) {
  	      	
	    	core_operation.reportCurrentTask(MessageText.getString("splash.plugin") + pluginsDirectory[i].getName());
	    }
	      
	    try{
	    
	    	List	loaded_pis = loadPluginFromDir(pluginsDirectory[i], bSkipAlreadyLoaded);
	      	
	    		// save details for later initialisation
	    	
	    	loaded_pi_list.add( loaded_pis );
	    	dirLoadedPIs.addAll( loaded_pis );
	    	
	      }catch( PluginException e ){
	      	
	      		// already handled
	      }
	      
	      if( core_operation != null ){
	      	
	    	  core_operation.reportPercent( (100 * (i + plugin_offset)) / plugin_total );
	      }
	    }
    } 
    return dirLoadedPIs;
  }
  
  private List 
  loadPluginFromDir(
  	File directory,
  	boolean bSkipAlreadyLoaded)
  
  	throws PluginException
  {
    List	loaded_pis = new ArrayList();
    
  	ClassLoader plugin_class_loader = root_class_loader;
  	
    if( !directory.isDirectory()){
    	
    	return( loaded_pis );
    }
    
    String pluginName = directory.getName();
    
    File[] pluginContents = directory.listFiles();
    
    if ( pluginContents == null || pluginContents.length == 0){
    	
    	return( loaded_pis );
    }
    
    	// first sanity check - dir must include either a plugin.properties or
    	// at least one .jar file
    
    boolean	looks_like_plugin	= false;
    
    for (int i=0;i<pluginContents.length;i++){
    	
    	String	name = pluginContents[i].getName().toLowerCase();
    	
    	if ( name.endsWith( ".jar") || name.equals( "plugin.properties" )){
    		
    		looks_like_plugin = true;
    		
    		break;
    	}
    }
    
    if ( !looks_like_plugin ){
    	
    	if (Logger.isEnabled())
				Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING,
						"Plugin directory '" + directory + "' has no plugin.properties "
								+ "or .jar files, skipping"));
    	
    	return( loaded_pis );
    }
    
    	// take only the highest version numbers of jars that look versioned
    
    String[]	plugin_version = {null};
    String[]	plugin_id = {null};
    
    pluginContents	= PluginLauncherImpl.getHighestJarVersions( pluginContents, plugin_version, plugin_id, true );
    
    for( int i = 0 ; i < pluginContents.length ; i++){
    	
    	File	jar_file = pluginContents[i];
    	
    		// migration hack for i18nAZ_1.0.jar
    	
    	if ( pluginContents.length > 1 ){
    		
    		String	name = jar_file.getName();
    		
    		if ( name.startsWith( "i18nPlugin_" )){
    			
    				// non-versioned version still there, rename it
    			
    			if (Logger.isEnabled())
						Logger.log(new LogEvent(LOGID, "renaming '" + name
								+ "' to conform with versioning system"));
    			
    			jar_file.renameTo( new File( jar_file.getParent(), "i18nAZ_0.1.jar  " ));
    			
    			continue;
    		}
    	}
    	
        plugin_class_loader = PluginLauncherImpl.addFileToClassPath( root_class_loader, plugin_class_loader, jar_file);
    }
        
    String plugin_class_string = null;
    
    try {
      Properties props = new Properties();
      
      File	properties_file = new File(directory.toString() + File.separator + "plugin.properties");
 
      try {
      	
      		// if properties file exists on its own then override any properties file
      		// potentially held within a jar
      	
      	if ( properties_file.exists()){
      	
      		FileInputStream	fis = null;
      		
      		try{
      			fis = new FileInputStream( properties_file );
      		
      			props.load( fis );
      			
      		}finally{
      			
      			if ( fis != null ){
      				
      				fis.close();
      			}
      		}
      		
      	}else{
      		
      		if ( plugin_class_loader instanceof URLClassLoader ){
      			
      			URLClassLoader	current = (URLClassLoader)plugin_class_loader;
      		    			
      			URL url = current.findResource("plugin.properties");
      		
      			if ( url != null ){
        			URLConnection connection = url.openConnection();
        			
        			InputStream is = connection.getInputStream();
      				
      				props.load(is);
      				
      			}else{
      				
      				throw( new Exception( "failed to load plugin.properties from jars"));
      			}
      		}else{
      			
 				throw( new Exception( "failed to load plugin.properties from dir or jars"));
 				      			
      		}
      	}
      }catch( Throwable e ){
      	
      	Debug.printStackTrace( e );
      	
      	String	msg =  "Can't read 'plugin.properties' for plugin '" + pluginName + "': file may be missing";
      	
      	Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, msg));
      	  
        System.out.println( msg );
        
        throw( new PluginException( msg, e ));
      }

      plugin_class_string = (String)props.get( "plugin.class");
      
      if ( plugin_class_string == null ){
      	
      	plugin_class_string = (String)props.get( "plugin.classes");
      }
      
      String	plugin_name_string = (String)props.get( "plugin.name");
      
      if ( plugin_name_string == null ){
      	
      	plugin_name_string = (String)props.get( "plugin.names");
      }
 
      int	pos1 = 0;
      int	pos2 = 0;
                 
      while(true){
  		int	p1 = plugin_class_string.indexOf( ";", pos1 );
  	
  		String	plugin_class;
  	
  		if ( p1 == -1 ){
  			plugin_class = plugin_class_string.substring(pos1).trim();
  		}else{
  			plugin_class	= plugin_class_string.substring(pos1,p1).trim();
  			pos1 = p1+1;
  		}
  
  		PluginInterfaceImpl existing_pi = getPluginFromClass( plugin_class );
  		
  		if ( existing_pi != null ){
  			
  			if (bSkipAlreadyLoaded) {
  				break;
  			}
  				
  				// allow user dir entries to override app dir entries without warning
  			
  			File	this_parent 	= directory.getParentFile();
  			File	existing_parent = null;
  			
  			if ( existing_pi.getInitializerKey() instanceof File ){
  				
  				existing_parent	= ((File)existing_pi.getInitializerKey()).getParentFile();
  			}
  			
  			if ( 	this_parent.equals( FileUtil.getApplicationFile("plugins")) &&
  					existing_parent	!= null &&
  					existing_parent.equals( FileUtil.getUserFile( "plugins" ))){
  				
  					// skip this overridden plugin
  				
  				Logger.log(new LogEvent(LOGID, "Plugin '" + plugin_name_string
								+ "/" + plugin_class
								+ ": shared version overridden by user-specific one"));
  				
  				return( new ArrayList());
  				
  			}else{
  				Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_WARNING,
								"Error loading '" + plugin_name_string + "', plugin class '"
										+ plugin_class + "' is already loaded"));
  			}

  		}else{
  			
  		  String	plugin_name = null;
  		  
  		  if ( plugin_name_string != null ){
  		  	
  		  	int	p2 = plugin_name_string.indexOf( ";", pos2 );
          	
      	
      		if ( p2 == -1 ){
      			plugin_name = plugin_name_string.substring(pos2).trim();
      		}else{
      			plugin_name	= plugin_name_string.substring(pos2,p2).trim();
      			pos2 = p2+1;
      		}    
  		  }
  		  
  		  Properties new_props = (Properties)props.clone();
  		  
  		  for (int j=0;j<default_version_details.length;j++){
  		  	
  		  	if ( plugin_class.equals( default_version_details[j][0] )){
  		  
		  		if ( new_props.get( "plugin.id") == null ){
  		  			
		  			new_props.put( "plugin.id", default_version_details[j][1]);  
  		  		}
		  		
		  		if ( plugin_name == null ){
		  			
		  			plugin_name	= default_version_details[j][2];
		  		}
		  		
		  		if ( new_props.get( "plugin.version") == null ){

		  				// no explicit version. If we've derived one then use that, otherwise defaults
 		  			
		  			if ( plugin_version[0] != null ){
		  
		  				new_props.put( "plugin.version", plugin_version[0]);
		     		    		  				
		  			}else{
		  				
		  				new_props.put( "plugin.version", default_version_details[j][3]);
		  			}
  		  		}
  		  	}
  		  }
  		  
  		  new_props.put( "plugin.class", plugin_class );
  		  
  		  if ( plugin_name != null ){
  		  	
  		  	new_props.put( "plugin.name", plugin_name );
  		  }
  		       		       		  
 	      // System.out.println( "loading plugin '" + plugin_class + "' using cl " + classLoader);
	      
	      	// if the plugin load fails we still need to generate a plugin entry
  		  	// as this drives the upgrade process
  		  
	      
	      Throwable	load_failure	= null;
	      
	      String pid = plugin_id[0]==null?directory.getName():plugin_id[0];
	      
	      Plugin plugin = PluginLauncherImpl.getPreloadedPlugin( plugin_class );
	      
	      if ( plugin == null ){
	    	  
	    	  try{
	    		  Class c = plugin_class_loader.loadClass(plugin_class);
		      
	    		  plugin	= (Plugin) c.newInstance();
	    		  
	    	  }catch (java.lang.UnsupportedClassVersionError e) {
	    		  plugin = new FailedPlugin(plugin_name,directory.getAbsolutePath());
	    		  
	    		  // shorten stack trace
	    		  load_failure	= new UnsupportedClassVersionError(e.getMessage());
	    		  
	    	  }catch( Throwable e ){
	      	
	    		  load_failure	= e;
	      	
	    		  plugin = new FailedPlugin(plugin_name,directory.getAbsolutePath());
	    	  }
	      }else{
	    	  
	    	  plugin_class_loader = plugin.getClass().getClassLoader();
	      }
	      
	      MessageText.integratePluginMessages((String)props.get("plugin.langfile"),plugin_class_loader);

	      PluginInterfaceImpl plugin_interface = 
	      		new PluginInterfaceImpl(
	      					plugin, 
							this, 
							directory, 
							plugin_class_loader,
							directory.getName(),	// key for config values
							new_props,
							directory.getAbsolutePath(),
							pid,
							plugin_version[0] );
	      
	      // Must use getPluginID() instead of pid, because they may differ
	      boolean bEnabled = COConfigurationManager
							.getBooleanParameter("PluginInfo."
									+ plugin_interface.getPluginID() + ".enabled", true);
	      
	      plugin_interface.setDisabled(!bEnabled);

	      try{
	      
	      	Method	load_method = plugin.getClass().getMethod( "load", new Class[]{ PluginInterface.class });
	      	
	      	load_method.invoke( plugin, new Object[]{ plugin_interface });
	      	
	      }catch( NoSuchMethodException e ){
	      	
	      }catch( Throwable e ){
	      	
	      	load_failure	= e;
	      }
	      
	      loaded_pis.add( plugin_interface );
	      
	      if ( load_failure != null ){
	      		  
	    	  	// don't complain about our internal one
	    	  
	    	  if ( !pid.equals(UpdaterUpdateChecker.getPluginID())){
	    		  
		      	String	msg = "Error loading plugin '" + pluginName + "' / '" + plugin_class_string + "'";
		   	 
		      	Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, load_failure));
	
		      	System.out.println( msg + " : " + load_failure);
		      }
	      }
  		}
	      
	    if ( p1 == -1 ){
	    	break;
	      	
	    }
      }
            
      return( loaded_pis );
      
    }catch(Throwable e) {
    	
    	if ( e instanceof PluginException ){
    		
    		throw((PluginException)e);
    	}
   
    	Debug.printStackTrace( e );
      
    	String	msg = "Error loading plugin '" + pluginName + "' / '" + plugin_class_string + "'";
 	 
    	Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, e));

    	System.out.println( msg + " : " + e);
    	
    	throw( new PluginException( msg, e ));
    }
  }
  
  public void initialisePlugins() {
		for (int i = 0; i < loaded_pi_list.size(); i++) {
			try {
				List l = (List) loaded_pi_list.get(i);

				if (l.size() > 0) {
					PluginInterfaceImpl plugin_interface = (PluginInterfaceImpl) l.get(0);

					if (Logger.isEnabled())
						Logger.log(new LogEvent(LOGID, "Initializing plugin '"
								+ plugin_interface.getPluginName() + "'"));

					if (core_operation != null) {
						core_operation.reportCurrentTask(MessageText
								.getString("splash.plugin.init")
								+ plugin_interface.getPluginName());
					}

					initialisePlugin(l);
					
					if (Logger.isEnabled())
						Logger.log(new LogEvent(LOGID, "Initialization of plugin '"
								+ plugin_interface.getPluginName() + "' complete"));

				}

			} catch (PluginException e) {
				// already handled
			} finally {
				if (core_operation != null) {
					core_operation.reportPercent((100 * (i + 1)) / loaded_pi_list.size());
				}
			}
		}

		// some plugins try and steal the logger stdout redirects. 
		// re-establish them if needed
		Logger.doRedirects();

		// now do built in ones

		if (Logger.isEnabled())
			Logger.log(new LogEvent(LOGID, "Initializing built-in plugins"));

		PluginManagerDefaults def = PluginManager.getDefaults();

		for (int i = 0; i < builtin_plugins.length; i++) {
			if (def.isDefaultPluginEnabled(builtin_plugins[i][0])) {
				String id = builtin_plugins[i][2];
				String key = builtin_plugins[i][3];

				try {
					Class cla = root_class_loader.loadClass(
							builtin_plugins[i][1]);

					if (Logger.isEnabled())
						Logger.log(new LogEvent(LOGID, "Initializing built-in plugin '"
								+ builtin_plugins[i][2] + "'" ));

					initializePluginFromClass(cla, id, key);

					Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING,
							"Initialization of built in plugin '" + builtin_plugins[i][2] + "' complete"));
				} catch (Throwable e) {
					try {
						// replace it with a "broken" plugin instance
						initializePluginFromClass(FailedPlugin.class, id, key);

					} catch (Throwable f) {
					}

					if (builtin_plugins[i][4].equalsIgnoreCase("true")) {
						Debug.printStackTrace(e);
						Logger.log(new LogAlert(LogAlert.UNREPEATABLE,
								"Initialization of built in plugin '" + builtin_plugins[i][2]
										+ "' fails", e));
					}
				}
			} else {
				if (Logger.isEnabled())
					Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING,
							"Built-in plugin '" + builtin_plugins[i][2] + "' is disabled"));
			}
		}

		if (Logger.isEnabled())
			Logger.log(new LogEvent(LOGID,
					"Initializing dynamically registered plugins"));

		for (int i = 0; i < registration_queue.size(); i++) {
			try {
				Object entry = registration_queue.get(i);

				if (entry instanceof Class) {

					Class cla = (Class) entry;

					singleton.initializePluginFromClass(cla, INTERNAL_PLUGIN_ID, cla
							.getName());

				} else {
					Object[] x = (Object[]) entry;

					Plugin plugin = (Plugin) x[0];

					singleton.initializePluginFromInstance(plugin, (String) x[1], plugin
							.getClass().getName());
				}
			} catch (PluginException e) {

⌨️ 快捷键说明

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