KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > alt > config > Deploy


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "OpenEJB" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of The OpenEJB Group. For written permission,
18  * please contact info@openejb.org.
19  *
20  * 4. Products derived from this Software may not be called "OpenEJB"
21  * nor may "OpenEJB" appear in their names without prior written
22  * permission of The OpenEJB Group. OpenEJB is a registered
23  * trademark of The OpenEJB Group.
24  *
25  * 5. Due credit should be given to the OpenEJB Project
26  * (http://openejb.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE OPENEJB GROUP AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * THE OPENEJB GROUP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2001 (C) The OpenEJB Group. All Rights Reserved.
42  *
43  * $Id: Deploy.java 2230 2005-10-11 03:14:03Z jcscoobyrs $
44  */

45 package org.openejb.alt.config;
46
47 import java.io.DataInputStream JavaDoc;
48 import java.io.InputStream JavaDoc;
49 import java.io.PrintStream JavaDoc;
50 import java.io.File JavaDoc;
51 import java.lang.reflect.Method JavaDoc;
52 import java.net.URL JavaDoc;
53 import java.net.URLClassLoader JavaDoc;
54 import java.net.MalformedURLException JavaDoc;
55 import java.util.Properties JavaDoc;
56 import java.util.StringTokenizer JavaDoc;
57 import java.util.HashMap JavaDoc;
58
59 import org.openejb.OpenEJBException;
60 import org.openejb.loader.SystemInstance;
61 import org.openejb.alt.config.ejb11.EjbDeployment;
62 import org.openejb.alt.config.ejb11.EjbJar;
63 import org.openejb.alt.config.ejb11.MethodParams;
64 import org.openejb.alt.config.ejb11.OpenejbJar;
65 import org.openejb.alt.config.ejb11.QueryMethod;
66 import org.openejb.alt.config.ejb11.ResourceLink;
67 import org.openejb.alt.config.ejb11.ResourceRef;
68 import org.openejb.alt.config.sys.Connector;
69 import org.openejb.alt.config.sys.Container;
70 import org.openejb.alt.config.sys.Openejb;
71 import org.openejb.util.JarUtils;
72 import org.openejb.util.Messages;
73 import org.openejb.util.SafeToolkit;
74 import org.openejb.util.Logger;
75 import org.openejb.util.FileUtils;
76
77 /**
78  * This class represents a command line tool for deploying beans.
79  *
80  * At the moment it contains multiple println statements
81  * and statements that read input from the user.
82  *
83  * These statements are really in chunks in specific times throughout
84  * the class. These chunks could be refactored into methods. Then
85  * the implementation of those methods could actually be delegated
86  * to another class that implements a specific interface we create.
87  *
88  * The command line statements could be moved into an implementation
89  * of this new interface. We could then create another implementation
90  * that gathers information from a GUI.
91  *
92  * This would give us a Deploy API rather than just a command line
93  * tool. Then beans could be deployed programmatically by another
94  * application, by a GUI screen, or by command line.
95  *
96  * Note: The command line version should be finished first!!! We
97  * don't want to start on a crusade of abstracting code that doesn't
98  * yet exist. Functionality first, neat flexible stuff later.
99  *
100  * @author <a HREF="mailto:david.blevins@visi.com">David Blevins</a>
101  */

102 public class Deploy {
103     private static final String JavaDoc helpBase = "META-INF/org.openejb.cli/";
104
105     protected static final Messages _messages = new Messages("org.openejb.alt.util.resources");
106
107     private static final String JavaDoc DEPLOYMENT_ID_HELP =
108     "\nDeployment ID ----- \n\nA name for the ejb that is unique not only in this jar, but \nin all the jars in the container system. This name will \nallow OpenEJB to place the bean in a global index and \nreference the bean quickly. OpenEJB will also use this name \nas the global JNDI name for the Remote Server and the Local \nServer. Clients of the Remote or Local servers can use this\nname to perform JNDI lookups.\n\nThe other EJB Server's using OpenEJB as the EJB Container \nSystem may also use this name to as part of a global JNDI \nnamespace available to remote application clients.\n\nExample: /my/acme/bugsBunnyBean\n\nSee http://www.openejb.org/deploymentids.html for details.\n";
109     private static final String JavaDoc CONTAINER_ID_HELP =
110     "\nContainer ID ----- \n\nThe name of the container where this ejb should run. \nContainers are declared and configured in the openejb.conf\nfile.\n";
111     private static final String JavaDoc CONNECTOR_ID_HELP =
112     "\nConnector ID ----- \n\nThe name of the connector or JDBC resource this resoure \nreference should be mapped to. Connectors and JDBC resources \nare declared and configured in the openejb.conf file.\n";
113
114     /*=======----------TODO----------=======
115       Neat options that this Deploy tool
116       could support
117
118       Contributions and ideas welcome!!!
119      =======----------TODO----------=======*/

120
121     /**
122      * Idea for a command line option
123      *
124      * If there is only one container of the appropriate type
125      * for a bean then the bean is automatically assigned to that
126      * container. The user is notified unless the QUIET flag is true.
127      *
128      * not implemented
129      */

130     private boolean AUTO_ASSIGN;
131
132     /**
133      * Idea for a command line option
134      *
135      * -m Move the jar to the OPENEJB_HOME/beans directory
136      *
137      * not implemented
138      */

139     private boolean MOVE_JAR;
140
141     /**
142      * Idea for a command line option
143      *
144      * -f Force an overwrite if the jar already exists
145      *
146      * not implemented
147      */

148     private boolean FORCE_OVERWRITE_JAR;
149
150     /**
151      * Idea for a command line option
152      *
153      * -c Copy the jar to the OPENEJB_HOME/beans directory
154      *
155      * not implemented
156      */

157     private boolean COPY_JAR;
158
159     /**
160      * Idea for a command line option
161      *
162      * Will automatically create an OpenEJB configuration
163      * file that can accomodate the beans in the jar.
164      *
165      * If there already is a config file, but, for example, there
166      * is not a container that is compatable for a bean type in the
167      * jar, then a useable container of the right type will be
168      * automatically created with default values.
169      *
170      * not implemented
171      */

172     private boolean AUTO_CONFIG;
173
174     /**
175      * Idea for a command line option
176      *
177      * Will generate the bean's deployment id from a particular id generation
178      * strategy.
179      *
180      * -g[S#]
181      *
182      * S# can be a number key to a generation strategy that is
183      * looked up internally.
184      *
185      * ----------------------------
186      * One strategy could be:
187      * id = jar_directory + ejb-name
188      * example:
189      * DIR path/to/a/jarfile/myBeans.jar
190      * BEAN CustomerBean
191      * ID path/to/a/jarfile/CustomerBean
192      *
193      * ----------------------------
194      * Another strategy:
195      * Just use the ejb-name
196      * DIR doesnt/matter/path/to/a/jarfile/myBeans.jar
197      * BEAN CustomerBean
198      * ID CustomerBean
199      *
200      * If ejb-name already looked like a JNDI name
201      * then this would work great, otherwise there
202      * would be a high chance of name collitions in
203      * the OpenEJB IntraVM global namespace.
204      * ----------------------------
205      *
206      * not implemented
207      */

208     private boolean GENERATE_DEPLOYMENT_ID;
209
210     /**
211      * Idea for a command line option
212      *
213      * Generate the CORBA stubs and ties
214      * and add them to the jar so people don't
215      * have to run a seperate tool to do that.
216      *
217      * not implemented
218      */

219     private boolean GENERATE_STUBS;
220
221     private DataInputStream JavaDoc in;
222     private PrintStream JavaDoc out;
223     private Openejb config;
224     private String JavaDoc configFile;
225     private boolean configChanged;
226     private boolean autoAssign;
227     private Container[] containers;
228     private Connector[] resources;
229     private ClassLoader JavaDoc classLoader;
230     private String JavaDoc jarLocation;
231
232     /*------------------------------------------------------*/
233     /* Constructors */
234     /*------------------------------------------------------*/
235     public Deploy() throws OpenEJBException {}
236
237     public void init(String JavaDoc openejbConfigFile) throws OpenEJBException {
238         try {
239             // Initialize loggers
240
Logger.initialize( System.getProperties() );
241
242             if (System.getProperty("openejb.nobanner") == null) {
243                 printVersion();
244                 System.out.println("");
245             }
246
247             in = new DataInputStream JavaDoc(System.in);
248             out = System.out;
249
250             configFile = openejbConfigFile;
251             if (configFile == null) {
252                 try {
253                     configFile = System.getProperty("openejb.configuration");
254                 } catch (Exception JavaDoc e) {
255                 }
256             }
257             if (configFile == null) {
258                 configFile = ConfigUtils.searchForConfiguration();
259             }
260             config = ConfigUtils.readConfig(configFile);
261
262             /* Load container list */
263             containers = config.getContainer();
264
265             /* Load resource list */
266             resources = config.getConnector();
267
268         } catch (Exception JavaDoc e) {
269             // TODO: Better exception handling.
270
e.printStackTrace();
271             throw new OpenEJBException(e.getMessage());
272         }
273
274     }
275
276     /*------------------------------------------------------*/
277     /* Methods for starting the deployment process */
278     /*------------------------------------------------------*/
279
280     private void deploy(String JavaDoc jarLocation) throws OpenEJBException {
281
282         this.jarLocation = jarLocation;
283         EjbJarUtils ejbJarUtils = new EjbJarUtils(jarLocation);
284
285         EjbValidator validator = new EjbValidator();
286
287         classLoader = null;
288         try {
289             File JavaDoc jarFile = new File JavaDoc(ejbJarUtils.getJarLocation());
290             URL JavaDoc[] classpath = new URL JavaDoc[]{jarFile.toURL()};
291             classLoader = new URLClassLoader JavaDoc(classpath, this.getClass().getClassLoader());
292         } catch (MalformedURLException JavaDoc e) {
293             throw new OpenEJBException("Unable to create a classloader to load classes from '"+jarLocation+"'", e);
294         }
295
296         EjbSet set = validator.validateJar(ejbJarUtils, classLoader);
297
298         if (set.hasErrors() || set.hasFailures()) {
299             validator.printResults(set);
300             System.out.println();
301             System.out.println("Jar not deployable.");
302             System.out.println();
303             System.out.println("Use the validator with -vvv option for more details." );
304             System.out.println("See http://www.openejb.org/validate.html for usage." );
305             return;
306         }
307
308         OpenejbJar openejbJar = new OpenejbJar();
309
310         Bean[] beans = ejbJarUtils.getBeans();
311
312         listBeanNames(beans);
313
314         for (int i = 0; i < beans.length; i++) {
315             openejbJar.addEjbDeployment(deployBean(beans[i], jarLocation));
316         }
317
318         if (MOVE_JAR) {
319             jarLocation = moveJar(jarLocation);
320         } else if (COPY_JAR) {
321             jarLocation = copyJar(jarLocation);
322         }
323
324         /* TODO: Automatically updating the users
325         config file might not be desireable for
326         some people. We could make this a
327         configurable option.
328         */

329         addDeploymentEntryToConfig(jarLocation);
330
331         saveChanges(jarLocation, openejbJar);
332
333     }
334
335     private EjbDeployment deployBean(Bean bean, String JavaDoc jarLocation) throws OpenEJBException {
336         EjbDeployment deployment = new EjbDeployment();
337
338         out.println("\n-----------------------------------------------------------");
339         out.println("Deploying bean: " + bean.getEjbName());
340         out.println("-----------------------------------------------------------");
341         deployment.setEjbName(bean.getEjbName());
342
343         if (GENERATE_DEPLOYMENT_ID) {
344             deployment.setDeploymentId(autoAssignDeploymentId(bean));
345         } else {
346             deployment.setDeploymentId(promptForDeploymentId());
347         }
348
349         if (AUTO_ASSIGN) {
350             deployment.setContainerId(autoAssignContainerId(bean));
351         } else {
352             deployment.setContainerId(promptForContainerId(bean));
353         }
354
355         ResourceRef[] refs = bean.getResourceRef();
356         if (refs.length > 0) {
357             out.println("\n==--- Step 3 ---==");
358             out.println("\nThis bean contains the following references to external \nresources:");
359
360             out.println("\nName\t\t\tType\n");
361
362             for (int i = 0; i < refs.length; i++) {
363                 out.print(refs[i].getResRefName() + "\t");
364                 out.println(refs[i].getResType());
365             }
366
367             out.println(
368                        "\nThese references must be linked to the available resources\ndeclared in your config file.");
369
370             out.println("Available resources are:");
371             listResources(resources);
372             for (int i = 0; i < refs.length; i++) {
373                 deployment.addResourceLink(resolveResourceRef(refs[i]));
374             }
375         }
376
377         //check for OQL statement
378
if (bean.getType().equals("CMP_ENTITY")){
379             if (bean.getHome() != null){
380                 Class JavaDoc tempBean = loadClass(bean.getHome());
381                 if (hasFinderMethods(tempBean)){
382                     promptForOQLForEntityBeans(tempBean, deployment);
383                 }
384             }
385             if (bean.getLocalHome() != null){
386                 Class JavaDoc tempBean = loadClass(bean.getLocalHome());
387                 if (hasFinderMethods(tempBean)){
388                     promptForOQLForEntityBeans(tempBean, deployment);
389                 }
390             }
391         }
392
393         return deployment;
394     }
395
396     private Class JavaDoc loadClass(String JavaDoc className) throws OpenEJBException {
397         try {
398             return classLoader.loadClass(className);
399         } catch (ClassNotFoundException JavaDoc cnfe) {
400             throw new OpenEJBException(SafeToolkit.messages.format("cl0007", className, this.jarLocation));
401         }
402     }
403
404     private boolean hasFinderMethods(Class JavaDoc bean)
405     throws OpenEJBException {
406
407         Method JavaDoc[] methods = bean.getMethods();
408
409         for (int i = 0; i < methods.length; i++) {
410             if (methods[i].getName().startsWith("find")
411                 && !methods[i].getName().equals("findByPrimaryKey")) {
412                 return true;
413             }
414         }
415         return false;
416     }
417
418     private void promptForOQLForEntityBeans(Class JavaDoc bean, EjbDeployment deployment)
419     throws OpenEJBException {
420         org.openejb.alt.config.ejb11.Query query;
421         QueryMethod queryMethod;
422         MethodParams methodParams;
423         boolean instructionsPrinted = false;
424
425         Method JavaDoc[] methods = bean.getMethods();
426         Class JavaDoc[] parameterList;
427         Class JavaDoc[] exceptionList;
428         String JavaDoc answer = null;
429         String JavaDoc parameters;
430
431         StringTokenizer JavaDoc parameterTokens;
432
433         for (int i = 0; i < methods.length; i++) {
434             if (methods[i].getName().startsWith("find")
435                 && !methods[i].getName().equals("findByPrimaryKey")) {
436
437                 if (!instructionsPrinted) {
438                     out.println("\n==--- Step 4 ---==");
439                     out.println(
440                                "\nThis part of the application allows you to add OQL (Object\n"
441                         + "Query Language) statements to your CMP Entity find methods.\n"
442                         + "Below is a list of find methods, each of which should get an \n"
443                         + "OQL statement.\n"
444                         + "\n"
445                         + "OQL statements are very similar to SQL statments with the \n"
446                         + "exception that they reference class names rather than table\n"
447                         + "names. Find method parameters can be referenced in OQL \n"
448                         + "statements as $1, $2, $3, and so on. \n"
449                         + "\n"
450                         + "If you had a find method in your home interface like this one:\n"
451                         + "\n"
452                         + " public Employee findByLastName( String lName )\n"
453                         + "\n"
454                         + "Then you could use an OQL method like the following:\n"
455                         + "\n"
456                         + " SELECT o FROM org.acme.employee.EmployeeBean o WHERE o.lastname = $1\n"
457                         + "\n"
458                         + "In this example, the $1 is referring to the first parameter, \n"
459                         + "which is the String lName.\n"
460                         + "\n"
461                         + "For more information on OQL see:\n"
462                         + "http://www.openejb.org/cmp_guide.html\n"
463                         );
464
465                     instructionsPrinted = true;
466                 }
467
468                 out.print("Method: ");
469                 parameterList = methods[i].getParameterTypes();
470
471                 // and it's parameters
472
out.print(methods[i].getName() + "(");
473                 for (int j = 0; j < parameterList.length; j++) {
474                     out.print(parsePartialClassName(parameterList[j].getName()));
475                     if (j != (parameterList.length - 1)) {
476                         out.print(", ");
477                     }
478                 }
479                 out.println(") ");
480
481                 try {
482                     boolean replied = false;
483
484                     while (!replied) {
485                         out.println("Please enter your OQL Statement here.");
486                         out.print("\nOQL Statement: ");
487                         answer = in.readLine();
488                         if (answer.length() > 0) {
489                             replied = true;
490                         }
491                     }
492
493                 } catch (Exception JavaDoc e) {
494                     throw new OpenEJBException(e.getMessage());
495                 }
496
497                 //create a new query and add it to the deployment
498
if (answer != null && !answer.equals("")) {
499                     query = new org.openejb.alt.config.ejb11.Query();
500                     methodParams = new MethodParams();
501                     queryMethod = new QueryMethod();
502
503                     //loop through the list of parameters
504
for (int j=0; j < parameterList.length; j++){
505                         methodParams.addMethodParam(parameterList[j].getName());
506                     }
507
508                     queryMethod.setMethodParams(methodParams);
509                     queryMethod.setMethodName(methods[i].getName());
510                     query.setQueryMethod(queryMethod);
511                     query.setObjectQl(answer);
512
513                     deployment.addQuery(query);
514
515                     out.println("\nYour OQL statement was successfully added to the jar.\n");
516                 }
517             }
518         }
519     }
520
521     private String JavaDoc parsePartialClassName(String JavaDoc className) {
522         if ( className.indexOf('.') < 1 ) return className;
523         return className.substring( className.lastIndexOf('.')+1 );
524     }
525
526     /*------------------------------------------------------*/
527     /* Methods for deployment id mapping */
528     /*------------------------------------------------------*/
529     private void listBeanNames(Bean[] beans) {
530         out.println("This jar contains the following beans:");
531         for (int i = 0; i < beans.length; i++) {
532             out.println(" " + beans[i].getEjbName());
533         }
534         out.println();
535     }
536
537     private String JavaDoc promptForDeploymentId() throws OpenEJBException {
538         String JavaDoc answer = null;
539         try {
540             boolean replied = false;
541             out.println("\n==--- Step 1 ---==");
542             out.println("\nPlease specify a deployment id for this bean.");
543
544             while (!replied) {
545                 out.println("Type the id or -help for more information.");
546                 out.print("\nDeployment ID: ");
547                 answer = in.readLine();
548                 if ("-help".equals(answer)) {
549                     out.println(DEPLOYMENT_ID_HELP);
550                 } else if (answer.length() > 0) {
551                     replied = true;
552                 }
553             }
554         } catch (Exception JavaDoc e) {
555             throw new OpenEJBException(e.getMessage());
556         }
557         return answer;
558     }
559
560     private String JavaDoc autoAssignDeploymentId(Bean bean) throws OpenEJBException {
561         String JavaDoc answer = bean.getEjbName();
562         out.println("\n==--- Step 1 ---==");
563         out.println("\nAuto assigning the ejb-name as the deployment id for this bean.");
564         out.print("\nDeployment ID: " + answer);
565
566         return answer;
567     }
568
569     /*------------------------------------------------------*/
570     /* Methods for container mapping */
571     /*------------------------------------------------------*/
572
573     private String JavaDoc promptForContainerId(Bean bean) throws OpenEJBException {
574         String JavaDoc answer = null;
575         boolean replied = false;
576         out.println("\n==--- Step 2 ---==");
577         out.println("\nPlease specify which container the bean will run in.");
578         out.println("Available containers are:");
579
580         Container[] cs = getUsableContainers(bean);
581
582         if (cs.length == 0) {
583             /* TODO: Allow or Automatically create a useable container
584              * Stopping the deployment process because there is no
585              * container of the right bean type is a terrible way
586              * deal with the problem. Instead, we should either
587              * 1) Automatically create a container for them and notify them
588              * that we have done so.
589              * 2) Allow them to create their own container.
590              * 3) Some combination of 1 and 2.
591              */

592             out.println(
593                        "!! There are no "
594                        + bean.getType()
595                        + " containers declared in "
596                        + configFile
597                        + " !!");
598             out.println(
599                        "A "
600                        + bean.getType()
601                        + " container must be declared and \nconfigured in your configuration file before this jar can\nbe deployed.");
602             System.exit(-1);
603         } else if (cs.length == 0) {
604             /* TODO: Automatically assign the bean to the container
605              * Since this is the only container in the system that
606              * can service this bean type, either
607              * 1) simply assign the bean to that container and notify the user.
608              * 2) allow the user to create another container.
609              */

610         }
611
612         listContainers(cs);
613         int choice = 0;
614         try {
615
616             while (!replied) {
617                 out.println(
618                            "\nType the number of the container\n-options to view the list again\nor -help for more information.");
619                 out.print("\nContainer: ");
620                 answer = in.readLine();
621                 if ("-help".equals(answer)) {
622                     out.println(CONTAINER_ID_HELP);
623                 } else if ("-options".equals(answer)) {
624                     listContainers(cs);
625                 } else if (answer.length() > 0) {
626                     try {
627                         choice = Integer.parseInt(answer);
628                     } catch (NumberFormatException JavaDoc nfe) {
629                         out.println("\'" + answer + "\' is not a numer.");
630                         continue;
631                     }
632                     if (choice > cs.length || choice < 1) {
633                         out.println(choice + " is not an option.");
634                         continue;
635                     }
636                     replied = true;
637                 }
638             }
639         } catch (Exception JavaDoc e) {
640             throw new OpenEJBException(e.getMessage());
641         }
642         return cs[choice - 1].getId();
643     }
644
645     private String JavaDoc autoAssignContainerId(Bean bean) throws OpenEJBException {
646         String JavaDoc answer = null;
647         boolean replied = false;
648         out.println("\n==--- Step 2 ---==");
649         out.println("\nAuto assigning the container the bean will run in.");
650
651         Container[] cs = getUsableContainers(bean);
652
653         if (cs.length == 0) {
654             /* TODO: Allow or Automatically create a useable container
655              * Stopping the deployment process because there is no
656              * container of the right bean type is a terrible way
657              * deal with the problem. Instead, we should either
658              * 1) Automatically create a container for them and notify them
659              * that we have done so.
660              * 2) Allow them to create their own container.
661              * 3) Some combination of 1 and 2.
662              */

663             out.println(
664                        "!! There are no "
665                        + bean.getType()
666                        + " containers declared in "
667                        + configFile
668                        + " !!");
669             out.println(
670                        "A "
671                        + bean.getType()
672                        + " container must be declared and \nconfigured in your configuration file before this jar can\nbe deployed.");
673             System.exit(-1);
674         }
675
676         out.println("\nContainer: " + cs[0].getId());
677         return cs[0].getId();
678     }
679
680     private void listContainers(Container[] containers) {
681         out.println("\nNum \tType \tID\n");
682
683         for (int i = 0; i < containers.length; i++) {
684             out.print((i + 1) + "\t");
685             out.print(containers[i].getCtype() + "\t");
686             out.println(containers[i].getId());
687         }
688     }
689
690     /*------------------------------------------------------*/
691     /* Methods for connection(resource) mapping */
692     /*------------------------------------------------------*/
693     private ResourceLink resolveResourceRef(ResourceRef ref) throws OpenEJBException {
694         String JavaDoc answer = null;
695         boolean replied = false;
696
697         out.println("\nPlease link reference: " + ref.getResRefName());
698
699         if (resources.length == 0) {
700             /* TODO: 1, 2 or 3
701              * 1) Automatically create a connector and link the reference to it.
702              * 2) Something more creative
703              * 3) Some ultra flexible combination of 1 and 2.
704              */

705             out.println("!! There are no resources declared in " + configFile + " !!");
706             out.println(
707                        "A resource connector must be declared and configured in \nyour configuration file before this jar can be deployed.");
708             System.exit(-2);
709         } else if (resources.length == 0) {
710             /* TODO: 1, 2 or 3
711              * 1) Automatically link the reference to the connector
712              * 2) Something more creative
713              * 3) Some ultra flexible combination of 1 and 2.
714              */

715         }
716
717         int choice = 0;
718         try {
719             while (!replied) {
720                 out.println(
721                            "\nType the number of the resource to link the bean's \nreference to, -options to view the list again, or -help\nfor more information.");
722                 out.print("\nResource: ");
723                 answer = in.readLine();
724                 if ("-help".equals(answer)) {
725                     out.println(CONNECTOR_ID_HELP);
726                 } else if ("-options".equals(answer)) {
727                     listResources(resources);
728                 } else if (answer.length() > 0) {
729                     try {
730                         choice = Integer.parseInt(answer);
731                     } catch (NumberFormatException JavaDoc nfe) {
732                         out.println("\'" + answer + "\' is not a number.");
733                         continue;
734                     }
735                     if (choice > resources.length || choice < 1) {
736                         out.println(choice + " is not an option.");
737                         continue;
738                     }
739                     replied = true;
740                 }
741             }
742         } catch (Exception JavaDoc e) {
743             throw new OpenEJBException(e.getMessage());
744         }
745
746         ResourceLink link = new ResourceLink();
747         link.setResRefName(ref.getResRefName());
748         link.setResId(resources[choice - 1].getId());
749         return link;
750     }
751
752     private void listResources(Connector[] connectors) {
753         out.println("\nNum \tID\n");
754
755         for (int i = 0; i < connectors.length; i++) {
756             out.print((i + 1) + "\t");
757             out.println(connectors[i].getId());
758         }
759     }
760
761     private void saveChanges(String JavaDoc jarFile, OpenejbJar openejbJar) throws OpenEJBException {
762         out.println("\n-----------------------------------------------------------");
763         out.println("Done collecting deployment information!");
764
765         out.print("Creating the openejb-jar.xml file...");
766         EjbJarUtils.writeOpenejbJar("META-INF/openejb-jar.xml", openejbJar);
767
768         out.println("done");
769
770         out.print("Writing openejb-jar.xml to the jar...");
771         JarUtils.addFileToJar(jarFile, "META-INF/openejb-jar.xml");
772
773         out.println("done");
774
775         if (configChanged) {
776             out.print("Updating your system config...");
777             ConfigUtils.writeConfig(configFile, config);
778
779             out.println("done");
780         }
781
782         out.println("\nCongratulations! Your jar is ready to use with OpenEJB.");
783         out.println(
784                    "\nIf the OpenEJB remote server is already running, you will\nneed to restart it in order for OpenEJB to recognize your bean.");
785         out.println(
786                    "\nNOTE: If you move or rename your jar file, you will have to\nupdate the path in this jar's deployment entry in your \nOpenEJB config file.");
787
788     }
789
790     /*------------------------------------------------------*/
791     /* Methods for exception handling */
792     /*------------------------------------------------------*/
793     private void logException(String JavaDoc m) throws OpenEJBException {
794         System.out.println("[OpenEJB] " + m);
795         throw new OpenEJBException(m);
796     }
797
798     private void logException(String JavaDoc m, Exception JavaDoc e) throws OpenEJBException {
799         m += " : " + e.getMessage();
800         System.out.println("[OpenEJB] " + m);
801         //e.printStackTrace();
802
throw new OpenEJBException(m);
803     }
804
805     /*------------------------------------------------------*/
806     /* Static methods */
807     /*------------------------------------------------------*/
808
809     private static final String JavaDoc ERROR_NO_EJBJARFILES_SPECIFIED = "No EJB JARFILES specified";
810     private static final String JavaDoc INCORRECT_OPTION = "Incorrect option: ";
811
812     public static void main(String JavaDoc args[]) {
813         try {
814             File JavaDoc directory = SystemInstance.get().getHome().getDirectory("lib");
815             SystemInstance.get().getClassPath().addJarsToPath(directory);
816             File JavaDoc directory1 = SystemInstance.get().getHome().getDirectory("dist");
817             SystemInstance.get().getClassPath().addJarsToPath(directory1);
818         } catch (Exception JavaDoc e) {
819             e.printStackTrace();
820         }
821         try {
822             Deploy d = new Deploy();
823
824             if (args.length == 0) {
825                 error(ERROR_NO_EJBJARFILES_SPECIFIED);
826                 printHelp();
827                 return;
828             }
829
830             boolean noBeansToDeploySpecified = true;
831             for (int i = 0; i < args.length; i++) {
832                 //AUTODEPLOY
833
if (args[i].equals("-a")) {
834                     d.AUTO_ASSIGN = true;
835                     d.GENERATE_DEPLOYMENT_ID = true;
836                 } else if (args[i].equals("-m")) {
837                     d.MOVE_JAR = true;
838                 } else if (args[i].equals("-f")) {
839                     d.FORCE_OVERWRITE_JAR = true;
840                 } else if (args[i].equals("-c")) {
841                     d.COPY_JAR = true;
842                 } else if (args[i].equals("-C")) {
843                     d.AUTO_ASSIGN = true;
844                 } else if (args[i].equals("-D")) {
845                     d.GENERATE_DEPLOYMENT_ID = true;
846                 } else if (args[i].equals("-conf")) {
847                     if (args.length > i + 1) {
848                         System.setProperty("openejb.configuration", args[++i]);
849                     }
850                 } else if (args[i].equals("-l")) {
851                     if (args.length > i + 1) {
852                         System.setProperty("log4j.configuration", args[++i]);
853                     }
854                 } else if (args[i].equals("-d")) {
855                     if (args.length > i + 1) {
856                         System.setProperty("openejb.home", args[++i]);
857                     }
858                 } else if (args[i].equals("-examples")) {
859                     printExamples();
860                 } else if (args[i].equals("-version")) {
861                     printVersion();
862                 } else if (args[i].equals("--help")) {
863                     printHelp();
864                 } else if (args[i].startsWith("-")) {
865                     error(INCORRECT_OPTION + args[i]);
866                     printHelp();
867                 } else {
868                     // We must have reached the jar list
869
noBeansToDeploySpecified = false;
870                     d.init(null);
871                     for (; i < args.length; i++) {
872                         try {
873                             d.deploy(args[i]);
874                         } catch (Exception JavaDoc e) {
875                             System.out.print("\nERROR in ");
876                             System.out.println(args[i]);
877                             System.out.println(e.getMessage());
878                         }
879                     }
880                 }
881             }
882             if (noBeansToDeploySpecified) {
883                 error(ERROR_NO_EJBJARFILES_SPECIFIED);
884                 printHelp();
885                 return;
886             }
887         } catch (Exception JavaDoc e) {
888             System.out.println(e.getMessage());
889             //e.printStackTrace();
890
}
891     }
892
893     private static void printVersion() {
894         /*
895          * Output startup message
896          */

897         Properties JavaDoc versionInfo = new Properties JavaDoc();
898
899         try {
900             JarUtils.setHandlerSystemProperty();
901             versionInfo.load(
902                             new URL JavaDoc("resource:/openejb-version.properties").openConnection().getInputStream());
903         } catch (java.io.IOException JavaDoc e) {
904         }
905
906         System.out.println(
907                           "OpenEJB Deploy Tool "
908                           + versionInfo.get("version")
909                           + " build: "
910                           + versionInfo.get("date")
911                           + "-"
912                           + versionInfo.get("time"));
913         System.out.println("" + versionInfo.get("url"));
914     }
915
916     private static void printHelp() {
917         String JavaDoc header = "OpenEJB Deploy Tool ";
918         try {
919             JarUtils.setHandlerSystemProperty();
920             Properties JavaDoc versionInfo = new Properties JavaDoc();
921             versionInfo.load(
922                             new URL JavaDoc("resource:/openejb-version.properties").openConnection().getInputStream());
923             header += versionInfo.get("version");
924         } catch (java.io.IOException JavaDoc e) {
925         }
926
927         System.out.println(header);
928
929         // Internationalize this
930
try {
931             InputStream JavaDoc in = Thread.currentThread().getContextClassLoader().getResource(helpBase + "deploy.help").openConnection().getInputStream();
932
933             int b = in.read();
934             while (b != -1) {
935                 System.out.write(b);
936                 b = in.read();
937             }
938         } catch (java.io.IOException JavaDoc e) {
939         }
940     }
941
942     private static void printExamples() {
943         String JavaDoc header = "OpenEJB Deploy Tool ";
944         try {
945             JarUtils.setHandlerSystemProperty();
946             Properties JavaDoc versionInfo = new Properties JavaDoc();
947             versionInfo.load(
948                             new URL JavaDoc("resource:/openejb-version.properties").openConnection().getInputStream());
949             header += versionInfo.get("version");
950         } catch (java.io.IOException JavaDoc e) {
951         }
952
953         System.out.println(header);
954
955         // Internationalize this
956
try {
957             InputStream JavaDoc in = Thread.currentThread().getContextClassLoader().getResource(helpBase + "deploy.examples").openConnection().getInputStream();
958
959             int b = in.read();
960             while (b != -1) {
961                 System.out.write(b);
962                 b = in.read();
963             }
964         } catch (java.io.IOException JavaDoc e) {
965         }
966     }
967
968     // Print error message to stderr
969
private static void error(String JavaDoc msg) {
970         System.err.println("\nERROR: " + msg + "\n");
971     }
972
973     private String JavaDoc moveJar(String JavaDoc jar) throws OpenEJBException {
974         return EjbJarUtils.moveJar(jar, FORCE_OVERWRITE_JAR);
975     }
976
977     private String JavaDoc copyJar(String JavaDoc jar) throws OpenEJBException {
978         return EjbJarUtils.copyJar(jar, FORCE_OVERWRITE_JAR);
979     }
980
981     private Container[] getUsableContainers(Bean bean) {
982         return EjbJarUtils.getUsableContainers(containers, bean);
983     }
984
985     private void addDeploymentEntryToConfig(String JavaDoc jarLocation) {
986         configChanged = ConfigUtils.addDeploymentEntryToConfig(jarLocation, config);
987     }
988 }
Popular Tags