portals-jetspeed-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rwat...@apache.org
Subject svn commit: r1641403 - in /portals/jetspeed-2/portal/trunk/components: jetspeed-cm/ jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/ jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/
Date Mon, 24 Nov 2014 15:01:26 GMT
Author: rwatler
Date: Mon Nov 24 15:01:25 2014
New Revision: 1641403

URL: http://svn.apache.org/r1641403
Log:
JS2-1307: Refactor Jexl Scriptable Test Case for Reuse.

Added:
    portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestCase.java
    portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestServer.java
Modified:
    portals/jetspeed-2/portal/trunk/components/jetspeed-cm/pom.xml
    portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/DatabasePageManagerServer.java
    portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/TestDatabasePageManagerCache.java

Modified: portals/jetspeed-2/portal/trunk/components/jetspeed-cm/pom.xml
URL: http://svn.apache.org/viewvc/portals/jetspeed-2/portal/trunk/components/jetspeed-cm/pom.xml?rev=1641403&r1=1641402&r2=1641403&view=diff
==============================================================================
--- portals/jetspeed-2/portal/trunk/components/jetspeed-cm/pom.xml (original)
+++ portals/jetspeed-2/portal/trunk/components/jetspeed-cm/pom.xml Mon Nov 24 15:01:25 2014
@@ -46,6 +46,11 @@
             <scope>provided</scope>
         </dependency>
         <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>jetspeed-commons</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-core</artifactId>
           <version>${spring.version}</version>
@@ -125,6 +130,18 @@
             <artifactId>junit</artifactId>
             <scope>provided</scope>
         </dependency>
+        <!--
+            again, abstract test cases require jexl... mark as
+            provided to keep jexl out of runtime. requires jexl
+            be included as test dependencies where used. should
+            be fixed if the project structure is reworked; see
+            junit dependency above.
+        -->
+        <dependency>
+            <groupId>commons-jexl</groupId>
+            <artifactId>commons-jexl</artifactId>
+            <scope>provided</scope>
+        </dependency>
 
         <!-- Test Dependencies -->
         <dependency>

Added: portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestCase.java
URL: http://svn.apache.org/viewvc/portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestCase.java?rev=1641403&view=auto
==============================================================================
--- portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestCase.java (added)
+++ portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestCase.java Mon Nov 24 15:01:25 2014
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.jetspeed.components.test;
+
+import junit.framework.TestCase;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Abstract Jexl scriptable test case.
+ *
+ * @author <a href="mailto:rwatler@apache.org">Randy Watler</a>
+ * @version $Id:$
+ */
+public abstract class AbstractJexlSpringTestCase extends TestCase {
+
+    private static final long LOGGING_PUMP_WAIT = 50;
+
+    private Logger log = LoggerFactory.getLogger(getClass());
+
+    private String osExecutableExtension;
+    private String fileSeparator;
+    private File javaExecutablePath;
+    private String classPathSeparator;
+    private File projectDirectoryPath;
+    private Map<String,String> systemProperties;
+    private String classPath;
+
+    @Override
+    protected void setUp() throws Exception {
+        // environment setup
+        osExecutableExtension = (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
+        fileSeparator = System.getProperty("file.separator");
+        javaExecutablePath = new File(System.getProperty("java.home")+fileSeparator+"bin"+fileSeparator+"java"+osExecutableExtension);
+        classPathSeparator = System.getProperty("path.separator");
+        projectDirectoryPath = new File(System.getProperty("basedir"));
+        systemProperties = new HashMap<String,String>();
+        for (Map.Entry<Object,Object> systemProperty : System.getProperties().entrySet()) {
+            String propertyName = systemProperty.getKey().toString();
+            String propertyValue = systemProperty.getValue().toString();
+            if (propertyName.startsWith("org.apache.jetspeed.") || propertyName.startsWith("java.net.") || propertyName.equals("basedir")) {
+                systemProperties.put(propertyName, propertyValue);
+            }
+        }
+
+        // construct launcher classpath from current class loader
+        StringBuilder classPathBuilder = new StringBuilder();
+        ClassLoader loader = this.getClass().getClassLoader();
+        assertTrue(loader instanceof URLClassLoader);
+        URLClassLoader urlLoader = (URLClassLoader)loader;
+        assertNotNull(urlLoader.getURLs());
+        for (URL pathURL : urlLoader.getURLs()) {
+            // convert path URL to file path
+            String path = new File(pathURL.toURI()).getCanonicalPath();
+
+            // build class path
+            if (classPathBuilder.length() > 0) {
+                classPathBuilder.append(classPathSeparator);
+            }
+            classPathBuilder.append(path);
+        }
+        classPath = classPathBuilder.toString();
+        assertTrue(classPath.length() > 0);
+
+        // continue setup
+        super.setUp();
+    }
+
+    protected String testProgramSystemPropertyValueFilter(String propertyName, int index, String propertyValue) {
+        // return original property value by default
+        return propertyValue;
+    }
+
+    protected Map<String,String> testProgramSystemProperties() {
+        return new HashMap<String,String>();
+    }
+
+    protected void sleep(TestProgram server0, TestProgram server1, long millis) throws IOException, InterruptedException {
+        long slept = 0;
+        while (slept < millis) {
+            // poll servers for logging
+            server0.poll();
+            server1.poll();
+            // sleep for interval
+            long sleep = Math.min(millis-slept, LOGGING_PUMP_WAIT);
+            Thread.sleep(sleep);
+            slept += sleep;
+        }
+    }
+
+    protected class TestProgram {
+
+        private String name;
+        private Class<?> mainClass;
+        private int index;
+
+        private Process process;
+        private BufferedWriter processInput;
+        private BufferedReader processOutput;
+
+        public TestProgram(String name, Class<?> mainClass, int index) {
+            this.name = name;
+            this.mainClass = mainClass;
+            this.index = index;
+        }
+
+        public synchronized void start() throws IOException {
+            assertNull(process);
+
+            // configure launcher with paths, properties, and indexed properties
+            ProcessBuilder launcher = new ProcessBuilder();
+            List<String> commandAndArgs = new ArrayList<String>();
+            commandAndArgs.add(javaExecutablePath.getCanonicalPath());
+            for (Map.Entry<String,String> systemProperty : systemProperties.entrySet()) {
+                String propertyName = systemProperty.getKey();
+                String propertyValue = testProgramSystemPropertyValueFilter(propertyName, index, systemProperty.getValue());
+                commandAndArgs.add( "-D"+propertyName+"="+propertyValue);
+            }
+            for (Map.Entry<String,String> systemProperty : testProgramSystemProperties().entrySet()) {
+                String propertyName = systemProperty.getKey();
+                String propertyValue = testProgramSystemPropertyValueFilter(propertyName, index, systemProperty.getValue());
+                commandAndArgs.add( "-D"+propertyName+"="+propertyValue);
+            }
+            commandAndArgs.add("-classpath");
+            commandAndArgs.add(classPath);
+            commandAndArgs.add(mainClass.getName());
+            log.info("Launcher command for "+name+": "+commandAndArgs);
+            launcher.command(commandAndArgs);
+            launcher.directory(projectDirectoryPath);
+            launcher.redirectErrorStream(true);
+
+            // launch test programs
+            process = launcher.start();
+
+            // setup I/O for process
+            processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
+            processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
+
+            // read messages from process
+            for (String line; (processOutput.ready() && ((line = processOutput.readLine()) != null));) {
+                logProcessLine(line);
+            }
+        }
+
+        public synchronized void poll() throws IOException
+        {
+            assertNotNull(process);
+
+            // read messages from process
+            for (String line; (processOutput.ready() && ((line = processOutput.readLine()) != null));) {
+                logProcessLine(line);
+            }
+        }
+
+        public synchronized String execute(String scriptLine) throws IOException
+        {
+            // poll to read messages from process
+            poll();
+
+            // write script line to process
+            processInput.write(scriptLine);
+            processInput.newLine();
+            processInput.flush();
+
+            // read result or messages from process
+            String resultLine = null;
+            for (String line; ((line = processOutput.readLine()) != null);) {
+                if (! line.startsWith(AbstractJexlSpringTestServer.SCRIPT_RESULT_LINE_PREFIX)) {
+                    logProcessLine(line);
+                } else {
+                    resultLine = line;
+                    break;
+                }
+            }
+            if ( resultLine == null) {
+                throw new IOException("Unexpected EOF from process output");
+            }
+            return resultLine;
+        }
+
+        public synchronized void shutdown(final long millis) throws IOException, InterruptedException {
+            assertNotNull(process);
+
+            // start thread to destroy process on timeout
+            Thread destroyThread = new Thread(new Runnable() {
+                public void run() {
+                    try {
+                        Thread.sleep(millis);
+                        if ( process != null) {
+                            log.warn( "Forcibly stopping "+name);
+                            process.destroy();
+                        }
+                    } catch (Exception e) {
+                    }
+                }
+            }, "DestroyThread");
+            destroyThread.setDaemon( true);
+            destroyThread.start();
+
+            // close process input to shutdown server and read messages
+            processInput.close();
+            for (String line; ((line = processOutput.readLine()) != null);) {
+                logProcessLine(line);
+            }
+
+            // join on process completion
+            process.waitFor();
+            processOutput.close();
+            process = null;
+
+            // join on destroy thread
+            destroyThread.interrupt();
+            destroyThread.join();
+        }
+
+        private void logProcessLine(String line)
+        {
+            if (line.contains("ERROR") || line.contains("Exception") || line.matches("\\s+at\\s.*")) {
+                log.error("{"+name+"} "+line);
+            } else {
+                log.info("{"+name+"} "+line);
+            }
+        }
+    }
+}

Added: portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestServer.java
URL: http://svn.apache.org/viewvc/portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestServer.java?rev=1641403&view=auto
==============================================================================
--- portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestServer.java (added)
+++ portals/jetspeed-2/portal/trunk/components/jetspeed-cm/src/main/java/org/apache/jetspeed/components/test/AbstractJexlSpringTestServer.java Mon Nov 24 15:01:25 2014
@@ -0,0 +1,224 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.jetspeed.components.test;
+
+import org.apache.commons.jexl.JexlContext;
+import org.apache.commons.jexl.JexlHelper;
+import org.apache.commons.jexl.Script;
+import org.apache.commons.jexl.ScriptFactory;
+import org.apache.jetspeed.components.JetspeedBeanDefinitionFilter;
+import org.apache.jetspeed.components.SpringComponentManager;
+import org.apache.jetspeed.security.JSSubject;
+
+import javax.security.auth.Subject;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.security.PrivilegedAction;
+import java.util.Map;
+
+/**
+ * Abstract Jexl scriptable test server.
+ *
+ * @author <a href="mailto:rwatler@apache.org">Randy Watler</a>
+ * @version $Id:$
+ */
+public abstract class AbstractJexlSpringTestServer {
+
+    public static final String SCRIPT_RESULT_LINE_PREFIX = "> ";
+
+    protected String baseDir;
+    protected SpringComponentManager scm;
+    protected JexlContext jexlContext;
+    protected boolean exit;
+
+    /**
+     * Initialize page manager server instance and script context.
+     *
+     * @throws Exception
+     */
+    public void initialize() throws Exception {
+        // setup jetspeed test component manager
+        JetspeedBeanDefinitionFilter beanDefinitionFilter = new JetspeedBeanDefinitionFilter(getBeanDefinitionFilterCategories());
+        String [] bootConfigurations = getBootConfigurations();
+        String [] configurations = getConfigurations();
+        baseDir = System.getProperty("basedir");
+        if ((baseDir == null) || (baseDir.length() == 0)) {
+            baseDir = System.getProperty("user.dir");
+        }
+        String appRoot = baseDir+"/target/test-classes/webapp";
+        scm = new SpringComponentManager(beanDefinitionFilter, bootConfigurations, configurations, appRoot, false);
+        scm.start();
+
+        // create jexl context
+        jexlContext = JexlHelper.createContext();
+        jexlContext.getVars().putAll(getContextVars());
+    }
+
+    /**
+     * Get Jetspeed Spring filter categories list.
+     *
+     * @return filter categories CSV list
+     */
+    protected abstract String getBeanDefinitionFilterCategories();
+
+    /**
+     * Get array of Spring boot configurations to load.
+     *
+     * @return Spring boot configurations array
+     */
+    protected String[] getBootConfigurations() {
+        return null;
+    }
+
+    /**
+     * Get array of Spring configurations to load.
+     *
+     * @return Spring configurations array
+     */
+    protected abstract String[] getConfigurations();
+
+    /**
+     * Get list of top level objects to add to Jexl context vars.
+     *
+     * @return map of context variables
+     */
+    protected abstract Map<String,Object> getContextVars();
+
+    /**
+     * Terminate page manager server instance.
+     *
+     * @throws Exception
+     */
+    public void terminate() throws Exception {
+        // tear down jetspeed component manager
+        scm.stop();
+    }
+
+    /**
+     * Execute a single line script against page manager server context.
+     *
+     * @param scriptLine jexl script
+     * @return script result line
+     */
+    public String execute(String scriptLine) {
+        // execute script line and return result line
+        String resultLine = scriptLine;
+        try {
+            Script jexlScript = ScriptFactory.createScript(scriptLine);
+            Object result = jexlScript.execute(jexlContext);
+            if (result != null) {
+                resultLine += " -> "+result;
+            }
+        } catch (Exception e) {
+            resultLine += " -> "+e;
+        }
+        return resultLine;
+    }
+
+    /**
+     * Sets server exit flag.
+     */
+    public void exit() {
+        exit = true;
+    }
+
+    /**
+     * Get server exit flag.
+     *
+     * @return server exit flag
+     */
+    public boolean isExit() {
+        return exit;
+    }
+
+    /**
+     * Get or create and cache user subject.
+     *
+     * @return user subject
+     */
+    protected Subject getUserSubject() {
+        return null;
+    }
+
+    /**
+     * Server main entry point.
+     *
+     * @return runtime exception or null
+     */
+    public Throwable run() {
+        try {
+            // initialize server
+            initialize();
+
+            // simple server reads script lines from standard
+            // input and writes results on standard output
+            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+            PrintWriter out = new PrintWriter(System.out, true);
+            do {
+                // read single line scripts to execute
+                String scriptLine = in.readLine();
+                if (scriptLine != null) {
+                    scriptLine = scriptLine.trim();
+                    String resultLine = "";
+                    if (scriptLine.length() > 0) {
+                        // get user and execute script
+                        Subject userSubject = getUserSubject();
+                        if (userSubject != null) {
+                            // execute script as user
+                            final String executeScriptLine = scriptLine;
+                            final String [] executeResultLine = new String[]{null};
+                            Exception executeException = (Exception) JSSubject.doAsPrivileged(userSubject, new PrivilegedAction() {
+                                public Object run() {
+                                    try {
+                                        executeResultLine[0] = execute(executeScriptLine);
+                                        return null;
+                                    } catch (Exception e) {
+                                        return e;
+                                    } finally {
+                                        JSSubject.clearSubject();
+                                    }
+                                }
+                            }, null);
+                            if (executeException != null) {
+                                throw executeException;
+                            }
+                            resultLine = executeResultLine[0];
+                        } else {
+                            // execute script anonymously
+                            resultLine = execute(scriptLine);
+                        }
+                    }
+
+                    // write prefixed single line results
+                    out.println(SCRIPT_RESULT_LINE_PREFIX+resultLine);
+                } else {
+                    // exit server on input EOF
+                    exit();
+                }
+            }
+            while (!isExit());
+
+            // terminate server and return
+            terminate();
+            return null;
+        } catch (Throwable t) {
+            return t;
+        }
+    }
+}

Modified: portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/DatabasePageManagerServer.java
URL: http://svn.apache.org/viewvc/portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/DatabasePageManagerServer.java?rev=1641403&r1=1641402&r2=1641403&view=diff
==============================================================================
--- portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/DatabasePageManagerServer.java (original)
+++ portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/DatabasePageManagerServer.java Mon Nov 24 15:01:25 2014
@@ -16,26 +16,17 @@
  */
 package org.apache.jetspeed.page.cache;
 
-import org.apache.commons.jexl.JexlContext;
-import org.apache.commons.jexl.JexlHelper;
-import org.apache.commons.jexl.Script;
-import org.apache.commons.jexl.ScriptFactory;
-import org.apache.jetspeed.components.JetspeedBeanDefinitionFilter;
-import org.apache.jetspeed.components.SpringComponentManager;
 import org.apache.jetspeed.components.jndi.JetspeedTestJNDIComponent;
+import org.apache.jetspeed.components.test.AbstractJexlSpringTestServer;
 import org.apache.jetspeed.page.PageManager;
 import org.apache.jetspeed.page.PageManagerTestShared;
-import org.apache.jetspeed.security.JSSubject;
 import org.apache.jetspeed.security.PrincipalsSet;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import javax.security.auth.Subject;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
 import java.security.Principal;
-import java.security.PrivilegedAction;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -46,136 +37,98 @@ import java.util.Set;
  * @author <a href="mailto:rwatler@apache.org">Randy Watler</a>
  * @version $Id: $
  */
-public class DatabasePageManagerServer
-{
+public class DatabasePageManagerServer extends AbstractJexlSpringTestServer {
+
     protected static Logger log = LoggerFactory.getLogger(DatabasePageManagerServer.class);
     
-    // Constants
-    
-    public static final String SCRIPT_RESULT_LINE_PREFIX = "> ";
-    
-    // Members
-    
     private JetspeedTestJNDIComponent jndiDS;
-    private String baseDir;
-    private SpringComponentManager scm;
     private PageManager pageManager;
-    private JexlContext jexlContext;
-    private boolean exit;
+
     private String user;
     private String groups;
     private String roles;
     private Subject userSubject;
     
-    // Life cycle
-    
-    /**
-     * Initialize page manager server instance and script context.
-     * 
-     * @throws Exception
-     */
-    public void initialize() throws Exception
-    {
-        // setup jetspeed test datasource and component manager
+    @Override
+    public void initialize() throws Exception {
+        // setup jetspeed test datasource
         jndiDS = new JetspeedTestJNDIComponent();
         jndiDS.setup();
-        final JetspeedBeanDefinitionFilter beanDefinitionFilter = new JetspeedBeanDefinitionFilter("default,jdbcDS");
-        final String [] bootConfigurations = new String[]{"boot/datasource.xml"};
-        final String [] configurations = new String[]{"database-page-manager.xml", "transaction.xml"};
-        baseDir = System.getProperty("basedir");
-        if ((baseDir == null) || (baseDir.length() == 0))
-        {
-            baseDir = System.getProperty("user.dir");
-        }
-        final String appRoot = baseDir+"/target/test-classes/webapp";
-        scm = new SpringComponentManager(beanDefinitionFilter, bootConfigurations, configurations, appRoot, false);
-        scm.start();
+
+        // initialize component manager and server
+        super.initialize();
 
         // access page manager
         pageManager = scm.lookupComponent("pageManager");
-        
-        // create jexl context
-        jexlContext = JexlHelper.createContext();
-        @SuppressWarnings("unchecked")
-        Map<String,Object> jexlContextVars = jexlContext.getVars();
-        jexlContextVars.put("pageManager", pageManager);
-        jexlContextVars.put("pageManagerServer", this);
 
         log.info( "DatabasePageManager server initialized");
     }
-    
-    /**
-     * Terminate page manager server instance.
-     * 
-     * @throws Exception
-     */
-    public void terminate() throws Exception
-    {
+
+    @Override
+    protected String getBeanDefinitionFilterCategories() {
+        return "default,jdbcDS";
+    }
+
+    @Override
+    protected String[] getBootConfigurations() {
+        return new String[]{"boot/datasource.xml"};
+    }
+
+    @Override
+    protected String[] getConfigurations() {
+        return new String[]{"database-page-manager.xml", "transaction.xml"};
+    }
+
+    @Override
+    protected Map<String,Object> getContextVars() {
+        Map<String,Object> contextVars = new HashMap<String,Object>();
+        contextVars.put("pageManager", scm.lookupComponent("pageManager"));
+        contextVars.put("pageManagerServer", this);
+        return contextVars;
+    }
+
+    @Override
+    public void terminate() throws Exception {
         // shutdown page manager
         pageManager.shutdown();
 
-        // tear down jetspeed component manager and test datasource
-        scm.stop();
+        // terminate component manager and server
+        super.terminate();
+
+        // tear down test datasource
         jndiDS.tearDown();
 
         log.info( "DatabasePageManager server terminated");
     }
-    
-    // Implementation
-    
-    /**
-     * Execute a single line script against page manager server context.
-     * 
-     * @param scriptLine jexl script
-     * @return script result line
-     */
-    public String execute(final String scriptLine)
-    {
-        // execute script line and return result line
-        String resultLine = scriptLine;
-        try
-        {
-            final Script jexlScript = ScriptFactory.createScript(scriptLine);
-            final Object result = jexlScript.execute(jexlContext);
-            if (result != null)
-            {
-                resultLine += " -> "+result;
+
+    @Override
+    public Subject getUserSubject() {
+        if ((userSubject == null) && (user != null)) {
+            Set<Principal> userPrincipals = new PrincipalsSet();
+            userPrincipals.add(new PageManagerTestShared.TestUser(user));
+            if (groups != null) {
+                String [] groupsArray = groups.split(",");
+                for (int i = 0; (i < groupsArray.length); i++) {
+                    userPrincipals.add(new PageManagerTestShared.TestGroup(groupsArray[i].trim()));
+                }
             }
+            if (roles != null) {
+                String [] rolesArray = roles.split(",");
+                for (int i = 0; (i < rolesArray.length); i++) {
+                    userPrincipals.add(new PageManagerTestShared.TestRole(rolesArray[i].trim()));
+                }
+            }
+            userSubject = new Subject(true, userPrincipals, new HashSet<Principal>(), new HashSet<Principal>());
         }
-        catch (final Exception e)
-        {
-            resultLine += " -> "+e;
-        }
-        return resultLine;
+        return userSubject;
     }
 
     /**
-     * Sets server exit flag.
-     */
-    public void exit()
-    {
-        exit = true;
-    }
-    
-    // Data access
-    
-    /**
-     * Get server exit flag.
-     * 
-     * @return server exit flag
-     */
-    public boolean isExit()
-    {
-        return exit;
-    }
-    
-    /**
      * Get user principal name.
      * 
      * @return user principal name
      */
-    public String getUser()
-    {
+    public String getUser() {
         return user;
     }
     
@@ -184,8 +137,7 @@ public class DatabasePageManagerServer
      * 
      * @param user user principal name
      */
-    public void setUser(String user)
-    {
+    public void setUser(String user) {
         this.user = user;
         this.userSubject = null;
     }
@@ -195,8 +147,7 @@ public class DatabasePageManagerServer
      * 
      * @return CSV list of group principal names
      */
-    public String getGroups()
-    {
+    public String getGroups() {
         return groups;
     }
 
@@ -205,8 +156,7 @@ public class DatabasePageManagerServer
      * 
      * @param groups CSV list of group principal names
      */
-    public void setGroups(String groups)
-    {
+    public void setGroups(String groups) {
         this.groups = groups;
         this.userSubject = null;
     }
@@ -216,8 +166,7 @@ public class DatabasePageManagerServer
      * 
      * @return CSV list of role principal names
      */
-    public String getRoles()
-    {
+    public String getRoles() {
         return roles;
     }
 
@@ -226,129 +175,20 @@ public class DatabasePageManagerServer
      * 
      * @param roles CSV list of role principal names
      */
-    public void setRoles(String roles)
-    {
+    public void setRoles(String roles) {
         this.roles = roles;
         this.userSubject = null;
     }
 
     /**
-     * Get or create and cache user subject.
-     * 
-     * @return user subject
-     */
-    public Subject getUserSubject()
-    {
-        if ((userSubject == null) && (user != null))
-        {
-            Set<Principal> userPrincipals = new PrincipalsSet();
-            userPrincipals.add(new PageManagerTestShared.TestUser(user));
-            if (groups != null)
-            {
-                String [] groupsArray = groups.split(",");
-                for (int i = 0; (i < groupsArray.length); i++)
-                {
-                    userPrincipals.add(new PageManagerTestShared.TestGroup(groupsArray[i].trim()));                                    
-                }
-            }
-            if (roles != null)
-            {
-                String [] rolesArray = roles.split(",");
-                for (int i = 0; (i < rolesArray.length); i++)
-                {
-                    userPrincipals.add(new PageManagerTestShared.TestRole(rolesArray[i].trim()));                                    
-                }
-            }
-            userSubject = new Subject(true, userPrincipals, new HashSet<Principal>(), new HashSet<Principal>());
-        }
-        return userSubject;
-    }
-    
-    // Application entry point
-    
-    /**
      * Server main entry point.
      * 
      * @param args not used
      */
-    public static void main(final String [] args)
-    {
-        try
-        {
-            // create and initialize server
-            final DatabasePageManagerServer server = new DatabasePageManagerServer();
-            server.initialize();
-            
-            // simple server reads script lines from standard
-            // input and writes results on standard output
-            final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
-            final PrintWriter out = new PrintWriter(System.out, true);
-            do
-            {
-                // read single line scripts to execute
-                String scriptLine = in.readLine();
-                if (scriptLine != null)
-                {
-                    scriptLine = scriptLine.trim();
-                    String resultLine = "";
-                    if (scriptLine.length() > 0)
-                    {
-                        // get user and execute script
-                        Subject userSubject = server.getUserSubject();
-                        if (userSubject != null)
-                        {                            
-                            // execute script as user
-                            final String executeScriptLine = scriptLine;
-                            final String [] executeResultLine = new String[]{null};
-                            Exception executeException = (Exception)JSSubject.doAsPrivileged(userSubject, new PrivilegedAction()
-                            {
-                                public Object run()
-                                {
-                                    try
-                                    {
-                                        executeResultLine[0] = server.execute(executeScriptLine);
-                                        return null;
-                                    }
-                                    catch (Exception e)
-                                    {
-                                        return e;
-                                    }
-                                    finally
-                                    {
-                                        JSSubject.clearSubject();
-                                    }
-                                }
-                            }, null);
-                            if (executeException != null)
-                            {
-                                throw executeException;
-                            }
-                            resultLine = executeResultLine[0];
-                        }
-                        else
-                        {
-                            // execute script anonymously
-                            resultLine = server.execute(scriptLine);
-                        }
-                    }
-
-                    // write prefixed single line results
-                    out.println(SCRIPT_RESULT_LINE_PREFIX+resultLine);
-                }
-                else
-                {
-                    // exit server on input EOF
-                    server.exit();
-                }
-            }
-            while (!server.isExit());
-            
-            // terminate server
-            server.terminate();
-        }
-        catch (final Throwable t)
-        {
-            log.error( "Unexpected exception: "+t, t);
+    public static void main(String [] args) {
+        Throwable error = (new DatabasePageManagerServer()).run();
+        if (error != null) {
+            log.error( "Unexpected exception: "+error, error);
         }
     }
 }

Modified: portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/TestDatabasePageManagerCache.java
URL: http://svn.apache.org/viewvc/portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/TestDatabasePageManagerCache.java?rev=1641403&r1=1641402&r2=1641403&view=diff
==============================================================================
--- portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/TestDatabasePageManagerCache.java (original)
+++ portals/jetspeed-2/portal/trunk/components/jetspeed-page-manager/src/test/java/org/apache/jetspeed/page/cache/TestDatabasePageManagerCache.java Mon Nov 24 15:01:25 2014
@@ -16,68 +16,73 @@
  */
 package org.apache.jetspeed.page.cache;
 
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.InputStreamReader;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-
 import junit.framework.Test;
-import junit.framework.TestCase;
 import junit.framework.TestSuite;
-
 import org.apache.jetspeed.cache.impl.EhCacheConfigResource;
+import org.apache.jetspeed.components.test.AbstractJexlSpringTestCase;
 import org.apache.jetspeed.om.page.FragmentProperty;
 import org.apache.jetspeed.page.PageManager;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.Map;
+
 /**
  * TestDatabasePageManagerCache
  * 
  * @author <a href="mailto:rwatler@apache.org">Randy Watler</a>
  * @version $Id: $
  */
-public class TestDatabasePageManagerCache extends TestCase
-{
+public class TestDatabasePageManagerCache extends AbstractJexlSpringTestCase {
+
     protected static Logger log = LoggerFactory.getLogger(TestDatabasePageManagerCache.class);
     
     private static final long CACHE_NOTIFICATION_STARTUP_WAIT = 10000;
     private static final long CACHE_NOTIFICATION_WAIT = 2000;
     private static final long CACHE_NOTIFICATION_POLL = 250;
-    private static final long CACHE_LOGGING_PUMP_WAIT = 50;
-    
-    // Members
-    
-    private String osExecutableExtension;
-    private String fileSeparator;
-    private File javaExecutablePath;
-    private String classPathSeparator;
-    private File projectDirectoryPath;
-    private Map<String,String> systemProperties;
-    private String classPath;
- 
-    // Test methods
-    
+
+    /**
+     * Creates the test suite.
+     *
+     * @return a test suite that includes all methods starting with "test"
+     */
+    public static Test suite() {
+        return new TestSuite(TestDatabasePageManagerCache.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        // setup cache properties
+        EhCacheConfigResource.getInstance(EhCacheConfigResource.EHCACHE_CONFIG_RESOURCE_DISTRIBUTED_CACHE, true);
+
+        // continue setup
+        super.setUp();
+    }
+
+    @Override
+    protected String testProgramSystemPropertyValueFilter(String propertyName, int index, String propertyValue) {
+        if (propertyName.equals(EhCacheConfigResource.EHCACHE_PORT_PROP_NAME)) {
+            return Integer.toString(Integer.parseInt(propertyValue)+index);
+        }
+        return propertyValue;
+    }
+
+    @Override
+    protected Map<String,String> testProgramSystemProperties() {
+        Map<String,String> systemProperties = super.testProgramSystemProperties();
+        systemProperties.put("log4j.configuration", "log4j-stdout.properties");
+        return systemProperties;
+    }
+
     /**
      * Tests distributed cache operation for DatabasePageManager
      */
-    public void testDatabasePageManagerCache()
-    {
+    public void testDatabasePageManagerCache() {
         String result;
 
         // check for distributed database support
         String databaseName = System.getProperty("org.apache.jetspeed.database.default.name");
-        if ((databaseName != null) && databaseName.equals("derby"))
-        {
+        if ((databaseName != null) && databaseName.equals("derby")) {
             System.out.println("Database support not distributed: system limitation... test skipped");
             log.warn("Database support not distributed: system limitation... test skipped");
             return;
@@ -86,8 +91,7 @@ public class TestDatabasePageManagerCach
         // create and start servers
         final TestProgram server0 = new TestProgram("server-0", DatabasePageManagerServer.class, 0);
         final TestProgram server1 = new TestProgram("server-1", DatabasePageManagerServer.class, 1);
-        try
-        {
+        try {
             // start servers
             server0.start();
             server1.start();
@@ -100,31 +104,25 @@ public class TestDatabasePageManagerCach
             boolean server0Distributed = false;
             boolean server1Distributed = false;
             final long distributedCheckStarted = System.currentTimeMillis();
-            do
-            {
+            do {
                 // check servers
-                if (!server0Distributed)
-                {
+                if (!server0Distributed) {
                     result = server0.execute("pageManager.isDistributed();");
                     assertTrue(!result.contains("Exception"));
                     server0Distributed = result.endsWith("true");
                 }
-                if (!server1Distributed)
-                {
+                if (!server1Distributed) {
                     result = server1.execute("pageManager.isDistributed();");
                     assertTrue(!result.contains("Exception"));
                     server1Distributed = result.endsWith("true");
                 }
                 
                 // wait if servers not distributed
-                if (!server0Distributed || !server1Distributed)
-                {
+                if (!server0Distributed || !server1Distributed) {
                     sleep(server0, server1, CACHE_NOTIFICATION_POLL);
                 }
-            }
-            while ((!server0Distributed || !server1Distributed) && (System.currentTimeMillis()-distributedCheckStarted < CACHE_NOTIFICATION_STARTUP_WAIT));
-            if (!server0Distributed && !server1Distributed)
-            {                
+            } while ((!server0Distributed || !server1Distributed) && (System.currentTimeMillis()-distributedCheckStarted < CACHE_NOTIFICATION_STARTUP_WAIT));
+            if (!server0Distributed && !server1Distributed) {
                 System.out.println("Server page managers not distributed: possible system limitation... test skipped");
                 log.warn("Server page managers not distributed: possible system limitation... test skipped");
                 return;
@@ -134,8 +132,7 @@ public class TestDatabasePageManagerCach
 
             // clean and setup database page managers
             result = server0.execute("removeRootFolder = pageManager.getFolder(\"/\");");
-            if (!result.contains("FolderNotFoundException"))
-            {
+            if (!result.contains("FolderNotFoundException")) {
                 result = server0.execute("pageManager.removeFolder(removeRootFolder);");
                 assertTrue(!result.contains("Exception"));
             }
@@ -371,71 +368,58 @@ public class TestDatabasePageManagerCach
             boolean deep1FolderRemoved = false;
             boolean rootFolderFoldersCountOne = false;
             long coherencyCheckStarted = System.currentTimeMillis();
-            do
-            {
+            do {
                 // reset request cache
                 result = server0.execute("pageManager.cleanupRequestCache();");
                 assertTrue(!result.contains("Exception"));
 
                 // check cache coherence
-                if (!defaultPageUpdated)
-                {
+                if (!defaultPageUpdated) {
                     result = server0.execute("pageManager.getPage(\"/default-page.psml\").getTitle();");
                     defaultPageUpdated = result.endsWith("Edited Default Page");
                 }
-                if (!anotherPageStateUpdated)
-                {
+                if (!anotherPageStateUpdated) {
                     result = server0.execute("pageManager.getPage(\"/another-page.psml\").getRootFragment().getState();");
                     anotherPageStateUpdated = result.endsWith("DEFAULT2");
                 }
-                if (!anotherPagePropertyUpdated)
-                {
+                if (!anotherPagePropertyUpdated) {
                     result = server0.execute("pageManager.getPage(\"/another-page.psml\").getRootFragment().getProperty(\"CUSTOM\");");
                     anotherPagePropertyUpdated = result.endsWith("CUSTOM2");
                 }
-                if (!someOtherPageRemoved)
-                {
+                if (!someOtherPageRemoved) {
                     result = server0.execute("pageManager.getPage(\"/some-other-page.psml\");");
                     someOtherPageRemoved = result.contains("PageNotFoundException");
                 }
-                if (!rootFolderPagesCountTwo)
-                {
+                if (!rootFolderPagesCountTwo) {
                     result = server0.execute("pageManager.getFolder(\"/\").getPages().size();");
                     rootFolderPagesCountTwo = result.endsWith("2");
                 }
-                if (!defaultLinkUpdated)
-                {
+                if (!defaultLinkUpdated) {
                     result = server0.execute("pageManager.getLink(\"/default.link\").getTitle();");
                     defaultLinkUpdated = result.endsWith("Edited Default Link");
                 }
-                if (!deep0FolderUpdated)
-                {
+                if (!deep0FolderUpdated) {
                     result = server0.execute("pageManager.getFolder(\"/deep-0\").getTitle();");
                     deep0FolderUpdated = result.endsWith("Edited Deep 0 Folder");
                 }
-                if (!deepPage1Removed)
-                {
+                if (!deepPage1Removed) {
                     result = server0.execute("pageManager.getPage(\"/deep-1/deep-page-1.psml\");");
                     deepPage1Removed = result.contains("PageNotFoundException");
                 }
-                if (!deep1FolderRemoved)
-                {
+                if (!deep1FolderRemoved) {
                     result = server0.execute("pageManager.getFolder(\"/deep-1\");");
                     deep1FolderRemoved = result.contains("FolderNotFoundException");
                 }
-                if (!rootFolderFoldersCountOne)
-                {
+                if (!rootFolderFoldersCountOne) {
                     result = server0.execute("pageManager.getFolder(\"/\").getFolders().size();");
                     rootFolderFoldersCountOne = result.endsWith("1");
                 }
                 
                 // wait for cache coherence
-                if (!defaultPageUpdated || !anotherPageStateUpdated || !anotherPagePropertyUpdated || !someOtherPageRemoved || !rootFolderPagesCountTwo || !defaultLinkUpdated || !deep0FolderUpdated || !deepPage1Removed || !deep1FolderRemoved || !rootFolderFoldersCountOne)
-                {
+                if (!defaultPageUpdated || !anotherPageStateUpdated || !anotherPagePropertyUpdated || !someOtherPageRemoved || !rootFolderPagesCountTwo || !defaultLinkUpdated || !deep0FolderUpdated || !deepPage1Removed || !deep1FolderRemoved || !rootFolderFoldersCountOne) {
                     sleep(server0, server1, CACHE_NOTIFICATION_POLL);
                 }
-            }
-            while ((!defaultPageUpdated || !anotherPageStateUpdated || !anotherPagePropertyUpdated || !someOtherPageRemoved || !rootFolderPagesCountTwo || !defaultLinkUpdated || !deep0FolderUpdated || !deepPage1Removed || !deep1FolderRemoved || !rootFolderFoldersCountOne) && (System.currentTimeMillis()-coherencyCheckStarted < CACHE_NOTIFICATION_WAIT));
+            } while ((!defaultPageUpdated || !anotherPageStateUpdated || !anotherPagePropertyUpdated || !someOtherPageRemoved || !rootFolderPagesCountTwo || !defaultLinkUpdated || !deep0FolderUpdated || !deepPage1Removed || !deep1FolderRemoved || !rootFolderFoldersCountOne) && (System.currentTimeMillis()-coherencyCheckStarted < CACHE_NOTIFICATION_WAIT));
             assertTrue(defaultPageUpdated);
             assertTrue(anotherPageStateUpdated);
             assertTrue(anotherPagePropertyUpdated);
@@ -499,46 +483,38 @@ public class TestDatabasePageManagerCach
             boolean newPageCreated = false;
             boolean deep2FolderCreated = false;
             coherencyCheckStarted = System.currentTimeMillis();
-            do
-            {
+            do {
                 // reset request cache
                 result = server1.execute("pageManager.cleanupRequestCache();");
                 assertTrue(!result.contains("Exception"));
                 
                 // check cache coherence
-                if (!defaultPageUserStateUpdated)
-                {
+                if (!defaultPageUserStateUpdated) {
                     result = server1.execute("pageManager.getPage(\"/default-page.psml\").getRootFragment().getState();");
                     defaultPageUserStateUpdated = result.endsWith("USER2");                    
                 }
-                if (!rootFolderPagesCountThree)
-                {
+                if (!rootFolderPagesCountThree) {
                     result = server1.execute("pageManager.getFolder(\"/\").getPages().size();");
                     rootFolderPagesCountThree = result.endsWith("3");
                 }
-                if (!rootFolderFoldersCountTwo)
-                {
+                if (!rootFolderFoldersCountTwo) {
                     result = server1.execute("pageManager.getFolder(\"/\").getFolders().size();");
                     rootFolderFoldersCountTwo = result.endsWith("2");
                 }
-                if (!newPageCreated)
-                {
+                if (!newPageCreated) {
                     result = server1.execute("pageManager.getPage(\"/new-page.psml\").getTitle();");
                     newPageCreated = result.endsWith("New Page");
                 }
-                if (!deep2FolderCreated)
-                {
+                if (!deep2FolderCreated) {
                     result = server1.execute("pageManager.getFolder(\"/deep-2\").getTitle();");
                     deep2FolderCreated = result.endsWith("Deep 2 Folder");
                 }
 
                 // wait for cache coherence
-                if (!defaultPageUserStateUpdated || !rootFolderPagesCountThree || !rootFolderFoldersCountTwo || !newPageCreated || !deep2FolderCreated)
-                {
+                if (!defaultPageUserStateUpdated || !rootFolderPagesCountThree || !rootFolderFoldersCountTwo || !newPageCreated || !deep2FolderCreated) {
                     sleep(server0, server1, CACHE_NOTIFICATION_POLL);
                 }
-            }
-            while ((!defaultPageUserStateUpdated || !rootFolderPagesCountThree || !rootFolderFoldersCountTwo || !newPageCreated || !deep2FolderCreated) && (System.currentTimeMillis()-coherencyCheckStarted < CACHE_NOTIFICATION_WAIT));
+            } while ((!defaultPageUserStateUpdated || !rootFolderPagesCountThree || !rootFolderFoldersCountTwo || !newPageCreated || !deep2FolderCreated) && (System.currentTimeMillis()-coherencyCheckStarted < CACHE_NOTIFICATION_WAIT));
             assertTrue(defaultPageUserStateUpdated);
             assertTrue(rootFolderPagesCountThree);
             assertTrue(rootFolderFoldersCountTwo);
@@ -568,8 +544,7 @@ public class TestDatabasePageManagerCach
             assertTrue(!result.contains("Exception"));
             result = server1.execute("pageManager.updateFragmentProperties(fragment, null);");
             assertTrue(!result.contains("Exception"));
-            if (FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED)
-            {
+            if (FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED) {
                 result = server1.execute("page = pageManager.getPage(\"/new-page.psml\");");
                 assertTrue(!result.contains("Exception"));
                 result = server1.execute("fragment = page.getRootFragment();");
@@ -592,8 +567,7 @@ public class TestDatabasePageManagerCach
             assertTrue(result.endsWith("USER3"));
             result = server1.execute("pageManager.getPage(\"/another-page.psml\").getRootFragment().getProperty(\"CUSTOM\");");
             assertTrue(result.endsWith("CUSTOM3"));
-            if (FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED)
-            {
+            if (FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED) {
                 result = server1.execute("pageManager.getPage(\"/new-page.psml\").getRootFragment().getProperty(\"GROUP-CUSTOM\");");
                 assertTrue(result.endsWith("GROUP-CUSTOM"));                
             }
@@ -601,39 +575,32 @@ public class TestDatabasePageManagerCach
             anotherPagePropertyUpdated = false;
             boolean newPagePropertyUpdated = false;
             coherencyCheckStarted = System.currentTimeMillis();
-            do
-            {
+            do {
                 // reset request cache
                 result = server0.execute("pageManager.cleanupRequestCache();");
                 assertTrue(!result.contains("Exception"));
                 
                 // check cache coherence
-                if (!defaultPageUserStateUpdated)
-                {
+                if (!defaultPageUserStateUpdated) {
                     result = server0.execute("pageManager.getPage(\"/default-page.psml\").getRootFragment().getState();");
                     defaultPageUserStateUpdated = result.endsWith("USER3");                    
                 }
-                if (!anotherPagePropertyUpdated)
-                {
+                if (!anotherPagePropertyUpdated) {
                     result = server0.execute("pageManager.getPage(\"/another-page.psml\").getRootFragment().getProperty(\"CUSTOM\");");
                     anotherPagePropertyUpdated = result.endsWith("CUSTOM3");
                 }
-                if (FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED)
-                {
-                    if (!newPagePropertyUpdated)
-                    {
+                if (FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED) {
+                    if (!newPagePropertyUpdated) {
                         result = server0.execute("pageManager.getPage(\"/new-page.psml\").getRootFragment().getProperty(\"GROUP-CUSTOM\");");
                         newPagePropertyUpdated = result.endsWith("GROUP-CUSTOM");
                     }                    
                 }
 
                 // wait for cache coherence
-                if (!defaultPageUserStateUpdated || !anotherPagePropertyUpdated || (!newPagePropertyUpdated && FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED))
-                {
+                if (!defaultPageUserStateUpdated || !anotherPagePropertyUpdated || (!newPagePropertyUpdated && FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED)) {
                     sleep(server0, server1, CACHE_NOTIFICATION_POLL);
                 }
-            }
-            while ((!defaultPageUserStateUpdated || !anotherPagePropertyUpdated || (!newPagePropertyUpdated && FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED)) && (System.currentTimeMillis()-coherencyCheckStarted < CACHE_NOTIFICATION_WAIT));
+            } while ((!defaultPageUserStateUpdated || !anotherPagePropertyUpdated || (!newPagePropertyUpdated && FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED)) && (System.currentTimeMillis()-coherencyCheckStarted < CACHE_NOTIFICATION_WAIT));
             assertTrue(defaultPageUserStateUpdated);
             assertTrue(anotherPagePropertyUpdated);
             assertTrue(newPagePropertyUpdated || !FragmentProperty.GROUP_AND_ROLE_PROPERTY_SCOPES_ENABLED);
@@ -655,286 +622,30 @@ public class TestDatabasePageManagerCach
             assertTrue(!result.contains("Exception"));
             result = server1.execute("pageManager.reset();");
             assertTrue(!result.contains("Exception"));
-        }
-        catch (final Exception e)
-        {
+        } catch (final Exception e) {
             log.error("Server test exception: "+e, e);
             fail( "Server test exception: "+e);            
-        }        
-        finally
-        {
+        } finally {
             // silently shutdown servers
-            try
-            {
-                server0.shutdown();
-            }
-            catch (final Exception e)
-            {
+            try {
+                server0.shutdown(CACHE_NOTIFICATION_STARTUP_WAIT);
+            } catch (final Exception e) {
                 log.error( "Server shutdown exception: "+e, e);
             }
-            try
-            {
-                server1.shutdown();
-            }
-            catch (final Exception e)
-            {
+            try {
+                server1.shutdown(CACHE_NOTIFICATION_STARTUP_WAIT);
+            } catch (final Exception e) {
                 log.error( "Server shutdown exception: "+e, e);
             }
         }
     }
     
-    private void sleep(TestProgram server0, TestProgram server1, long millis) throws IOException, InterruptedException
-    {
-        long slept = 0;
-        while (slept < millis)
-        {
-            // poll servers for logging
-            server0.poll();
-            server1.poll();
-            // sleep for interval
-            long sleep = Math.min(millis-slept, CACHE_LOGGING_PUMP_WAIT);
-            Thread.sleep(sleep);
-            slept += sleep;
-        }
-    }
-    
-    // Implementation classes
-    
-    protected class TestProgram
-    {
-        private String name;
-        private Class<?> mainClass;
-        private int index;
-
-        private Process process;
-        private BufferedWriter processInput;
-        private BufferedReader processOutput;
-        
-        public TestProgram(final String name, final Class<?> mainClass, final int index)
-        {
-            this.name = name;
-            this.mainClass = mainClass;
-            this.index = index;
-        }
-        
-        public synchronized void start() throws IOException
-        {
-            assertNull(process);
-
-            // configure launcher with paths, properties, and indexed properties
-            final ProcessBuilder launcher = new ProcessBuilder();
-            final List<String> commandAndArgs = new ArrayList<String>();
-            commandAndArgs.add(javaExecutablePath.getCanonicalPath());
-            for (Map.Entry<String,String> systemProperty : systemProperties.entrySet())
-            {
-                final String propertyName = systemProperty.getKey();
-                String propertyValue = systemProperty.getValue();
-                if (propertyName.equals(EhCacheConfigResource.EHCACHE_PORT_PROP_NAME))
-                {
-                    propertyValue = Integer.toString(Integer.parseInt(propertyValue)+index);
-                }
-                commandAndArgs.add( "-D"+propertyName+"="+propertyValue);
-            }
-            commandAndArgs.add("-Dlog4j.configuration=log4j-stdout.properties");
-            commandAndArgs.add("-classpath");
-            commandAndArgs.add(classPath);
-            commandAndArgs.add(mainClass.getName());
-            log.info("Launcher command for "+name+": "+commandAndArgs);
-            launcher.command(commandAndArgs);
-            launcher.directory(projectDirectoryPath);
-            launcher.redirectErrorStream(true);
-
-            // launch test programs
-            process = launcher.start();
-
-            // setup I/O for process
-            processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
-            processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
-
-            // read messages from process
-            for (String line; (processOutput.ready() && ((line = processOutput.readLine()) != null));)
-            {
-                logProcessLine(line);
-            }
-        }
-
-        public synchronized void poll() throws IOException
-        {
-            assertNotNull(process);
-
-            // read messages from process
-            for (String line; (processOutput.ready() && ((line = processOutput.readLine()) != null));)
-            {
-                logProcessLine(line);
-            }
-        }
-
-        public synchronized String execute(final String scriptLine) throws IOException
-        {
-            // poll to read messages from process
-            poll();
-
-            // write script line to process
-            processInput.write(scriptLine);
-            processInput.newLine();
-            processInput.flush();
-
-            // read result or messages from process
-            String resultLine = null;
-            for (String line; ((line = processOutput.readLine()) != null);)
-            {
-                if (! line.startsWith(DatabasePageManagerServer.SCRIPT_RESULT_LINE_PREFIX))
-                {
-                    logProcessLine(line);
-                }
-                else
-                {
-                    resultLine = line;
-                    break;
-                }
-            }
-            if ( resultLine == null)
-            {
-                throw new IOException("Unexpected EOF from process output");
-            }
-            return resultLine;
-        }
-        
-        public synchronized void shutdown() throws IOException, InterruptedException
-        {
-            assertNotNull( process);
-
-            // start thread to destroy process on timeout
-            final Thread destroyThread = new Thread(new Runnable()
-            {
-                public void run()
-                {
-                    try
-                    {
-                        Thread.sleep(CACHE_NOTIFICATION_STARTUP_WAIT);
-                        if ( process != null)
-                        {
-                            log.warn( "Forcibly stopping "+name);
-                            process.destroy();
-                        }
-                    }
-                    catch ( final Exception e)
-                    {
-                    }
-                }
-            }, "DestroyThread");
-            destroyThread.setDaemon( true);
-            destroyThread.start();
-
-            // close process input to shutdown server and read messages
-            processInput.close();
-            for (String line; ((line = processOutput.readLine()) != null);)
-            {
-                logProcessLine(line);
-            }
-
-            // join on process completion
-            process.waitFor();
-            processOutput.close();
-            process = null;
-
-            // join on destroy thread
-            destroyThread.interrupt();
-            destroyThread.join();
-        }
-        
-        private void logProcessLine(final String line)
-        {
-            if (line.contains("ERROR") || line.contains("Exception") || line.matches("\\s+at\\s.*"))
-            {
-                log.error("{"+name+"} "+line);
-            }
-            else
-            {
-                log.info("{"+name+"} "+line);                        
-            }
-        }
-    }
-    
-    // TestCase implementation
-    
-    /* (non-Javadoc)
-     * @see junit.framework.TestCase#setUp()
-     */
-    protected void setUp() throws Exception
-    {
-        // setup cache properties
-        EhCacheConfigResource.getInstance(EhCacheConfigResource.EHCACHE_CONFIG_RESOURCE_DISTRIBUTED_CACHE, true);
-        
-        // environment setup
-        osExecutableExtension = (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
-        fileSeparator = System.getProperty("file.separator");
-        javaExecutablePath = new File(System.getProperty("java.home")+fileSeparator+"bin"+fileSeparator+"java"+osExecutableExtension);
-        classPathSeparator = System.getProperty("path.separator");
-        projectDirectoryPath = new File(System.getProperty("basedir"));
-        systemProperties = new HashMap<String,String>();
-        for (final Map.Entry<Object,Object> systemProperty : System.getProperties().entrySet())
-        {
-            final String propertyName = systemProperty.getKey().toString();
-            final String propertyValue = systemProperty.getValue().toString();
-            if (propertyName.startsWith("org.apache.jetspeed.") || propertyName.startsWith("java.net.") || propertyName.equals("basedir"))
-            {
-                systemProperties.put(propertyName, propertyValue);
-            }
-        }
-
-        // construct launcher classpath from current class loader
-        final StringBuilder classPathBuilder = new StringBuilder();
-        final ClassLoader loader = this.getClass().getClassLoader();
-        assertTrue(loader instanceof URLClassLoader);
-        final URLClassLoader urlLoader = (URLClassLoader)loader;
-        assertNotNull(urlLoader.getURLs());
-        for (final URL pathURL : urlLoader.getURLs())
-        {
-            // convert path URL to file path
-            final String path = new File(pathURL.toURI()).getCanonicalPath();
-
-            // build class path
-            if (classPathBuilder.length() > 0)
-            {
-                classPathBuilder.append(classPathSeparator);
-            }
-            classPathBuilder.append(path);
-        }
-        classPath = classPathBuilder.toString();
-        assertTrue(classPath.length() > 0);
-
-        // continue setup
-        super.setUp();
-    }
-
-    /* (non-Javadoc)
-     * @see junit.framework.TestCase#tearDown()
-     */
-    protected void tearDown() throws Exception
-    {
-        super.tearDown();
-    }
-    
-    // Application entry point
-
     /**
      * Start the tests.
      * 
      * @param args not used
      */
-    public static void main(final String [] args)
-    {
+    public static void main(final String [] args) {
         junit.awtui.TestRunner.main(new String[]{TestDatabasePageManagerCache.class.getName()});
     }
-
-    /**
-     * Creates the test suite.
-     * 
-     * @return a test suite that includes all methods starting with "test"
-     */
-    public static Test suite()
-    {
-        return new TestSuite(TestDatabasePageManagerCache.class);
-    }
 }



---------------------------------------------------------------------
To unsubscribe, e-mail: jetspeed-dev-unsubscribe@portals.apache.org
For additional commands, e-mail: jetspeed-dev-help@portals.apache.org


Mime
View raw message