Server Help Forum Index Server Help
Community forums for Subgame, ASSS, and bots
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   StatisticsStatistics   RegisterRegister 
 ProfileProfile   Login to check your private messagesLogin to check your private messages   LoginLogin (SSL) 

Server Help | ASSS Wiki (0) | Shanky.com
java dynamic load/unload/run

 
Post new topic   Reply to topic Printable version
 View previous topic  win32 Post :: Post UNIX script  View next topic  
Author Message
BDwinsAlt
Agurus's Posse


Age:33
Gender:Gender:Male
Joined: Jun 16 2003
Posts: 1145
Location: Alabama
Offline

PostPosted: Thu Jan 03, 2008 4:34 pm    Post subject: java dynamic load/unload/run Reply to topic Reply with quote

I've been googling for a while now. I can load a class and use .newInstance(), but I can't make it execute the code in that class.

Here is my current code
Code: Show/Hide

       File file = new File("modules");
           URL url = file.toURL();
           URL[] urls = new URL[]{url};
      
           ClassLoader cl = new URLClassLoader(urls);
           Class cls = cl.loadClass(moduleName);
           cls.newInstance();
           System.out.println("Loaded module: " + moduleName);


It runs fine without error and prints the module was loaded. Am I missing something?

I know I can do it like: ChatLog chatLog = new ChatLog();
I want people to be able to add there own modules into a folder named modules, then they can select which ever modules they want to use in that folder like: macros, chatlog, ect.

I need it to search for modules (I can probably figure that one out)
Then i need it to load and execute by using something.run(); where run in the class is:

public void run() { ... }

Any ideas on an easy way to do this?
Back to top
View users profile Send private message Add User to Ignore List Send email Visit posters website AIM Address Yahoo Messenger MSN Messenger
Bak
?ls -s
0 in


Age:24
Gender:Gender:Male
Joined: Jun 11 2004
Posts: 1826
Location: USA
Offline

PostPosted: Thu Jan 03, 2008 4:39 pm    Post subject: Reply to topic Reply with quote

use getMethod on the Class and then call invoke on the Method. You also probably want to store the object returned by newInstance()

getMethod: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getMethod(java.lang.String,%20java.lang.Class[])
invoke: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object[])

forum messes up the links, you have to copy and paste
_________________
SubSpace Discretion: A Third Generation SubSpace Client
Back to top
View users profile Send private message Add User to Ignore List AIM Address
Doc Flabby
Server Help Squatter


Joined: Feb 26 2006
Posts: 636
Offline

PostPosted: Thu Jan 03, 2008 4:57 pm    Post subject: Reply to topic Reply with quote

If you need an example have alook at how i did it in Skybill. That supports loadable modules.
_________________
Rediscover online gaming. Get Subspace | STF The future...prehaps
Back to top
View users profile Send private message Add User to Ignore List
BDwinsAlt
Agurus's Posse


Age:33
Gender:Gender:Male
Joined: Jun 16 2003
Posts: 1145
Location: Alabama
Offline

PostPosted: Thu Jan 03, 2008 5:45 pm    Post subject: Reply to topic Reply with quote

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: modules/ChatLog (wrong name: ChatLog)


I get that error when I use parts of the utils.java

It finds the file, but when it gets to: result.add(utils.createObject(modulePath + f1.getName().replace(".class", "")));

I think that is where it messes up.

Code: Show/Hide

   //dynamically create clases from string
   public static Object createObject(String className) {
         Object object = null;
         try {
             Class classDefinition = Class.forName(className);
             object = classDefinition.newInstance();
         } catch (InstantiationException e) {
             System.out.println(e);
         } catch (IllegalAccessException e) {
             System.out.println(e);
         } catch (ClassNotFoundException e) {
             System.out.println(e);
         }
         return object;
      }
   //get program direcotry
   public static String getProgramDirectory()
   {
      return new File(new File("t.tmp").getAbsolutePath()).getParentFile().getAbsolutePath();
   }

   //get list of modules in folder
   public static List<Object> getModuleList(String modulePath)
   {
      Vector<Object> result = new Vector<Object>();
      //get plugin directory
      
      File dir = new File(utils.getProgramDirectory() +
            ("." + modulePath).replace('.', File.separatorChar)
            );        
      
       // The list of files can also be retrieved as File objects
       File[] files = dir.listFiles();
      
       // This filter only returns directories
       FileFilter fileFilter = new FileFilter() {
           public boolean accept(File file) {
              if (file.getName().endsWith(".class"))
              {
               return file.isFile();
              }
              return false;
           }
       };
       files = dir.listFiles(fileFilter);
      
       for(File f1 :files)
       {
          result.add(utils.createObject(modulePath + f1.getName().replace(".class", "")));
          
       }
       return result;
   }

Back to top
View users profile Send private message Add User to Ignore List Send email Visit posters website AIM Address Yahoo Messenger MSN Messenger
Doc Flabby
Server Help Squatter


Joined: Feb 26 2006
Posts: 636
Offline

PostPosted: Thu Jan 03, 2008 6:11 pm    Post subject: Reply to topic Reply with quote

i recommend looking at subbill 0.2 (0.3 sucks)
util.java
biller.java

This is the method that loads a plugin for a server (is run everytime a new server connects)
Code: Show/Hide

private void attachServerEventListeners(Server s1){
      //get plugin directory
      File dir = new File(utils.getProgramDirectory() +
            ".com.playSubSpace.TCPBiller.Plugins.Server".replace('.', File.separatorChar)
            );        
      
       // The list of files can also be retrieved as File objects
       File[] files = dir.listFiles();
      
       // This filter only returns directories
       FileFilter fileFilter = new FileFilter() {
           public boolean accept(File file) {
              if (file.getName().endsWith(".class"))
              {
               return file.isFile();
              }
              return false;
           }
       };
       files = dir.listFiles(fileFilter);
      
       for(File f1 :files)
       {
         IServerListener temp = (IServerListener)utils.createObject(
               "com.playSubSpace.TCPBiller.Plugins.Server."+ f1.getName().replace(".class", "") ) ;
        
         System.out.println("Loading Server Command Module:" + f1.getName().replace(".class", "") );
        
         s1.addServerListener(temp);

       }
   }


I would recommend double checking the path is correct its trying to load the class from, it might be loading the wrong classfile. The class name must also be the same name as the file (case as well)
Back to top
View users profile Send private message Add User to Ignore List
BDwinsAlt
Agurus's Posse


Age:33
Gender:Gender:Male
Joined: Jun 16 2003
Posts: 1145
Location: Alabama
Offline

PostPosted: Thu Jan 03, 2008 9:32 pm    Post subject: Reply to topic Reply with quote

I am able to load the class, but it hogs up the entire program. Is there a way to play with invoke so it does allow that one class to do eveything. I tired putting it into a separate thread, but it stops anything from displaying the the text boxes.
Back to top
View users profile Send private message Add User to Ignore List Send email Visit posters website AIM Address Yahoo Messenger MSN Messenger
Bak
?ls -s
0 in


Age:24
Gender:Gender:Male
Joined: Jun 11 2004
Posts: 1826
Location: USA
Offline

PostPosted: Fri Jan 04, 2008 9:20 am    Post subject: Reply to topic Reply with quote

did you call repaint on the textboxes after you changed them?
Back to top
View users profile Send private message Add User to Ignore List AIM Address
BDwinsAlt
Agurus's Posse


Age:33
Gender:Gender:Male
Joined: Jun 16 2003
Posts: 1145
Location: Alabama
Offline

PostPosted: Fri Jan 04, 2008 5:40 pm    Post subject: Reply to topic Reply with quote

I try to get the text from them, but then it won't update anything. I'll try doing module loading from another class.

Edit: It will allow me to enter text, but it won't display the text that is appended when the server sends it.

Edit 2: If I add something to the box, then load the module, it display what was there before loading, otherwise it just stays blank. new_let_it_all_out.gif

Edit 3: SOLVED
I tried running it as a thread again. Worked. I'm using an easy plugin method I found.
Back to top
View users profile Send private message Add User to Ignore List Send email Visit posters website AIM Address Yahoo Messenger MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    Server Help Forum Index -> Non-Subspace Related Coding All times are GMT - 5 Hours
Page 1 of 1

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum
View online users | View Statistics | View Ignored List


Software by php BB © php BB Group
Server Load: 669 page(s) served in previous 5 minutes.

phpBB Created this page in 0.786130 seconds : 33 queries executed (89.8%): GZIP compression disabled