1 16 17 package examples; 18 19 import java.rmi.Remote ; 20 import java.rmi.server.UnicastRemoteObject ; 21 import java.rmi.RemoteException ; 22 import java.rmi.Naming ; 23 import java.util.Vector ; 24 25 26 import org.apache.log4j.Logger; 27 import org.apache.log4j.NDC; 28 import org.apache.log4j.PropertyConfigurator; 29 30 62 public class NumberCruncherServer extends UnicastRemoteObject 63 implements NumberCruncher { 64 65 66 static Logger logger = Logger.getLogger(NumberCruncherServer.class); 67 68 public 69 NumberCruncherServer() throws RemoteException { 70 } 71 72 public 73 int[] factor(int number) throws RemoteException { 74 75 try { 77 NDC.push(this.getClientHost()); 78 } 79 catch(java.rmi.server.ServerNotActiveException e) { 80 NDC.push("localhost"); 82 } 83 84 NDC.push(String.valueOf(number)); 89 90 logger.info("Beginning to factor."); 91 if(number <= 0) { 92 throw new IllegalArgumentException (number+" is not a positive integer."); 93 } 94 else if(number == 1) 95 return new int[] {1}; 96 97 Vector factors = new Vector (); 98 int n = number; 99 100 for(int i = 2; (i <= n) && (i*i <= number); i++) { 101 logger.debug("Trying to see if " + i + " is a factor."); 105 106 if((n % i) == 0) { 107 logger.info("Found factor "+i); 108 factors.addElement(new Integer (i)); 109 do { 110 n /= i; 111 } while((n % i) == 0); 112 } 113 delay(100); 116 } 117 118 if(n != 1) { 119 logger.info("Found factor "+n); 120 factors.addElement(new Integer (n)); 121 } 122 123 int len = factors.size(); 124 125 int[] result = new int[len]; 126 for(int i = 0; i < len; i++) { 127 result[i] = ((Integer ) factors.elementAt(i)).intValue(); 128 } 129 130 NDC.remove(); 136 137 return result; 138 } 139 140 static 141 void usage(String msg) { 142 System.err.println(msg); 143 System.err.println( 144 "Usage: java org.apache.log4j.examples.NumberCruncherServer configFile\n" + 145 " where configFile is a log4j configuration file."); 146 System.exit(1); 147 } 148 149 public static 150 void delay(int millis) { 151 try{Thread.currentThread().sleep(millis);} 152 catch(InterruptedException e) {} 153 } 154 155 public static void main(String [] args) { 156 if(args.length != 1) 157 usage("Wrong number of arguments."); 158 159 NumberCruncherServer ncs; 160 PropertyConfigurator.configure(args[0]); 161 try { 162 ncs = new NumberCruncherServer(); 163 Naming.rebind("Factor", ncs); 164 logger.info("NumberCruncherServer bound and ready to serve."); 165 } 166 catch(Exception e) { 167 logger.error("Could not bind NumberCruncherServer.", e); 168 return; 169 } 170 NumberCruncherClient.loop(ncs); 171 } 172 } 173 | Popular Tags |