KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > portal > pluto > Deploy


1 /*
2  * Copyright 2003,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.portal.pluto;
17
18 import java.io.File JavaDoc;
19 import java.io.FileOutputStream JavaDoc;
20 import java.io.FileReader JavaDoc;
21 import java.io.FileWriter JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.util.Collection JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.Locale JavaDoc;
28 import java.util.Vector JavaDoc;
29 import java.util.jar.JarEntry JavaDoc;
30 import java.util.jar.JarFile JavaDoc;
31
32 import org.apache.cocoon.portal.pluto.factory.ControllerFactoryImpl;
33 import org.apache.cocoon.portal.pluto.om.PortletApplicationDefinitionImpl;
34 import org.apache.cocoon.portal.pluto.om.PortletDefinitionRegistryImpl;
35 import org.apache.cocoon.portal.pluto.om.ServletDefinitionImpl;
36 import org.apache.cocoon.portal.pluto.om.ServletMapping;
37 import org.apache.cocoon.portal.pluto.om.WebApplicationDefinitionImpl;
38 import org.apache.cocoon.portal.pluto.om.common.DescriptionImpl;
39 import org.apache.cocoon.portal.pluto.om.common.DescriptionSetImpl;
40 import org.apache.cocoon.portal.pluto.om.common.DisplayNameImpl;
41 import org.apache.cocoon.portal.pluto.om.common.DisplayNameSetImpl;
42 import org.apache.cocoon.portal.pluto.om.common.TagDefinition;
43 import org.apache.commons.cli.CommandLine;
44 import org.apache.commons.cli.CommandLineParser;
45 import org.apache.commons.cli.HelpFormatter;
46 import org.apache.commons.cli.Option;
47 import org.apache.commons.cli.Options;
48 import org.apache.commons.cli.ParseException;
49 import org.apache.commons.cli.PosixParser;
50 import org.apache.commons.lang.SystemUtils;
51 import org.apache.pluto.om.ControllerFactory;
52 import org.apache.pluto.om.common.Parameter;
53 import org.apache.pluto.om.common.ParameterCtrl;
54 import org.apache.pluto.om.common.ParameterSet;
55 import org.apache.pluto.om.common.ParameterSetCtrl;
56 import org.apache.pluto.om.common.SecurityRoleRef;
57 import org.apache.pluto.om.common.SecurityRoleRefSet;
58 import org.apache.pluto.om.common.SecurityRoleRefSetCtrl;
59 import org.apache.pluto.om.common.SecurityRoleSet;
60 import org.apache.pluto.om.portlet.PortletDefinition;
61 import org.apache.pluto.om.servlet.ServletDefinition;
62 import org.apache.pluto.om.servlet.ServletDefinitionCtrl;
63 import org.apache.pluto.om.servlet.ServletDefinitionListCtrl;
64 import org.apache.xml.serialize.OutputFormat;
65 import org.apache.xml.serialize.XMLSerializer;
66 import org.exolab.castor.mapping.Mapping;
67 import org.exolab.castor.xml.Marshaller;
68 import org.exolab.castor.xml.Unmarshaller;
69 import org.xml.sax.InputSource JavaDoc;
70
71 /**
72  * First version of a simple portlet deploy tool for the Cocoon Portal.
73  * It works very similar to the deploy tool of the Pluto project (most
74  * code is taken and improved from the Pluto tool!).
75  * The only difference is that this deploy tool does not copy the taglib
76  * definition for the portlet tags, so you have to have these in your
77  * portlet war already!
78  *
79  * @author <a HREF="mailto:cziegeler@apache.org">Carsten Ziegeler</a>
80  *
81  * @version CVS $Id: Deploy.java 30941 2004-07-29 19:56:58Z vgritsenko $
82  */

83 public class Deploy {
84
85     //attributes for the web.xml creation for portlets
86
public final static String JavaDoc WEB_PORTLET_PUBLIC_ID = "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN";
87     public final static String JavaDoc WEB_PORTLET_DTD = "http://java.sun.com/dtd/web-app_2_3.dtd";
88
89     private static boolean debug = false;
90     private static final String JavaDoc webInfDir = File.separatorChar + "WEB-INF" + File.separatorChar;
91
92     /**
93      * Deploy the archive
94      * Unpack the archive in the servlet engine context directory
95      */

96     public static void deployArchive(final String JavaDoc webAppsDir,
97                                      final String JavaDoc warFile,
98                                      final String JavaDoc warFileName)
99     throws IOException JavaDoc {
100         System.out.println("Deploying '" + warFileName + "' ...");
101
102         final String JavaDoc destination = webAppsDir + warFileName;
103
104         if ( debug) {
105             System.out.println(" unpacking '" + warFile + "' ...");
106         }
107         final JarFile JavaDoc jarFile = new JarFile JavaDoc(warFile);
108         final Enumeration JavaDoc files = jarFile.entries();
109         while (files.hasMoreElements()) {
110             JarEntry JavaDoc entry = (JarEntry JavaDoc) files.nextElement();
111
112             File JavaDoc file = new File JavaDoc(destination, entry.getName());
113             File JavaDoc dirF = new File JavaDoc(file.getParent());
114             dirF.mkdirs();
115             if (entry.isDirectory()) {
116                 file.mkdirs();
117             } else {
118                 byte[] buffer = new byte[1024];
119                 int length = 0;
120                 InputStream JavaDoc fis = jarFile.getInputStream(entry);
121                 FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(file);
122                 while ((length = fis.read(buffer)) >= 0) {
123                     fos.write(buffer, 0, length);
124                 }
125                 fos.close();
126             }
127
128         }
129
130         if ( debug ) {
131             System.out.println("Finished!");
132         }
133     }
134
135     /**
136      * Helper method to setup the mapping
137      */

138     private static Mapping getMapping(final String JavaDoc uri)
139     throws IOException JavaDoc {
140         final String JavaDoc mappingResource = uri.substring(uri.indexOf("://")+2);
141         final Mapping mapping = new Mapping();
142      
143         final InputSource JavaDoc is = new InputSource JavaDoc(Deploy.class.getResourceAsStream(mappingResource));
144         try {
145             mapping.loadMapping( is );
146         } catch (Exception JavaDoc e) {
147             throw new IOException JavaDoc("Failed to load mapping file " + mappingResource);
148         }
149         return mapping;
150     }
151     
152     /**
153      * Prepare the web archive of the portlet web app
154      */

155     public static void prepareWebArchive(String JavaDoc webAppsDir, String JavaDoc webModule)
156     throws Exception JavaDoc {
157         System.out.println("Preparing web archive '" + webModule + "' ...");
158
159         // get portlet xml mapping file
160
Mapping mappingPortletXml = getMapping(PortletDefinitionRegistryImpl.PORTLET_MAPPING);
161         // get web xml mapping file
162
Mapping mappingWebXml = getMapping(PortletDefinitionRegistryImpl.WEBXML_MAPPING);
163
164         File JavaDoc portletXml = new File JavaDoc(webAppsDir + webModule + webInfDir + "portlet.xml");
165         File JavaDoc webXml = new File JavaDoc(webAppsDir + webModule + webInfDir + "web.xml");
166
167         Unmarshaller unmarshaller = new Unmarshaller(mappingPortletXml);
168         PortletApplicationDefinitionImpl portletApp =
169             (PortletApplicationDefinitionImpl)unmarshaller.unmarshal(new FileReader JavaDoc(portletXml));
170
171         // refill structure with necessary information
172
Vector JavaDoc structure = new Vector JavaDoc();
173         structure.add(webModule);
174         structure.add(null);
175         structure.add(null);
176         portletApp.preBuild(structure);
177
178         if (debug) {
179             System.out.println(portletApp);
180         }
181
182         // now generate web part
183

184         WebApplicationDefinitionImpl webApp = null;
185
186         if (webXml.exists()) {
187             Unmarshaller unmarshallerWeb = new Unmarshaller(mappingWebXml);
188             unmarshallerWeb.setIgnoreExtraElements(true);
189             webApp =
190                 (WebApplicationDefinitionImpl) unmarshallerWeb.unmarshal(
191                     new FileReader JavaDoc(webXml));
192         } else {
193             webApp = new WebApplicationDefinitionImpl();
194             DisplayNameImpl dispName = new DisplayNameImpl();
195             dispName.setDisplayName(webModule);
196             dispName.setLocale(Locale.ENGLISH);
197             DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
198             dispSet.add(dispName);
199             webApp.setDisplayNames(dispSet);
200             DescriptionImpl desc = new DescriptionImpl();
201             desc.setDescription("Automated generated Application Wrapper");
202             desc.setLocale(Locale.ENGLISH);
203             DescriptionSetImpl descSet = new DescriptionSetImpl();
204             descSet.add(desc);
205             webApp.setDescriptions(descSet);
206         }
207
208         ControllerFactory controllerFactory = new ControllerFactoryImpl();
209
210         ServletDefinitionListCtrl servletDefinitionSetCtrl =
211             (ServletDefinitionListCtrl) controllerFactory.get(
212                 webApp.getServletDefinitionList());
213         Collection JavaDoc servletMappings = webApp.getServletMappings();
214
215         Iterator JavaDoc portlets = portletApp.getPortletDefinitionList().iterator();
216         while (portlets.hasNext()) {
217
218             PortletDefinition portlet = (PortletDefinition) portlets.next();
219
220             if ( debug ) {
221                 System.out.println(" Portlet: " + portlet.getId());
222             }
223             // check if already exists
224
ServletDefinition servlet =
225                 webApp.getServletDefinitionList().get(portlet.getName());
226             if (servlet != null) {
227                 if (!servlet
228                     .getServletClass()
229                     .equals("org.apache.pluto.core.PortletServlet")) {
230                     System.out.println(
231                         "Note: Replaced already existing the servlet with the name '"
232                             + portlet.getName()
233                             + "' with the wrapper servlet.");
234                 }
235                 ServletDefinitionCtrl _servletCtrl =
236                     (ServletDefinitionCtrl) controllerFactory.get(servlet);
237                 _servletCtrl.setServletClass(
238                     "org.apache.pluto.core.PortletServlet");
239             } else {
240                 servlet =
241                     servletDefinitionSetCtrl.add(
242                         portlet.getName(),
243                         "org.apache.pluto.core.PortletServlet");
244             }
245
246             ServletDefinitionCtrl servletCtrl =
247                 (ServletDefinitionCtrl) controllerFactory.get(servlet);
248
249             DisplayNameImpl dispName = new DisplayNameImpl();
250             dispName.setDisplayName(portlet.getName() + " Wrapper");
251             dispName.setLocale(Locale.ENGLISH);
252             DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
253             dispSet.add(dispName);
254             servletCtrl.setDisplayNames(dispSet);
255             DescriptionImpl desc = new DescriptionImpl();
256             desc.setDescription("Automated generated Portlet Wrapper");
257             desc.setLocale(Locale.ENGLISH);
258             DescriptionSetImpl descSet = new DescriptionSetImpl();
259             descSet.add(desc);
260             servletCtrl.setDescriptions(descSet);
261             ParameterSet parameters = servlet.getInitParameterSet();
262
263             ParameterSetCtrl parameterSetCtrl =
264                 (ParameterSetCtrl) controllerFactory.get(parameters);
265
266             Parameter parameter1 = parameters.get("portlet-class");
267             if (parameter1 == null) {
268                 parameterSetCtrl.add(
269                     "portlet-class",
270                     portlet.getClassName());
271             } else {
272                 ParameterCtrl parameterCtrl =
273                     (ParameterCtrl) controllerFactory.get(parameter1);
274                 parameterCtrl.setValue(portlet.getClassName());
275
276             }
277             Parameter parameter2 = parameters.get("portlet-guid");
278             if (parameter2 == null) {
279                 parameterSetCtrl.add(
280                     "portlet-guid",
281                     portlet.getId().toString());
282             } else {
283                 ParameterCtrl parameterCtrl =
284                     (ParameterCtrl) controllerFactory.get(parameter2);
285                 parameterCtrl.setValue(portlet.getId().toString());
286
287             }
288
289             boolean found = false;
290             Iterator JavaDoc mappings = servletMappings.iterator();
291             while (mappings.hasNext()) {
292                 ServletMapping servletMapping =
293                     (ServletMapping) mappings.next();
294                 if (servletMapping
295                     .getServletName()
296                     .equals(portlet.getName())) {
297                     found = true;
298                     servletMapping.setUrlPattern(
299                         "/" + portlet.getName().replace(' ', '_') + "/*");
300                 }
301             }
302             if (!found) {
303                 ServletMapping servletMapping =
304                     new ServletMapping();
305                 servletMapping.setServletName(portlet.getName());
306                 servletMapping.setUrlPattern(
307                     "/" + portlet.getName().replace(' ', '_') + "/*");
308                 servletMappings.add(servletMapping);
309             }
310
311             SecurityRoleRefSet servletSecurityRoleRefs =
312                 ((ServletDefinitionImpl)servlet).getInitSecurityRoleRefSet();
313
314             SecurityRoleRefSetCtrl servletSecurityRoleRefSetCtrl =
315                 (SecurityRoleRefSetCtrl) controllerFactory.get(
316                     servletSecurityRoleRefs);
317
318             SecurityRoleSet webAppSecurityRoles = webApp.getSecurityRoles();
319                 
320             SecurityRoleRefSet portletSecurityRoleRefs =
321                 portlet.getInitSecurityRoleRefSet();
322
323             Iterator JavaDoc p = portletSecurityRoleRefs.iterator();
324
325             while (p.hasNext()) {
326                 SecurityRoleRef portletSecurityRoleRef =
327                     (SecurityRoleRef) p.next();
328                 
329                 if ( portletSecurityRoleRef.getRoleLink()== null
330                     &&
331                         webAppSecurityRoles.get(portletSecurityRoleRef.getRoleName())==null
332                 ){
333                     System.out.println(
334                         "Note: The web application has no security role defined which matches the role name \""
335                             + portletSecurityRoleRef.getRoleName()
336                             + "\" of the security-role-ref element defined for the wrapper-servlet with the name '"
337                             + portlet.getName()
338                             + "'.");
339                     break;
340                 }
341                 SecurityRoleRef servletSecurityRoleRef =
342                     servletSecurityRoleRefs.get(
343                         portletSecurityRoleRef.getRoleName());
344                 if (null != servletSecurityRoleRef) {
345                     System.out.println(
346                         "Note: Replaced already existing element of type <security-role-ref> with value \""
347                             + portletSecurityRoleRef.getRoleName()
348                             + "\" for subelement of type <role-name> for the wrapper-servlet with the name '"
349                             + portlet.getName()
350                             + "'.");
351                     servletSecurityRoleRefSetCtrl.remove(
352                         servletSecurityRoleRef);
353                 }
354                 servletSecurityRoleRefSetCtrl.add(portletSecurityRoleRef);
355             }
356
357         }
358
359         TagDefinition portletTagLib = new TagDefinition();
360         Collection JavaDoc taglibs = webApp.getCastorTagDefinitions();
361         taglibs.add(portletTagLib);
362         
363         if (debug) {
364             System.out.println(webApp);
365         }
366
367         OutputFormat of = new OutputFormat();
368         of.setIndenting(true);
369         of.setIndent(4); // 2-space indention
370
of.setLineWidth(16384);
371         // As large as needed to prevent linebreaks in text nodes
372
of.setDoctype(WEB_PORTLET_PUBLIC_ID, WEB_PORTLET_DTD);
373
374         FileWriter JavaDoc writer =
375             new FileWriter JavaDoc(webAppsDir + webModule +
376                                            SystemUtils.FILE_SEPARATOR + "WEB-INF"+
377                                            SystemUtils.FILE_SEPARATOR + "web.xml");
378         XMLSerializer serializer = new XMLSerializer(writer, of);
379         try {
380             Marshaller marshaller = new Marshaller(serializer.asDocumentHandler());
381             marshaller.setMapping(mappingWebXml);
382             marshaller.marshal(webApp);
383         } finally {
384             writer.close();
385         }
386
387         if ( debug ) {
388             System.out.println("Finished!");
389         }
390     }
391
392     public static void main(String JavaDoc args[]) {
393         String JavaDoc warFile;
394         String JavaDoc webAppsDir;
395         
396         final Options options = new Options();
397
398         Option o;
399         o = new Option("w", true, "webapps directory");
400         o.setRequired(true);
401         o.setArgName("WEBAPPS_DIR");
402         options.addOption(o);
403         
404         o = new Option("p", true, "web archive containing the portlet(s)");
405         o.setRequired(true);
406         o.setArgName("PORTLET_WAR");
407         options.addOption(o);
408         
409         options.addOption("d", "debug", false, "Show debug messages.");
410         
411         try {
412             final CommandLineParser parser = new PosixParser();
413             final CommandLine cmd = parser.parse( options, args);
414
415             // first test/turn on debug
416
debug = cmd.hasOption("d");
417             if (debug) {
418                 for(int i=0; i<args.length;i++) {
419                     System.out.println( "args["+ i +"]:" + args[i]);
420                 }
421             }
422             
423             
424             webAppsDir = cmd.getOptionValue("w");
425             if (!webAppsDir.endsWith(File.separator))
426                 webAppsDir += File.separatorChar;
427     
428             //portalImplWebDir = cmd.getOptionValue("X");
429
//if (!portalImplWebDir.endsWith(File.separator))
430
// portalImplWebDir += File.separatorChar;
431

432             warFile = cmd.getOptionValue("p");
433         } catch( ParseException exp ) {
434             HelpFormatter formatter = new HelpFormatter();
435             formatter.printHelp( "deploy", options, true );
436             System.exit(1);
437             return;
438         }
439
440         // let's do some tests on the war file name
441
String JavaDoc warFileName = warFile;
442         if (warFileName.indexOf("/") != -1) {
443             warFileName = warFileName.substring(warFileName.lastIndexOf("/") + 1);
444         }
445         if (warFileName.indexOf(File.separatorChar) != -1) {
446             warFileName = warFileName.substring(warFileName.lastIndexOf(File.separatorChar) + 1);
447         }
448         if (warFileName.endsWith(".war")) {
449             warFileName = warFileName.substring(0, warFileName.lastIndexOf("."));
450         }
451
452         try {
453             deployArchive(webAppsDir, warFile, warFileName);
454
455             prepareWebArchive(webAppsDir, warFileName);
456         } catch (Exception JavaDoc e) {
457             e.printStackTrace();
458             System.exit(1);
459             return;
460         }
461         System.exit(0);
462     }
463
464 }
465
Popular Tags