KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > core > jini > ServiceLocatorHelper


1 /*
2 * ################################################################
3 *
4 * ProActive: The Java(TM) library for Parallel, Distributed,
5 * Concurrent computing with Security and Mobility
6 *
7 * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
8 * Contact: proactive-support@inria.fr
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23 * USA
24 *
25 * Initial developer(s): The ProActive Team
26 * http://www.inria.fr/oasis/ProActive/contacts.html
27 * Contributor(s):
28 *
29 * ################################################################
30 */

31 package org.objectweb.proactive.core.jini;
32
33 import java.io.File JavaDoc;
34 import java.io.IOException JavaDoc;
35
36 import net.jini.core.discovery.LookupLocator;
37 import net.jini.core.lookup.ServiceMatches;
38 import net.jini.core.lookup.ServiceRegistrar;
39 import net.jini.core.lookup.ServiceTemplate;
40
41 import net.jini.discovery.DiscoveryEvent;
42 import net.jini.discovery.DiscoveryListener;
43 import net.jini.discovery.LookupDiscovery;
44
45 import org.apache.log4j.Logger;
46
47 import org.objectweb.proactive.core.runtime.jini.JiniRuntime;
48
49
50 /**
51   * <p>
52   * The <code>ServiceLocatorHelper</code> is a utility class, that takes
53         * care of creating or discovering the
54   * Lookup Service when using JINI.
55   * </p>
56   *
57   * @author ProActive Team
58   * @version 1.0, 2002/09/20
59   * @since ProActive 0.9.3
60   *
61   */

62 public class ServiceLocatorHelper implements DiscoveryListener {
63     protected static Logger logger = Logger.getLogger(ServiceLocatorHelper.class.getName());
64     protected static int MAX_RETRY = 8;
65     protected static long MAX_WAIT = 10000L;
66     private static String JavaDoc DEFAULT_POLICY = System.getProperty("user.dir") +
67         System.getProperty("file.separator") + "proactive.java.policy";
68     private static final String JavaDoc FILE_SEPARATOR = System.getProperty(
69             "file.separator");
70     private static String JavaDoc policy;
71     private static String JavaDoc DEFAULT_RMID_LOCATION = System.getProperty(
72             "java.home") + FILE_SEPARATOR + "bin" + FILE_SEPARATOR + "rmid";
73     private static String JavaDoc DEFAULT_RMID_PARAMS = "-J-Djava.security.policy=";
74     protected static LookupLocator lookup = null;
75     protected static ServiceRegistrar registrar = null;
76
77     /**
78  * settings of the service locator
79  */

80     protected boolean shouldCreateServiceLocator = true;
81     protected boolean locatorChecked;
82     protected static boolean multicastLocator = false;
83     private static String JavaDoc host = null;
84
85     static {
86         try {
87             host = java.net.InetAddress.getLocalHost().getCanonicalHostName();
88             String JavaDoc policyLocation = System.getProperty("java.security.policy");
89             if(policyLocation != null) policy = getAbsolutePath(policyLocation);
90             else policy = DEFAULT_POLICY;
91             DEFAULT_RMID_PARAMS = DEFAULT_RMID_PARAMS.concat(policy);
92         } catch (java.net.UnknownHostException JavaDoc e) {
93             logger.fatal("Lookup failed: " + e.getMessage());
94             e.printStackTrace();
95             System.exit(1);
96         }
97     }
98
99     private static String JavaDoc grpName = "public";
100     private static final String JavaDoc tmpDir = createTempDirectory(host);
101     private static java.io.File JavaDoc jiniLockFile = null;
102     private static final String JavaDoc jiniLockFileLocation = System.getProperty(
103             "user.dir") + System.getProperty("file.separator") + host +
104         "jiniLockFile";
105
106     //
107
// -- Constructors -----------------------------------------------
108
//
109
public ServiceLocatorHelper() {
110         if (logger.isDebugEnabled()) {
111             logger.debug("ServiceLocatorHelper() constructor");
112         }
113     }
114
115     //
116
// -- PUBLIC METHODS -----------------------------------------------
117
//
118
public boolean shouldCreateServiceLocator() {
119         return shouldCreateServiceLocator;
120     }
121
122     public void setShouldCreateServiceLocator(boolean v) {
123         shouldCreateServiceLocator = v;
124     }
125
126     /**
127  * true if you want a multicast service Locator
128  * false if you want a unicast service Locator
129  */

130     public void setMulticastLocator(boolean v) {
131         ServiceLocatorHelper.multicastLocator = v;
132     }
133
134     /**
135  * Initialise the service locator for this host
136  */

137     public synchronized void initializeServiceLocator() {
138         if (!shouldCreateServiceLocator) {
139             return; // don't bother
140
}
141         if (locatorChecked) {
142             return; // already done for this VM
143
}
144         try {
145             getOrCreateServiceLocator();
146             //delete the lock file
147
if (jiniLockFile != null) {
148                 if (jiniLockFile.exists()) {
149                     jiniLockFile.delete();
150                 }
151             }
152         } catch (java.io.IOException JavaDoc e) {
153             if (jiniLockFile != null) {
154                 if (jiniLockFile.exists()) {
155                     jiniLockFile.delete();
156                 }
157             }
158             e.printStackTrace();
159             System.exit(1);
160         }
161         locatorChecked = true;
162     }
163
164     //
165
// -- implements DiscoveryListener -----------------------------------------------
166
//
167

168     /**
169  * for multicast discover
170  */

171     public void discovered(DiscoveryEvent evt) {
172         //if (logger.isDebugEnabled()) {
173
// //logger.debug(">> Start discover ...");
174
//}
175
ServiceRegistrar[] registrars = evt.getRegistrars();
176
177         // if (logger.isDebugEnabled()) {
178
// logger.debug(">> > " + registrars.length + " registrars : ");
179
// }
180
for (int n = 0; n < registrars.length; n++) {
181             ServiceLocatorHelper.registrar = registrars[n];
182             //displayServices(); // just for test
183
}
184
185         //if (logger.isDebugEnabled()) {
186
// //logger.debug(">> Stop discover...");
187
//}
188
}
189
190     /**
191  * for multicast discover
192  */

193     public void discarded(DiscoveryEvent evt) {
194         //if (logger.isDebugEnabled()) {
195
// //logger.debug(">> discarded ...");
196
//}
197
}
198
199     //
200
// -- PROTECTED METHODS -----------------------------------------------
201
//
202

203     /**
204  * Delete recursively all files and directory
205  *@param dir The directory to clean
206  */

207     protected static void delDirectory(java.io.File JavaDoc dir) {
208         java.io.File JavaDoc[] files = dir.listFiles();
209         if (files != null) {
210             for (int i = 0; i < files.length; i++) {
211                 delDirectory(files[i]);
212             }
213         }
214         logger.info("deleting " + dir.getPath() + " ...");
215         dir.delete();
216         if (dir.exists()) {
217             logger.warn("We cannot delete this file : " + dir.getPath());
218             logger.warn(
219                 "... You should delete it before running a new ServiceLocator ...");
220         }
221     }
222
223     //
224
// -- PRIVATE METHODS -----------------------------------------------
225
//
226

227     /**
228  * Display all services on this registrar
229  *@param registrar The registrar to contact
230  */

231     private void displayServices() {
232         try {
233             // the code takes separate routes from here for client or service
234
logger.info(">> found a service locator (registrar) : " +
235                 ServiceLocatorHelper.registrar);
236             logger.info(">> >> ServiceID : " +
237                 ServiceLocatorHelper.registrar.getServiceID());
238
239             logger.info(">> >> >> Groups : ");
240
241             String JavaDoc[] groups = ServiceLocatorHelper.registrar.getGroups();
242             for (int i = 0; i < groups.length; i++) {
243                 logger.info(">> >> >> >> " + i + ") " + groups[i]);
244             }
245
246             logger.info(">> >> >> Locator : " +
247                 ServiceLocatorHelper.registrar.getLocator());
248
249             ServiceTemplate template = new ServiceTemplate(null,
250                     new Class JavaDoc[] { JiniRuntime.class }, null);
251             ServiceMatches matches = ServiceLocatorHelper.registrar.lookup(template,
252                     Integer.MAX_VALUE);
253
254             logger.info(">> >> >> " + matches.items.length + " required ");
255             logger.info(">> >> >> " + matches.totalMatches + " founded ");
256
257             for (int i = 0; i < matches.items.length; i++) {
258                 logger.info(">> >> >> >> Object (" + i + ") found : ");
259                 logger.info(">> >> >> >> >> ID : " +
260                     matches.items[i].serviceID);
261                 logger.info(">> >> >> >> >> Service : " +
262                     matches.items[i].service);
263                 logger.info(">> >> >> >> >> Attributs :");
264
265                 for (int j = 0; j < matches.items[i].attributeSets.length;
266                         j++) {
267                     logger.info(">> >> >> >> >> >> Attr : " +
268                         matches.items[i].attributeSets[j]);
269                 }
270
271                 logger.info(
272                     "--------------------------------------------------------------------------------------");
273             }
274         } catch (java.rmi.RemoteException JavaDoc e) {
275             e.printStackTrace();
276         }
277     }
278
279     private static String JavaDoc createTempDirectory(String JavaDoc host) {
280         try {
281             java.io.File JavaDoc fTmp = java.io.File.createTempFile("proactive-",
282                     "-" + host);
283             String JavaDoc tmpDirPath = fTmp.getAbsolutePath();
284
285             //if (logger.isDebugEnabled()) {
286
// //logger.debug(">> TEMP directory = " + tmpDirPath);
287
//}
288
return tmpDirPath;
289         } catch (Exception JavaDoc e) {
290             logger.fatal("Cannot create the TEMP directory : " + e.toString());
291             e.printStackTrace();
292             System.exit(1);
293             return null;
294         }
295     }
296
297     /**
298  * Try to get the Service Locator on the local host (unicast search)
299  * Create it if it doesn't exist
300  */

301     private void getOrCreateServiceLocator() throws java.io.IOException JavaDoc {
302         if ((System.getSecurityManager() == null) &&
303                 !("false".equals(System.getProperty("proactive.securitymanager")))) {
304             System.setSecurityManager(new java.rmi.RMISecurityManager JavaDoc());
305         }
306         if (multicastLocator) {
307             // For multicast
308
LookupDiscovery discover = new LookupDiscovery(LookupDiscovery.ALL_GROUPS);
309             discover.addDiscoveryListener(this);
310             // stay around long enough to receive replies
311
try {
312                 Thread.sleep(MAX_WAIT);
313                 if (ServiceLocatorHelper.registrar == null) {
314                     createServiceLocator();
315                 }
316             } catch (InterruptedException JavaDoc e) {
317             }
318         } else {
319             // For unicast on `host`
320
logger.info("Lookup : jini://" + host);
321             try {
322                 lookup = new LookupLocator("jini://" + host);
323                 logger.info("Lookup.getRegistrar() on " + host);
324                 ServiceLocatorHelper.registrar = lookup.getRegistrar();
325             } catch (java.net.MalformedURLException JavaDoc e) {
326                 throw new java.io.IOException JavaDoc("Lookup failed: " +
327                     e.getMessage());
328             } catch (java.io.IOException JavaDoc e) {
329                 logger.error("Registrar search failed: " + e.getMessage());
330                 if (MAX_RETRY-- > 0) {
331                     //-----------wont work everywhere---------------------------
332
String JavaDoc[] env = new String JavaDoc[2];
333
334                     env[0] = DEFAULT_RMID_LOCATION;
335                     env[1] = DEFAULT_RMID_PARAMS;
336                     Runtime.getRuntime().exec(env);
337
338                     createServiceLocator();
339                     getOrCreateServiceLocator();
340                 } else {
341                     //delete the lock file
342
if (jiniLockFile.exists()) {
343                         jiniLockFile.delete();
344                     }
345                     throw new java.io.IOException JavaDoc(
346                         "\nCannot run a ServiceLocator : Have you launched the rmid deamon on " +
347                         host);
348                 }
349             } catch (java.lang.ClassNotFoundException JavaDoc e) {
350                 if (jiniLockFile.exists()) {
351                     jiniLockFile.delete();
352                 }
353                 throw new java.io.IOException JavaDoc("Registrar search failed: " +
354                     e.toString());
355             }
356
357             logger.info("Registrar found on " + host);
358
359             // Just for test
360
//displayServices();
361
}
362     }
363
364     /**
365  * Create a new Service Locator on the local host
366  */

367     private static void createServiceLocator() {
368         //this block is usefull to avoid many ServiceLocator to be created by different
369
//threads at the same time.If the file cannot be created, it is because another thread
370
//put a lock on it, in other word it is trying to create the serviceLocator
371
//so wait a bit for the service to be created
372
if (!createLockFile()) {
373             try {
374                 Thread.sleep(2000);
375             } catch (Exception JavaDoc e) {
376                 e.printStackTrace();
377             }
378             return;
379         }
380         logger.info("creating lock file");
381         logger.info(
382             "No ServiceLocator founded ... we launch a ServiceLocator on " +
383             host);
384         String JavaDoc reggieTmpDir = tmpDir + System.getProperty("file.separator") +
385             "reggie_log";
386         delDirectory(new java.io.File JavaDoc(tmpDir));
387         java.io.File JavaDoc directory = new java.io.File JavaDoc(tmpDir);
388         directory.mkdirs();
389
390         if (logger.isDebugEnabled()) {
391             //logger.debug("We use the ClassServer : "+httpserver);
392
logger.debug(
393                 "We don't use a ClassServer for the service Locator (we use the CLASSPATH)");
394         }
395
396         //String[] args = { httpserver , policy , reggieTmpDir,};
397
// String classpath = System.getProperty("java.class.path");
398
// try{
399
// java.io.File canonicalFile = new java.io.File(classpath);
400
// classpath = canonicalFile.getCanonicalPath();
401
// }catch (Exception e){
402
// e.printStackTrace();
403
//
404
// }
405
String JavaDoc[] args = { "", policy, reggieTmpDir, };
406         com.sun.jini.start.ServiceStarter.create(args,
407             "com.sun.jini.reggie.CreateLookup",
408             "com.sun.jini.reggie.RegistrarImpl", "lookup");
409     }
410
411     /**
412  * Method createLockFile.
413  * @param host
414  * @return String
415  */

416     private static boolean createLockFile() {
417         jiniLockFile = new java.io.File JavaDoc(jiniLockFileLocation);
418         //jiniLockFile.deleteOnExit();
419
try {
420             return jiniLockFile.createNewFile();
421         } catch (java.io.IOException JavaDoc e) {
422             //an exception occured try anyway to create the service locator
423
return true;
424         }
425     }
426     
427     private static String JavaDoc getAbsolutePath(String JavaDoc path) {
428             if (path.startsWith("file:")) {
429                 //remove file part to build absolute path
430
path = path.substring(5);
431             }
432             try {
433                 return new File JavaDoc(path).getCanonicalPath();
434             } catch (IOException JavaDoc e) {
435                 logger.error(e.getMessage());
436                 return path;
437             }
438         }
439 }
440
Popular Tags