1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.jetspeed.deployment;
18  
19  import java.io.File;
20  import java.io.FileInputStream;
21  import java.io.FileNotFoundException;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import java.nio.channels.FileChannel;
25  
26  import junit.framework.AssertionFailedError;
27  import junit.framework.Test;
28  import junit.framework.TestSuite;
29  
30  import org.apache.jetspeed.AbstractRequestContextTestCase;
31  import org.apache.jetspeed.components.portletentity.PortletEntityNotStoredException;
32  import org.apache.jetspeed.container.window.PortletWindowAccessor;
33  import org.apache.jetspeed.deployment.impl.StandardDeploymentManager;
34  import org.apache.jetspeed.factory.PortletFactory;
35  import org.apache.jetspeed.om.common.portlet.MutablePortletApplication;
36  import org.apache.jetspeed.om.common.portlet.MutablePortletEntity;
37  import org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager;
38  import org.apache.jetspeed.util.DirectoryHelper;
39  import org.apache.jetspeed.util.JarHelper;
40  import org.apache.pluto.om.portlet.PortletDefinition;
41  
42  /***
43   * <p>
44   * TestSimpleDeployment
45   * </p>
46   * 
47   * @author <a href="mailto:weaver@apache.org">Scott T. Weaver </a>
48   * @version $Id: TestSimpleDeployment.java 517719 2007-03-13 15:05:48Z ate $
49   *  
50   */
51  public class TestSimpleDeployment extends AbstractRequestContextTestCase
52  {
53      protected static final String TEST_PORTLET_APP_NAME = "HW_App";
54      protected String webAppsDir;
55  
56      protected File deploySrc;
57  
58      protected File deployRootFile;
59  
60      protected String testDb;
61      protected File webAppsDirFile;
62      protected File copyFrom;
63      protected PortletWindowAccessor windowAccess;
64      protected PortletFactory portletFactory;
65      protected ApplicationServerManager manager;
66   
67  
68      /***
69       * Start the tests.
70       * 
71       * @param args
72       *            the arguments. Not used
73       */
74      public static void main( String args[] )
75      {
76          junit.awtui.TestRunner.main(new String[]{TestSimpleDeployment.class.getName()});
77      }
78  
79      /***
80       * Creates the test suite.
81       * 
82       * @return a test suite (<code>TestSuite</code>) that includes all
83       *         methods starting with "test"
84       */
85      public static Test suite()
86      {
87          // All methods starting with "test" will be executed in the test suite.
88          // return new JetspeedTestSuite(TestSimpleDeployment.class);
89          return new TestSuite(TestSimpleDeployment.class);
90      }
91      public void testFileSystemHelperOnWar() throws Exception
92      {
93          File demoApp = new File(deploySrc, "demo.war");
94             
95          JarHelper jarHelper = new JarHelper(demoApp, true);
96          File rootDirectory = jarHelper.getRootDirectory();
97          File webXml = new File(rootDirectory, "WEB-INF/web.xml");
98          assertTrue(webXml.exists());
99          jarHelper.close();          
100         assertFalse(webXml.exists());
101         
102         // Test for keeping jar temp files around
103         jarHelper = new JarHelper(demoApp, false);
104         assertTrue(webXml.exists());
105         jarHelper.close();          
106         assertTrue(webXml.exists());
107     }
108     
109     public void testFileSystemManagerOnDir() throws Exception
110     {
111         File demoApp = new File("./test/testdata/deploy/webapp");
112         assertTrue(demoApp.exists());
113         
114         DirectoryHelper dirHelper = new DirectoryHelper(demoApp);
115         File webXml = new File(dirHelper.getRootDirectory(), "WEB-INF/web.xml");
116         assertTrue(webXml.exists());
117              
118     }
119     
120     /*    
121     
122     public void testDeploy() throws Exception
123     {
124 
125         System.out.println("Deployment src: " + deploySrc);
126         manager = new TomcatManager("", "", 0, "", 0, "", "");
127         SimpleRegistry simpleRegistry = new InMemoryRegistryImpl();
128         DeployDecoratorEventListener ddel = new DeployDecoratorEventListener(simpleRegistry, deployRootFile
129                 .getAbsolutePath());
130 
131         DeployPortletAppEventListener dpal = new DeployPortletAppEventListener(webAppsDir, new FileSystemPAM(
132                 webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager), portletRegistry );
133         ArrayList eventListeners = new ArrayList(2);
134         eventListeners.add(ddel);
135         eventListeners.add(dpal);
136         // Use a -1 delay to disable auto scan
137         StandardDeploymentManager autoDeployment = new StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners );
138         
139         autoDeployment.start();
140         autoDeployment.fireDeploymentEvent();
141 
142         File decoratorVm = new File(deployRootFile.getAbsolutePath() + File.separator + "generic" + File.separator + "html" + File.separator
143                 + "portletstd" + File.separator + "decorator.vm");
144         
145         File demoAppDeployed = new File(webAppsDirFile, TEST_PORTLET_APP_NAME);
146         File demoApp = demoAppDeployed;
147         File securityApp = new File(webAppsDirFile, "TestSecurityRoles");
148 
149         assertTrue(decoratorVm.getCanonicalPath() + " was not created!", decoratorVm.exists());
150 
151         verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
152         verifyDemoAppCreated("TestSecurityRoles", securityApp);
153        
154         MutablePortletApplication jetspeedApp = portletRegistry.getPortletApplicationByIdentifier("jetspeed");
155         assertNotNull("jetspeed was not registered into the portlet registery.", jetspeedApp);
156         assertFalse("local app, jetspeed, got deployed when it should have only been registered.", new File(webAppsDir
157                 + "/jetspeed").exists());
158 
159         //make sure we can load registered app's classes
160         Iterator portletDefItr = jetspeedApp.getPortletDefinitions().iterator();
161         while (portletDefItr.hasNext())
162         {
163             PortletDefinition def = (PortletDefinition) portletDefItr.next();
164             try
165             {
166                 Portlet portlet = JetspeedPortletFactoryProxy.loadPortletClass(def.getClassName());
167                 assertNotNull("Could not load portlet class: "+def.getClassName(), portlet);
168             }
169             catch (Exception e)
170             {
171                 assertNull("Unable to load registered portlet class, " + def.getClassName(), e);
172             }
173 
174         }
175         
176         // test undeploy
177         File demoWar = new File(deploySrc, "demo.war");
178         demoWar.delete();
179         autoDeployment.fireUndeploymentEvent();        
180         verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp);    
181         
182         // test deploy again        
183         copyDeployables();
184         autoDeployment.fireDeploymentEvent();
185         verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
186         demoWar.delete();
187         autoDeployment.fireUndeploymentEvent();
188         verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp);
189         
190         // test redeploy
191         
192         // So, first deploy the typical demo.war we have been using before.
193         copyDeployables();
194         autoDeployment.fireDeploymentEvent();
195         verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
196         DirectoryHelper demoAppDeployedDir = new DirectoryHelper(demoAppDeployed);
197         long beforeSize = new File(demoAppDeployedDir.getRootDirectory(), "WEB-INF/portlet.xml").length();
198         
199         // Trigger re-deployment using a demo.war that has a slightly larger portlet.xml
200         // then the one we just deployed.  We will use size comparisons as or litmus test.
201         File redeployDemoWar = new File("./test/deployment/redeploy/demo.war");
202         FileChannel srcDemoWarChannel = new FileInputStream(redeployDemoWar).getChannel();
203         FileChannel dstDemoWarChannel = new FileOutputStream(demoWar).getChannel();
204         dstDemoWarChannel.transferFrom(srcDemoWarChannel, 0, srcDemoWarChannel.size());
205         srcDemoWarChannel.close();
206         dstDemoWarChannel.close();
207         
208         // Make sure the demo.war that will trigger redeploy has a larger portlet.xml then the current one
209         JarHelper rdDemoWar = new JarHelper(demoWar, true);
210         assertTrue(new File(rdDemoWar.getRootDirectory(), "WEB-INF/portlet.xml").length() > beforeSize);
211         
212         // Need to slow it down so the timestamp check works
213         Thread.sleep(500);
214         demoWar.setLastModified(System.currentTimeMillis());
215         autoDeployment.fireRedeploymentEvent();
216       
217         long afterSize = new File(demoAppDeployedDir.getRootDirectory(), "WEB-INF/portlet.xml").length();
218         // The portlet.xml in re-deploy has an additional portlet entry in portlet.xml, so it should be bigger
219         assertTrue(afterSize > beforeSize);
220         autoDeployment.stop();
221         
222     }
223     
224     
225     public void testUndeployVersusRedeploy() throws Exception
226     {
227         manager = new TomcatManager("", "", 0, "", 0, "", "");
228         
229         DeployPortletAppEventListener dpal = new DeployPortletAppEventListener(webAppsDir, new FileSystemPAM(
230                 webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager), portletRegistry );
231         ArrayList eventListeners = new ArrayList(1);
232         
233         eventListeners.add(dpal);
234         
235         // Use a -1 delay to disable auto scan
236         StandardDeploymentManager autoDeployment = new StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners );        
237         autoDeployment.start();
238 
239         buildEntityTestData(autoDeployment);       
240         
241         
242         MutablePortletEntity entity = entityAccess.getPortletEntity("testEnity");
243         
244         PreferenceSetCtrl prefs = (PreferenceSetCtrl) entity.getPreferenceSet();
245         List values = new ArrayList(1);
246         values.add("some value");
247         prefs.add("pref1", values);
248         
249         entity.store();
250         
251         assertNotNull(entity);
252         
253         Preference pref = entity.getPreferenceSet().get("pref1");
254         
255         assertNotNull(pref);
256         
257         //test entity removal via undeploy
258         File demoWar = new File(deploySrc, "demo.war");
259         demoWar.delete();
260         
261         autoDeployment.fireUndeploymentEvent();
262         
263                 
264         entity = entityAccess.getPortletEntity("testEnity");
265         
266         assertNull(entity);
267         
268         // Now test that redploy DOES NOT kill the entity
269         buildEntityTestData(autoDeployment);
270         
271         entity = entityAccess.getPortletEntity("testEnity");
272         
273         assertNotNull(entity);
274         
275         pref = entity.getPreferenceSet().get("pref1");
276         
277         assertNull("Preference was not deleted with last undeploy",pref);
278         
279         demoWar.setLastModified(System.currentTimeMillis());
280         
281         autoDeployment.fireRedeploymentEvent();        
282         
283         entity = entityAccess.getPortletEntity("testEnity");
284         
285         assertNotNull(entity);
286         
287     }
288 */   
289 
290     /***
291      * <p>
292      * buildEntityTestData
293      * </p>
294      *
295      * @param autoDeployment
296      * @throws IOException
297      * @throws PortletEntityNotStoredException
298      */
299     protected void buildEntityTestData( StandardDeploymentManager autoDeployment ) throws Exception
300     {
301         copyDeployables();
302         
303         File demoApp = new File(webAppsDirFile, TEST_PORTLET_APP_NAME);
304                 
305         autoDeployment.fireDeploymentEvent();
306         
307         verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
308         
309         MutablePortletApplication app = portletRegistry.getPortletApplication(TEST_PORTLET_APP_NAME);
310         
311         PortletDefinition portlet = (PortletDefinition) app.getPortletDefinitionList().iterator().next();
312         
313         MutablePortletEntity entity = entityAccess.newPortletEntityInstance(portlet);
314         entity.setId("testEnity");
315         
316         entityAccess.storePortletEntity(entity);
317         
318         
319         
320     }
321 
322     /***
323      * <p>
324      * verifyDemoAppCreated
325      * </p>
326      *
327      * @param demoApp
328      */
329     private void verifyDemoAppCreated( String appName, File appFile )
330     {
331         assertNotNull(appName + " was not registered into the portlet registery.", portletRegistry
332                 .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME));
333         assertTrue(appName + " directory was not created, app not deployed.", appFile.exists());
334     }
335     
336 
337     
338     
339 
340     /***
341      * <p>
342      * verifyDemoAppDeleted
343      * </p>
344      *
345      * @param demoApp
346      *
347     private void verifyDemoAppDeleted( String appName, File appFile )
348     {
349         assertNull(appName + " was not removed from the registry.", portletRegistry
350                 .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME));
351         assertFalse(appName+" directory was not deleted.", appFile.exists());
352     }
353     */
354 
355     /***
356      * @see junit.framework.TestCase#setUp()
357      */
358     public void setUp()
359     {
360 
361         try
362         {
363             super.setUp();
364             copyFrom = new File("./test/deployment/deploy");
365             deploySrc = new File("./target/deployment/deploy");
366             deploySrc.mkdirs();
367             deployRootFile = new File("./target/deployment/templates/decorators");
368             deployRootFile.mkdirs();
369             webAppsDirFile = new File("./target/deployment/webapps");
370             webAppsDirFile.mkdirs();
371 
372             webAppsDir = webAppsDirFile.getCanonicalPath();
373             testDb = new File("./test/db/hsql/Registry").getCanonicalPath();           
374             
375             copyDeployables();
376 //            windowAccess = new PortletWindowAccessorImpl(entityAccess, true);  
377         }
378         catch (Exception e)
379         {
380             e.printStackTrace();
381             throw new AssertionFailedError("Unable to set up test environment " + e.toString());
382         }
383 
384     }
385 
386     /***
387      * <p>
388      * copyDeployables
389      * </p>
390      * @throws IOException
391      */
392     protected void copyDeployables() throws IOException
393     {      
394         
395   
396         copyFiles(copyFrom, deploySrc);
397         
398     }
399     
400     
401 
402     /***
403      * <p>
404      * copyFiles
405      * </p>
406      *
407      * @throws IOException
408      * @throws FileNotFoundException
409      */
410     protected void copyFiles(File srcDir, File dstDir) throws IOException, FileNotFoundException
411     {
412         File[] children = srcDir.listFiles();
413         for(int i=0; i<children.length; i++)
414         {
415             File child = children[i];
416             if(child.isFile())
417             {
418                 File toFile = new File(dstDir, child.getName());
419                 toFile.createNewFile();
420                 FileChannel srcChannel = new FileInputStream(child).getChannel();
421                 FileChannel dstChannel = new FileOutputStream(toFile).getChannel();
422                 dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
423                 srcChannel.close();
424                 dstChannel.close();
425             }
426             else
427             {
428                 File newSubDir = new File(dstDir, child.getName());
429                 newSubDir.mkdir();
430                 copyFiles(child, newSubDir);
431             }
432         }
433     }
434 
435     /***
436      * @see junit.framework.TestCase#tearDown()
437      */
438     public void tearDown() throws Exception
439     {
440 /*        
441         manager = new TomcatManager("", "", 0, "", 0, "", "");
442         FileSystemPAM pam = new FileSystemPAM(webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager);
443 
444         try
445         {
446             DirectoryHelper dirHelper = new DirectoryHelper(new File(webAppsDir + "/" + TEST_PORTLET_APP_NAME));
447             paWar1 = new PortletApplicationWar(dirHelper, TEST_PORTLET_APP_NAME, "/"
448                     + TEST_PORTLET_APP_NAME);
449             pam.undeploy(paWar1);
450         }
451         catch (Exception e1)
452         {
453 
454         }
455 
456         pam.unregister("jetspeed");
457 
458         try
459         {
460             DirectoryHelper dirHelper = new DirectoryHelper(new File(webAppsDir + "/TestSecurityRoles"));
461             paWar3 = new PortletApplicationWar(dirHelper, "TestSecurityRoles", "/TestSecurityRoles" );
462 
463             pam.undeploy(paWar3);
464         }
465         catch (Exception e3)
466         {
467 
468         }
469 
470         // DirectoryUtils.rmdir(new File("./target/deployment"));
471         new DirectoryHelper(new File("./target/deployment")).remove();
472 */        
473         super.tearDown();
474 
475     }
476 
477     
478 }