portals-jetspeed-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dlest...@apache.org
Subject svn commit: r209328 [12/14] - in /portals/jetspeed-2/trunk/components/portal: src/ src/java/ src/java/org/ src/java/org/apache/ src/java/org/apache/jetspeed/ src/java/org/apache/jetspeed/aggregator/ src/java/org/apache/jetspeed/aggregator/impl/ src/jav...
Date Tue, 05 Jul 2005 21:55:50 GMT
Added: portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,629 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed 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.velocity;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.portlet.PortletConfig;
+import javax.portlet.PortletMode;
+import javax.portlet.PortletRequest;
+import javax.portlet.RenderRequest;
+import javax.portlet.RenderResponse;
+import javax.portlet.WindowState;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.collections.ExtendedProperties;
+import org.apache.commons.collections.map.LRUMap;
+import org.apache.commons.configuration.Configuration;
+import org.apache.commons.configuration.ConfigurationException;
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.jetspeed.Jetspeed;
+import org.apache.jetspeed.PortalReservedParameters;
+import org.apache.jetspeed.capabilities.CapabilityMap;
+import org.apache.jetspeed.components.ComponentManager;
+import org.apache.jetspeed.locator.LocatorDescriptor;
+import org.apache.jetspeed.locator.TemplateDescriptor;
+import org.apache.jetspeed.locator.TemplateLocator;
+import org.apache.jetspeed.locator.TemplateLocatorException;
+import org.apache.jetspeed.om.page.Fragment;
+import org.apache.jetspeed.om.page.Page;
+import org.apache.jetspeed.request.RequestContext;
+import org.apache.pluto.Constants;
+import org.apache.portals.bridges.velocity.BridgesVelocityViewServlet;
+import org.apache.velocity.Template;
+import org.apache.velocity.app.VelocityEngine;
+import org.apache.velocity.context.Context;
+import org.apache.velocity.exception.ParseErrorException;
+import org.apache.velocity.exception.ResourceNotFoundException;
+import org.apache.velocity.runtime.RuntimeServices;
+import org.apache.velocity.runtime.log.LogSystem;
+
+/**
+ * @version $Id: JetspeedVelocityViewServlet.java 188385 2005-03-09 19:04:58Z taylor $
+ */
+public class JetspeedVelocityViewServlet extends BridgesVelocityViewServlet
+{
+    /** logging */
+    private static final Log log = LogFactory.getLog(JetspeedVelocityViewServlet.class);
+
+    /** default cache size */
+    private static final long DEFAULT_CACHE_SIZE = 50;
+
+    /** default cache validation interval */
+    private static final String CACHE_SIZE_PARAMETER = "org.apache.jetspeed.cache.size";
+
+    /** default cache validation interval */
+    private static final long DEFAULT_CACHE_VALIDATION_INTERVAL = 10000;
+
+    /** default cache validation interval */
+    private static final String CACHE_VALIDATION_INTERVAL_PARAMETER = "org.apache.jetspeed.cache.validation.interval";
+
+    /** TLS for Context propagation */
+    private static ThreadLocal handlingRequestContext = new ThreadLocal();
+
+    /** decoration locators */
+    private TemplateLocator decorationLocator;
+
+    /** velocity engine configuration caching object */
+    private class VelocityEngineConfig
+    {
+        public String decoration;
+        public String type;
+        public String mediaType;
+        public String language;
+        public String country;
+
+        public File macros;
+        public long macrosLastModified;
+        public long lastValidated;
+
+        public VelocityEngineConfig(String decoration, String type, String mediaType, String language, String country)
+        {
+            this.decoration = decoration;
+            this.type = type;
+            this.mediaType = mediaType;
+            this.language = language;
+            this.country = country;
+            
+            this.macrosLastModified = -1;
+            this.lastValidated = System.currentTimeMillis();
+        }
+    }
+
+    /** VelocityEngine configuration cache by decoration */
+    private Map velocityEngineConfigCache;
+
+    /** VelocityEngine cache by macros locators */
+    private Map velocityEngineCache;
+
+    /** cache validation interval */
+    private long cacheValidationInterval;
+
+    /**
+     * Initialize servlet, BridgesVelocityViewServlet, and VelocityViewServlet.
+     *
+     * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.init()
+     *
+     * @param config servlet configuation
+     */
+    public void init(ServletConfig config) throws ServletException
+    {
+        // initialize
+        super.init(config);
+
+        // get jetspeed component manager configuration for decorations
+        ComponentManager cm = Jetspeed.getComponentManager();
+        if (null == cm)  // TODO: retry loop 
+            throw new ServletException("Could not get Jetspeed Component Manager");
+        
+        decorationLocator = (TemplateLocator) cm.getComponent("DecorationLocator");
+
+        // initialize thread safe velocity engine cache
+        int cacheSize = (int) getLongInitParameter(config, CACHE_SIZE_PARAMETER, DEFAULT_CACHE_SIZE);
+        velocityEngineConfigCache = new LRUMap(cacheSize);
+        velocityEngineCache = new LRUMap(cacheSize/2);
+
+        // initialize velocity engine cache validation interval
+        cacheValidationInterval = getLongInitParameter(config, CACHE_VALIDATION_INTERVAL_PARAMETER, DEFAULT_CACHE_VALIDATION_INTERVAL);
+    }
+
+    /**
+     * Handle the template processing request.
+     *
+     * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.handleRequest()
+     *
+     * @param request client request
+     * @param response client response
+     * @param ctx  VelocityContext to fill
+     * @return Velocity Template object or null
+     */
+    protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) throws Exception
+    {
+        // configure velocity context
+        PortletRequest renderRequest = (PortletRequest) request.getAttribute(Constants.PORTLET_REQUEST);
+        RenderResponse renderResponse = (RenderResponse) request.getAttribute(Constants.PORTLET_RESPONSE);
+        PortletConfig portletConfig = (PortletConfig) request.getAttribute(Constants.PORTLET_CONFIG);
+        if (renderRequest != null)
+        {
+            renderRequest.setAttribute(VELOCITY_CONTEXT_ATTR, ctx);
+        }
+        
+        RequestContext requestContext = (RequestContext)request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE);
+        if(requestContext == null)
+        {
+            throw new IllegalStateException("JetspeedVelocityViewServlet unable to handle request because there is no RequestContext in "+
+                   "the HttpServletRequest.");
+        }
+        
+        JetspeedPowerTool jpt = (JetspeedPowerTool) renderRequest.getAttribute(PortalReservedParameters.JETSPEED_POWER_TOOL_REQ_ATTRIBUTE);
+        if(jpt == null)
+        {
+            throw new IllegalStateException("JetspeedVelocityViewServlet unable to handle request because there is no JetspeedPowerTool in "+
+                   "the HttpServletRequest.");
+        }
+        
+        ctx.put("jetspeed", jpt);  
+        ctx.put("JS2RequestContext", requestContext);
+        ctx.put("renderRequest", renderRequest);
+        ctx.put("renderResponse", renderResponse);
+        ctx.put("portletConfig", portletConfig);
+        ctx.put("portletModeView", PortletMode.VIEW);
+        ctx.put("portletModeEdit", PortletMode.EDIT);
+        ctx.put("portletModeHelp", PortletMode.HELP);
+        ctx.put("windowStateNormal", WindowState.NORMAL);
+        ctx.put("windowStateMinimized", WindowState.MINIMIZED);
+        ctx.put("windowStateMaximized", WindowState.MAXIMIZED);
+        StringBuffer appRoot = new StringBuffer(request.getScheme()).append("://")
+                                   .append(request.getServerName()).append(":")
+                                   .append(request.getServerPort()).append(renderRequest.getContextPath());
+        ctx.put("appRoot", appRoot.toString());        
+        
+        
+        // setup TLS for Context propagation
+        handlingRequestContext.set(ctx);
+
+        // handle request normally
+        return super.handleRequest(request, response, ctx);
+    }
+
+    /**
+     * Retrieves the requested template.
+     *
+     * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.getTemplate()
+     *
+     * @param name The file name of the template to retrieve relative to the template root.
+     * @return The requested template.
+     * @throws ResourceNotFoundException if template not found from any available source.
+     * @throws ParseErrorException if template cannot be parsed due to syntax (or other) error.
+     * @throws Exception if an error occurs in template initialization
+     */
+    public Template getTemplate(String name)
+        throws ResourceNotFoundException, ParseErrorException, Exception
+    {
+        // retrieve Context to lookup appropriate velocity engine
+        Context ctx = (Context) handlingRequestContext.get();
+        if (ctx != null)
+        {
+            // create or lookup cached velocity engine
+            VelocityEngine velocity = getVelocityEngine(ctx);
+            if (velocity != null)
+            {
+                // get template from velocity engine
+                return velocity.getTemplate(name);
+            }
+        }
+
+        // fallback to global velocity engine singleton
+        return super.getTemplate(name);
+    }
+
+    /**
+     * Retrieves the requested template with the specified character encoding.
+     *
+     * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.getTemplate()
+     *
+     * @param name The file name of the template to retrieve relative to the template root.
+     * @param encoding the character encoding of the template
+     * @return The requested template.
+     * @throws ResourceNotFoundException if template not found from any available source.
+     * @throws ParseErrorException if template cannot be parsed due to syntax (or other) error.
+     * @throws Exception if an error occurs in template initialization
+     */
+    public Template getTemplate(String name, String encoding)
+        throws ResourceNotFoundException, ParseErrorException, Exception
+    {
+        // retrieve Context to lookup appropriate velocity engine
+        Context ctx = (Context) handlingRequestContext.get();
+        if (ctx != null)
+        {
+            // create or lookup cached velocity engine
+            VelocityEngine velocity = getVelocityEngine(ctx);
+            if (velocity != null)
+            {
+                // get template from velocity engine
+                return velocity.getTemplate(name, encoding);
+            }
+        }
+
+        // fallback to global velocity engine singleton
+        return super.getTemplate(name, encoding);
+    }
+
+    /** velocity engine logging adapter */
+    private static class VelocityEngineLogger implements LogSystem
+    {
+        /** velocity log */
+        private static final Log velocityLog = LogFactory.getLog("velocity");
+
+        /**
+         * init
+         *
+         * @see org.apache.velocity.runtime.log.LogSystem.init(org.apache.velocity.runtime.RuntimeServices)
+         */
+        public void init(RuntimeServices rsvc)
+        {
+        }
+        
+        /**
+         * logVelocityMessage
+         *
+         * @see org.apache.velocity.runtime.log.LogSystem.logVelocityMessage(int, java.lang.String)
+         */
+        public void logVelocityMessage(int level, String message)
+        {
+            switch (level)
+            {
+                case LogSystem.DEBUG_ID :
+                    velocityLog.debug(message);
+                    break;
+                case LogSystem.INFO_ID :
+                    velocityLog.info(message);
+                    break;
+                case LogSystem.WARN_ID :
+                    velocityLog.warn(message);
+                    break;
+                case LogSystem.ERROR_ID :
+                    velocityLog.error(message);
+                    break;
+                default :
+                    velocityLog.trace(message);
+                    break;
+            }
+        }
+    }
+
+    /**
+     * Loads Velocity configuration information and returns that 
+     * information as an ExtendedProperties, which will be used to 
+     * initialize the Velocity runtime.
+     *
+     * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.loadConfiguration()
+     *
+     * @param config ServletConfig passed to the servlets init() function.
+     * @return ExtendedProperties loaded with Velocity runtime configuration values.
+     * @throws IOException I/O problem accessing the specified file, if specified.
+     */
+    protected ExtendedProperties loadConfiguration(ServletConfig config)
+        throws IOException
+    {
+        // configure Velocity engines for using logging adapter
+        ExtendedProperties configuration = super.loadConfiguration(config);
+        configuration.clearProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS);
+        configuration.clearProperty("runtime.log.logsystem.log4j.category");
+        configuration.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new VelocityEngineLogger());
+        return configuration;
+    }
+
+    /**
+     * Get VelocityEngine for template access.
+     *
+     * @param ctx the velocity context.
+     * @return The VelocityEngine or null.
+     */
+    private VelocityEngine getVelocityEngine(Context ctx)
+    {
+        // get render request and request context from Context
+        RenderRequest renderRequest = (RenderRequest) ctx.get("renderRequest");
+        RequestContext requestContext = (RequestContext) ctx.get("JS2RequestContext");
+        JetspeedPowerTool jpt = (JetspeedPowerTool) ctx.get("jetspeed");
+        if ((renderRequest != null) && (requestContext != null))
+        {
+            // get layout type and decoration, fallback to
+            // page default decorations
+            Fragment layout = (Fragment) renderRequest.getAttribute(JetspeedPowerTool.LAYOUT_ATTR);
+            if (layout == null)
+            {
+               // layout = (Fragment) renderRequest.getAttribute(JetspeedPowerTool.FRAGMENT_ATTR);
+                layout = jpt.getCurrentFragment();
+            }
+            String layoutType = layout.getType();
+            String layoutDecoration = layout.getDecorator();
+            if (layoutDecoration == null)
+            {
+                //Page page = (Page) renderRequest.getAttribute(PortalReservedParameters.PAGE_ATTRIBUTE_KEY);
+                Page page = requestContext.getPage();
+                layoutDecoration = page.getDefaultDecorator(layoutType);
+            }
+            
+            // get layout capabilites and locale
+            CapabilityMap capabilityMap = requestContext.getCapabilityMap();
+            Locale locale = requestContext.getLocale();
+            String layoutMediaType = capabilityMap.getPreferredMediaType().getName();
+            String layoutLanguage = locale.getLanguage();
+            String layoutCountry = locale.getCountry();
+            
+            // lookup cache config based on decoration cache key
+            String cacheKey = layoutDecoration + ":" + layoutType + ":" + layoutMediaType + ":" + layoutLanguage + ":" + layoutCountry;
+            VelocityEngineConfig config = null;
+            synchronized (velocityEngineConfigCache)
+            {
+               config = (VelocityEngineConfig) velocityEngineConfigCache.get(cacheKey);
+            }
+            
+            // validate cached configuration and return VelocityEngine if cached
+            long now = System.currentTimeMillis();
+            if ((config != null) && (now <= (config.lastValidated + cacheValidationInterval))) 
+            {
+                if (config.macros != null)
+                {
+                    synchronized (velocityEngineCache)
+                    {
+                        // use cached velocity engine if available
+                        VelocityEngine velocity = (VelocityEngine) velocityEngineCache.get(config.macros.getAbsolutePath());
+                        if (velocity != null)
+                        {
+                            return velocity;
+                        }
+                    }
+                }
+                else
+                {
+                    return null;
+                }
+            }
+            
+            // load and/or verify decorator macros configuration
+            TemplateDescriptor macrosDescriptor = null;
+            
+            // create reusable decoration base descriptor
+            LocatorDescriptor descriptor = null;
+            try
+            {
+                descriptor = decorationLocator.createLocatorDescriptor(null);
+            }
+            catch (TemplateLocatorException tle)
+            {
+                log.error("getVelocityEngine(): unable create base descriptor", tle);
+            }
+            descriptor.setMediaType(layoutMediaType);
+            descriptor.setCountry(layoutCountry);
+            descriptor.setLanguage(layoutLanguage);
+            descriptor.setType(layoutType);
+            
+            // get decoration configuration properties descriptor
+            descriptor.setName(layoutDecoration + "/" + JetspeedPowerTool.DECORATOR_TYPE + ".properties");
+            TemplateDescriptor propertiesDescriptor = null;
+            try
+            {
+                propertiesDescriptor = decorationLocator.locateTemplate(descriptor);
+            }
+            catch (TemplateLocatorException tle)
+            {
+                // fallback to generic template type
+                try
+                {
+                    descriptor.setType(JetspeedPowerTool.GENERIC_TEMPLATE_TYPE);
+                    propertiesDescriptor = decorationLocator.locateTemplate(descriptor);
+                }
+                catch (TemplateLocatorException tleFallback)
+                {
+                }
+            }
+            // load configuration properties
+            Configuration configuration = null;
+            if (propertiesDescriptor != null)
+            {
+                try
+                {
+                    configuration = new PropertiesConfiguration(propertiesDescriptor.getAbsolutePath());
+                }
+                catch (ConfigurationException ce)
+                {
+                    log.warn("getVelocityEngine(): unable read decorator properties from " + propertiesDescriptor.getAbsolutePath(), ce);
+                }
+            }
+            if (configuration != null)
+            {
+                // get decoration template macros extension and suffix
+                String ext = configuration.getString("template.extension");
+                String macros = configuration.getString("template.macros");
+                
+                // get decoration template macros descriptor if defined
+                if ((ext != null) && (ext.length() > 0) && (macros != null) && (macros.length() > 0))
+                {
+                    descriptor.setName(layoutDecoration + "/" + JetspeedPowerTool.DECORATOR_TYPE + macros + ext);
+                    try
+                    {
+                        macrosDescriptor = decorationLocator.locateTemplate(descriptor);
+                    }
+                    catch (TemplateLocatorException tle)
+                    {
+                        // fallback to extends decoration, (assume macros named the
+                        // same in the parent decoration as configured here)
+                        try
+                        {
+                            String parent = configuration.getString("extends");
+                            if ((parent != null) && (parent.length() > 0))
+                            {
+                                descriptor.setName(parent + "/" + JetspeedPowerTool.DECORATOR_TYPE + macros + ext);
+                                macrosDescriptor = decorationLocator.locateTemplate(descriptor);
+                            }
+                        }
+                        catch (TemplateLocatorException tleExtends)
+                        {
+                        }
+                    }
+                }
+            }
+            
+            // compare located macros file with cached version
+            // to validate/refresh cached config and velocity engine
+            boolean newVelocityEngineConfig = false;
+            boolean forceVelocityEngineRefresh = false;
+            if (config == null)
+            {
+                config = new VelocityEngineConfig(layoutDecoration, layoutType, layoutMediaType, layoutLanguage, layoutCountry);
+                synchronized (velocityEngineConfigCache)
+                {
+                    velocityEngineConfigCache.put(cacheKey, config);
+                }
+                newVelocityEngineConfig = true;
+            }
+            if (((macrosDescriptor == null) && (config.macros != null)) ||
+                ((macrosDescriptor != null) && (config.macros == null)) ||
+                ((macrosDescriptor != null) && (config.macros != null) &&
+                 (!macrosDescriptor.getAbsolutePath().equals(config.macros.getAbsolutePath()) ||
+                  (config.macros.lastModified() != config.macrosLastModified))))
+            {
+                // set or reset configuration cache entry
+                config.lastValidated = now;
+                if (macrosDescriptor != null)
+                {
+                    // save macros file
+                    config.macros = new File(macrosDescriptor.getAbsolutePath());
+                    config.macrosLastModified = config.macros.lastModified();
+                }
+                else
+                {
+                    // clear macros file
+                    config.macros = null;
+                    config.macrosLastModified = -1;
+                }
+
+                // aggressively force creation of new velocity engine
+                // if any configuration change detected
+                forceVelocityEngineRefresh = !newVelocityEngineConfig;
+            }
+            else
+            {
+                // config validated
+                config.lastValidated = now;
+            }
+
+            // get or create new velocity engine intialized with
+            // validated macros configuration
+            VelocityEngine velocity = null;
+            if ((macrosDescriptor != null) && (config.macros != null))
+            {
+                synchronized (velocityEngineCache)
+                {
+                    if (!forceVelocityEngineRefresh)
+                    {
+                        // use cached velocity engine
+                        velocity = (VelocityEngine) velocityEngineCache.get(config.macros.getAbsolutePath());
+                    }
+                    if (velocity == null)
+                    {
+                        // create and cache new velocity engine
+                        velocity = initVelocity(macrosDescriptor);
+                        if (velocity != null)
+                        {
+                            velocityEngineCache.put(config.macros.getAbsolutePath(), velocity);
+                        }
+                    }
+                }
+            }
+            
+            // return velocity engine for validated configuration
+            return velocity;
+        }
+        return null;
+    }
+
+    /**
+     * Initialize new velocity instance using specified macros template.
+     *
+     * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.initVelocity()
+     *
+     * @param macros template descriptor.
+     * @return new VelocityEngine instance.
+     */
+    private VelocityEngine initVelocity(TemplateDescriptor macros)
+    {
+        try
+        {
+            // create new instance to initialize
+            VelocityEngine velocity = new VelocityEngine();
+            
+            // initialize new instance as is done with the default
+            // velocity singleton, appending macros template to the
+            // base configuration velocimacro.library property
+            velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, getServletContext());
+            velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.tools.view.servlet.ServletLogger");
+            velocity.setProperty(VelocityEngine.RESOURCE_LOADER, "webapp");
+            velocity.setProperty("webapp.resource.loader.class", "org.apache.velocity.tools.view.servlet.WebappLoader");
+            ExtendedProperties configuration = loadConfiguration(getServletConfig());
+            configuration.addProperty("velocimacro.library", macros.getAppRelativePath());
+            velocity.setExtendedProperties(configuration);
+
+            // initialize and return velocity engine
+            velocity.init();
+            log.debug("initVelocity(): create new VelocityEngine instance to support " + macros.getAppRelativePath() + " decoration template macros");
+            return velocity;
+        }
+        catch (Exception e)
+        {
+            log.error("initVelocity(): unable to initialize velocity engine instance, using default singleton", e);
+        }
+        return null;
+    }
+
+    /**
+     * Utility to get long init parameters.
+     *
+     * @param config servlet config
+     * @param name of init parameter
+     * @param defaultValue value
+     * @return parameter value
+     */
+    private long getLongInitParameter(ServletConfig config, String name, long defaultValue)
+    {
+        String value = config.getInitParameter(name);
+        if ((value == null) || (value.length() == 0))
+        {
+            value = config.getServletContext().getInitParameter(name);
+        }
+        if ((value != null) && (value.length() > 0))
+        {
+            try
+            {
+                return Long.parseLong(value);
+            }
+            catch (Exception e)
+            {
+            }
+        }
+        return defaultValue;
+    }
+}

Added: portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/PageActionAccess.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/PageActionAccess.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/PageActionAccess.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/PageActionAccess.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,170 @@
+/*
+ * Copyright 2000-2001,2004 The Apache Software Foundation.
+ * 
+ * Licensed 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.velocity;
+
+import java.io.Serializable;
+import java.security.AccessControlException;
+import java.security.AccessController;
+import java.util.HashMap;
+
+import javax.portlet.PortletMode;
+import javax.portlet.WindowState;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.jetspeed.JetspeedActions;
+import org.apache.jetspeed.om.page.Page;
+import org.apache.jetspeed.security.PortletPermission;
+
+/**
+ * PageActionAccess
+ *
+ * @author <a href="mailto:ate@douma.nu">Ate Douma</a>
+ * @version $Id: PageActionAccess.java 188506 2005-04-21 08:50:37Z ate $
+ */
+public class PageActionAccess implements Serializable
+{
+    protected static final Log log = LogFactory.getLog(PageActionAccess.class);
+
+    private static final class ActionAccess implements Serializable
+    {
+        int checkedFlags;
+        int actionFlags;
+    }
+    
+    private boolean anonymous;
+    private boolean editAllowed;
+    private HashMap fragmentActionAccess;
+    
+    public PageActionAccess(boolean anonymous, Page page)
+    {
+        this.anonymous = anonymous;        
+        this.editAllowed = checkEditPage(page);
+        this.fragmentActionAccess = new HashMap();
+    }
+    
+    public void checkReset(boolean anonymous, Page page)
+    {
+        if (this.anonymous != anonymous)
+        {
+            this.anonymous = anonymous;
+            this.editAllowed = checkEditPage(page);
+            this.fragmentActionAccess.clear();
+        }
+    }
+    
+    public boolean isAnonymous()
+    {
+        return anonymous;
+    }
+    
+    public boolean isEditAllowed()
+    {
+        return editAllowed;
+    }
+    
+    public boolean checkPortletMode(String fragmentId, String portletName, PortletMode mode)
+    {
+        return checkActionAccess(fragmentId, portletName, mode.toString());
+    }
+
+    public boolean checkWindowState(String fragmentId, String portletName, WindowState state)
+    {
+        return checkActionAccess(fragmentId, portletName, state.toString());
+    }
+    
+    protected synchronized boolean checkActionAccess(String fragmentId, String portletName, String action)
+    {
+        try
+        {
+            int actionIndex = getActionMask(action);
+            ActionAccess actionAccess = (ActionAccess)fragmentActionAccess.get(fragmentId);
+            if ( actionAccess == null )
+            {
+                actionAccess = new ActionAccess();
+                fragmentActionAccess.put(fragmentId, actionAccess);
+            }
+            if ( (actionAccess.checkedFlags & actionIndex) != actionIndex )
+            {
+                // TODO: not handling PortletPermission checks yet 
+                // boolean access = checkPermission(portletName, action);
+                boolean access = true;
+
+                if ( access )
+                {
+                    actionAccess.actionFlags |= actionIndex;
+                }
+                actionAccess.checkedFlags |= actionIndex;            
+            }
+            return ((actionAccess.actionFlags & actionIndex) == actionIndex);
+        }
+        catch (IndexOutOfBoundsException e)
+        {
+            log.error("Unknown action: "+action, e);
+            return false;
+        }
+    }
+    
+    /**
+     * Determines whether the access request indicated by the specified
+     * permission should be allowed or denied, based on the security policy
+     * currently in effect.
+     * 
+     * @param resource
+     *                  The fully qualified resource name of the portlet
+     *                  (PA::portletName)
+     * @param action
+     *                  The action to perform on this resource (i.e. view, edit, help,
+     *                  max, min...)
+     * @return true if the action is allowed, false if it is not
+     */
+    protected boolean checkPermission( String resource, String action )
+    {
+        try
+        {
+            // TODO: it may be better to check the PagePermission for the outer
+            // most
+            // fragment (i.e. the PSML page)
+            AccessController.checkPermission(new PortletPermission(resource, action));
+        }
+        catch (AccessControlException e)
+        {
+            return false;
+        }
+        return true;
+    }
+    
+    protected boolean checkEditPage(Page page)
+    {
+        boolean allowed = false;
+        try
+        {
+            page.checkAccess(Page.EDIT_ACTION);
+            allowed = true;
+        }       
+        catch (SecurityException se) {}
+        return allowed;
+    }
+
+    protected int getActionMask(String action)
+    throws IndexOutOfBoundsException
+    {
+        int i = 0;
+        // will throw IndexOutOfBoundsExceptions on unknown action
+        while ( !JetspeedActions.ACTIONS[i++].equals(action) ) ;
+        return 1<<i;
+    }
+}

Added: portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,67 @@
+/*
+ * Created on Jul 28, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Generation - Code and Comments
+ */
+package org.apache.jetspeed.velocity;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.velocity.tools.view.tools.ViewTool;
+
+/**
+ * <p>
+ * ContentTool
+ * </p>
+ * <p>
+ *
+ * </p>
+ * @author <a href="mailto:weaver@apache.org">Scott T. Weaver</a>
+ * @version $Id: RemoteContentTool.java 187163 2004-08-01 15:51:27Z weaver $
+ *
+ */
+public class RemoteContentTool implements ViewTool
+{
+
+    /**
+     * <p>
+     * init
+     * </p>
+     *
+     * @see org.apache.velocity.tools.view.tools.ViewTool#init(java.lang.Object)
+     * @param arg0
+     */
+    public void init( Object arg0 )
+    {
+        
+        
+    }
+    
+    public String include(String remoteContentUrl)
+    {
+        GetMethod remoteContentGet = null;
+        
+        try
+        {
+            HttpClient client = new HttpClient();
+            remoteContentGet = new GetMethod(remoteContentUrl);
+            client.executeMethod(remoteContentGet);
+            return remoteContentGet.getResponseBodyAsString();
+        }
+        catch (Exception e)
+        {
+            return e.toString()+" message:"+ e.getMessage();
+        }
+        finally
+        {
+            if(remoteContentGet != null)
+            {
+                remoteContentGet.releaseConnection();
+            }
+        }
+    }
+
+ 
+
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2000-2001,2004 The Apache Software Foundation.
+ * 
+ * Licensed 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;
+
+import org.apache.jetspeed.components.util.RegistrySupportedTestCase;
+import org.apache.jetspeed.container.JetspeedPortletContainerWrapper;
+import org.apache.jetspeed.container.window.PortletWindowAccessor;
+import org.apache.jetspeed.container.window.impl.PortletWindowAccessorImpl;
+import org.apache.pluto.PortletContainer;
+import org.apache.pluto.PortletContainerImpl;
+
+/**
+ * @author <a href="mailto:sweaver@einnovation.com">Scott T. Weaver</a>
+ *
+ */
+public class AbstractPortalContainerTestCase extends RegistrySupportedTestCase
+{
+
+    protected PortletWindowAccessor windowAccessor;
+    protected PortletContainer portletContainer;
+    
+    /* (non-Javadoc)
+     * @see junit.framework.TestCase#setUp()
+     */
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+        windowAccessor = new PortletWindowAccessorImpl(entityAccess, true);
+        portletContainer = new JetspeedPortletContainerWrapper(new PortletContainerImpl());
+    }
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2000-2001,2004 The Apache Software Foundation.
+ * 
+ * Licensed 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;
+
+/**
+ * <p>
+ * Constants used for test cases.
+ * </p>
+ * 
+ * @author <a href="mailto:dlestrat@apache.org">David Le Strat</a>
+ */
+public class PortalTestConstants
+{
+    public final static String JETSPEED_PROPERTIES_PATH = "../../portal-webapp/src/webapp/WEB-INF/conf/jetspeed.properties";
+    
+    public final static String PORTAL_WEBAPP_PATH = "../../portal-webapp/src/webapp";
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed 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.aggregator;
+
+import java.util.ArrayList;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.jetspeed.aggregator.impl.PageAggregatorImpl;
+import org.apache.jetspeed.aggregator.impl.PortletAggregatorImpl;
+
+/**
+ * <P>Test the aggregation service</P>
+ *
+ * @author <a href="mailto:david@bluesunrise.com">David Sean Taylor</a>
+ * @version $Id: TestAggregator.java 187850 2004-10-29 14:33:27Z weaver $
+ * 
+ */
+public class TestAggregator extends TestRenderer
+{
+    private PortletAggregator portletAggregator;
+    private PageAggregator pageAggregator;
+    
+    /**
+     * Start the tests.
+     *
+     * @param args the arguments. Not used
+     */
+    public static void main(String args[])
+    {
+        junit.awtui.TestRunner.main(new String[] { TestAggregator.class.getName()});
+    }
+
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+        
+        ArrayList pathes = new ArrayList(4);
+        pathes.add("portlet/{mediaType}/jetspeed");
+        pathes.add("portlet/{mediaType}");
+        pathes.add("generic/{mediaType}");
+        pathes.add("/{mediaType}");
+
+        pageAggregator = new PageAggregatorImpl(renderer, pathes);
+        portletAggregator = new PortletAggregatorImpl(renderer);
+        
+    }
+
+    public static Test suite()
+    {
+        // All methods starting with "test" will be executed in the test suite.
+        return new TestSuite(TestAggregator.class);
+    }
+
+    public void testBasic() throws Exception
+    {
+        assertNotNull("portlet aggregator is null", portletAggregator);
+        assertNotNull("page aggregator is null", pageAggregator);
+        /*
+        Profiler profiler = (Profiler)Jetspeed.getComponentManager().getComponent(Profiler.class);
+
+        RequestContext request = RequestContextFactory.getInstance(null, null, null);
+
+        ProfileLocator locator = profiler.getProfile(request);
+        request.setProfileLocator(locator);
+
+        pageAggregator.build(request);
+        */
+    }
+
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2000-2001,2004 The Apache Software Foundation.
+ * 
+ * Licensed 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.aggregator;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.jetspeed.AbstractPortalContainerTestCase;
+import org.apache.jetspeed.aggregator.impl.PortletRendererImpl;
+
+/**
+ * TestPortletRenderer
+ *
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: TestRenderer.java 187850 2004-10-29 14:33:27Z weaver $
+ */
+public class TestRenderer extends AbstractPortalContainerTestCase
+{
+    protected PortletRenderer renderer;
+    
+   
+    /**
+     * Start the tests.
+     *
+     * @param args the arguments. Not used
+     */
+    public static void main(String args[])
+    {
+        junit.awtui.TestRunner.main(new String[] { TestRenderer.class.getName()});
+    }
+
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+        
+        renderer = new PortletRendererImpl(portletContainer, windowAccessor);       
+    }
+
+    /**
+     * Creates the test suite.
+     *
+     * @return a test suite (<code>TestSuite</code>) that includes all methods
+     *         starting with "test"
+     */
+    public static Test suite()
+    {
+        // All methods starting with "test" will be executed in the test suite.
+        return new TestSuite(TestRenderer.class);
+    }
+
+    public void testBasic() throws Exception
+    {
+        assertNotNull("portlet renderer is null", renderer);
+    }
+    
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2000-2001,2004 The Apache Software Foundation.
+ * 
+ * Licensed 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.container;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.pluto.PortletContainer;
+import org.apache.pluto.PortletContainerImpl;
+
+/**
+ * TestPortletContainer
+ *
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: TestPortletContainer.java 187716 2004-10-13 15:53:23Z weaver $
+ */
+public class TestPortletContainer extends TestCase 
+{
+    
+    private PortletContainer portletContainer;
+    
+    /**
+     * Defines the testcase name for JUnit.
+     *
+     * @param name the testcase's name.
+     */
+    public TestPortletContainer(String name)
+    {
+        super(name);
+    }
+
+    /**
+     * Start the tests.
+     *
+     * @param args the arguments. Not used
+     */
+    public static void main(String args[])
+    {
+        junit.awtui.TestRunner.main(new String[] { TestPortletContainer.class.getName()});
+    }
+
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+        
+        portletContainer = new JetspeedPortletContainerWrapper(new PortletContainerImpl());
+    }
+
+   public static Test suite()
+    {
+        // All methods starting with "test" will be executed in the test suite.
+        return new TestSuite(TestPortletContainer.class);
+    }
+
+    public void testBasic()
+    {
+        
+        // not much more i can do without setting up a mock servlet or portlet framework
+    }
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,224 @@
+/*
+ * Copyright 2000-2001,2004 The Apache Software Foundation.
+ * 
+ * Licensed 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.container.state;
+
+import java.io.FileInputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import javax.portlet.PortletMode;
+import javax.portlet.WindowState;
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpServletResponse;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.jetspeed.Jetspeed;
+import org.apache.jetspeed.PortalTestConstants;
+import org.apache.jetspeed.container.state.NavigationalState;
+import org.apache.jetspeed.container.state.NavigationalStateComponent;
+import org.apache.jetspeed.container.state.impl.JetspeedNavigationalStateComponent;
+import org.apache.jetspeed.container.url.PortalURL;
+import org.apache.jetspeed.container.url.impl.AbstractPortalURL;
+import org.apache.jetspeed.container.window.PortletWindowAccessor;
+import org.apache.jetspeed.engine.AbstractEngine;
+import org.apache.jetspeed.engine.Engine;
+import org.apache.jetspeed.engine.SpringEngine;
+import org.apache.jetspeed.om.common.portlet.MutablePortletEntity;
+import org.apache.jetspeed.om.window.impl.PortletWindowImpl;
+import org.apache.jetspeed.request.JetspeedRequestContext;
+import org.apache.pluto.om.entity.PortletEntity;
+import org.apache.pluto.om.window.PortletWindow;
+import org.apache.pluto.om.window.PortletWindowList;
+import org.apache.pluto.om.window.PortletWindowListCtrl;
+import org.jmock.Mock;
+import org.jmock.core.matcher.AnyArgumentsMatcher;
+import org.jmock.core.stub.ReturnStub;
+import org.jmock.core.stub.VoidStub;
+
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
+import com.mockrunner.mock.web.MockHttpSession;
+import com.mockrunner.mock.web.MockServletConfig;
+import com.mockrunner.mock.web.MockServletContext;
+
+/**
+ * TestPortletContainer
+ *
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: TestNavigationalState.java 188438 2005-03-23 22:57:11Z ate $
+ */
+
+public class TestNavigationalState extends TestCase
+{
+    // needed to be able to Mock PortletWindowListCtrl
+    private interface CompositeWindowList extends PortletWindowList, PortletWindowListCtrl{}
+
+    private NavigationalStateComponent navFullSession;
+    private NavigationalStateComponent navSession;
+    private NavigationalStateComponent navPluto;
+
+    /**
+     * Defines the testcase name for JUnit.
+     *
+     * @param name the testcase's name.
+     */
+    public TestNavigationalState(String name)
+    {
+        super(name);
+    }
+
+    /**
+     * Start the tests.
+     *
+     * @param args the arguments. Not used
+     */
+    public static void main(String args[])
+    {
+        junit.awtui.TestRunner.main(new String[] { TestNavigationalState.class.getName()});
+    }
+    
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+
+        // need to flag internal JNDI on...
+        System.setProperty(AbstractEngine.JNDI_SUPPORT_FLAG_KEY, "true");
+        
+        // create Engine
+        PropertiesConfiguration config = new  PropertiesConfiguration();
+        config.load(new FileInputStream(PortalTestConstants.JETSPEED_PROPERTIES_PATH));
+        Mock servletConfigMock = new Mock(ServletConfig.class);
+        MockServletConfig msc = new MockServletConfig();
+        msc.setServletContext(new MockServletContext());
+        Engine engine = Jetspeed.createEngine(config, PortalTestConstants.PORTAL_WEBAPP_PATH, msc, SpringEngine.class);
+
+        // mock test PortletWindow
+        Mock entityMock = new Mock(MutablePortletEntity.class);        
+        Mock windowListMock = new Mock(CompositeWindowList.class);
+        PortletWindowListCtrl windowList = (PortletWindowListCtrl)windowListMock.proxy();
+        entityMock.expects(new AnyArgumentsMatcher()).method("getPortletWindowList").withNoArguments().will(
+                new ReturnStub(windowList));
+        windowListMock.expects(new AnyArgumentsMatcher()).method("add").withAnyArguments().will(
+                new VoidStub());
+
+        PortletWindowAccessor accessor = (PortletWindowAccessor) Jetspeed.getComponentManager().getComponent(PortletWindowAccessor.class);        
+        accessor.createPortletWindow((PortletEntity)entityMock.proxy(), "111");
+        accessor.createPortletWindow((PortletEntity)entityMock.proxy(), "222");
+        accessor.createPortletWindow((PortletEntity)entityMock.proxy(), "333");
+        
+        navFullSession = new JetspeedNavigationalStateComponent("org.apache.jetspeed.container.state.impl.SessionFullNavigationalState",
+                "org.apache.jetspeed.container.url.impl.QueryStringEncodingPortalURL",
+                 "org.apache.jetspeed.container.state.impl.JetspeedNavigationalStateCodec");
+        navSession = new JetspeedNavigationalStateComponent("org.apache.jetspeed.container.state.impl.SessionNavigationalState",
+                "org.apache.jetspeed.container.url.impl.PathInfoEncodingPortalURL",
+                 "org.apache.jetspeed.container.state.impl.JetspeedNavigationalStateCodec");
+        navPluto = new JetspeedNavigationalStateComponent("org.apache.jetspeed.container.state.impl.PathNavigationalState",
+               "org.apache.jetspeed.container.url.impl.PathInfoEncodingPortalURL",
+                "org.apache.jetspeed.container.state.impl.JetspeedNavigationalStateCodec");
+    }
+
+    public static Test suite()
+    {
+        // All methods starting with "test" will be executed in the test suite.
+        return new TestSuite(TestNavigationalState.class);
+    }
+
+    public void testAllComponents()
+        throws Exception
+    {
+
+        // general navigational state test
+        navigationTest(navFullSession, true);
+        navigationTest(navSession, false);
+        navigationTest(navPluto, false);
+    }
+
+    private void navigationTest(NavigationalStateComponent component, boolean useQueryStringPortalURL)
+    throws Exception
+    {
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        MockHttpSession session = new MockHttpSession();
+        HttpServletResponse response = new MockHttpServletResponse();
+        ServletConfig config = new MockServletConfig();
+        request.setSession(session);
+        request.setServerName("www.sporteportal.com");
+        request.setScheme("http");
+        request.setContextPath("/jetspeed");
+        request.setServletPath("/portal");
+        request.setPathInfo("stuff");
+        request.setRequestURI("/jetspeed/portal/stuff");
+
+        JetspeedRequestContext context = new JetspeedRequestContext(request, response, config, null );
+        
+        // create base PortletURL
+        PortalURL url = component.createURL(context.getRequest(), context.getCharacterEncoding());
+        context.setPortalURL(url);
+
+        PortletWindow window = new PortletWindowImpl("111");
+        PortletWindow window2 = new PortletWindowImpl("222");
+        PortletWindow window3 = new PortletWindowImpl("333");
+ 
+        HashMap parameters = new HashMap();
+        parameters.put("test",new String[]{"one","two","three"});
+
+        String portletURL = url.createPortletURL(window,parameters,PortletMode.EDIT,WindowState.MAXIMIZED,true,false);
+        
+        String navStateParameterName = Jetspeed.getContext().getConfigurationProperty("portalurl.navigationalstate.parameter.name", AbstractPortalURL.DEFAULT_NAV_STATE_PARAMETER); 
+
+        if ( useQueryStringPortalURL )
+        {
+            request.setupAddParameter(navStateParameterName,portletURL.substring(portletURL.indexOf('=')+1));            
+        }
+        else
+        {
+            request.setPathInfo(portletURL.substring(portletURL.indexOf("/portal")+7));
+        }
+        
+        context = new JetspeedRequestContext(request, response, config, null );
+                
+        url = component.createURL(context.getRequest(), context.getCharacterEncoding());
+        context.setPortalURL(url);
+        NavigationalState nav = url.getNavigationalState();
+
+        // Check that they come out correctly
+        assertTrue("window mode is not set", nav.getMode(window).equals(PortletMode.EDIT));
+        assertTrue("window state is not set", nav.getState(window).equals(WindowState.MAXIMIZED));
+        PortletWindow target = nav.getPortletWindowOfAction();
+        assertNotNull("target window is null", target);
+        assertEquals("target window should equal window 111", target.getId(), "111");
+
+        PortletWindow maximizedWindow = nav.getMaximizedWindow();
+        assertNotNull("maximized window is null", maximizedWindow);
+        assertEquals("maximized window should equal window 111", maximizedWindow.getId(), "111");
+
+        Iterator iter = nav.getParameterNames(target);
+        int parameterCount = 0;
+        assertTrue("There should be one parameter",iter.hasNext());
+        while ( iter.hasNext() ) {
+            assertEquals("parameter name should equals \"test\"", (String)iter.next(), "test");
+            String[] values = nav.getParameterValues(target,"test");
+            assertNotNull("parameter name has no values", values);
+            assertEquals("parameter test should have 3 values", values.length, 3);
+            assertEquals("parameter test[0] should be \"one\"", values[0], "one");
+            assertEquals("parameter test[1] should be \"two\"", values[1], "two");
+            assertEquals("parameter test[2] should be \"three\"", values[2], "three");
+        }
+    }
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,473 @@
+/**
+ * Created on Jan 13, 2004
+ *
+ * 
+ * @author
+ */
+package org.apache.jetspeed.deployment;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+
+import junit.framework.AssertionFailedError;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.jetspeed.components.portletentity.PortletEntityNotStoredException;
+import org.apache.jetspeed.components.util.RegistrySupportedTestCase;
+import org.apache.jetspeed.container.window.PortletWindowAccessor;
+import org.apache.jetspeed.container.window.impl.PortletWindowAccessorImpl;
+import org.apache.jetspeed.deployment.impl.StandardDeploymentManager;
+import org.apache.jetspeed.factory.PortletFactory;
+import org.apache.jetspeed.om.common.portlet.MutablePortletApplication;
+import org.apache.jetspeed.om.common.portlet.MutablePortletEntity;
+//import org.apache.jetspeed.tools.pamanager.FileSystemPAM;
+import org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager;
+import org.apache.jetspeed.util.DirectoryHelper;
+import org.apache.jetspeed.util.JarHelper;
+import org.apache.jetspeed.util.descriptor.PortletApplicationWar;
+import org.apache.pluto.om.portlet.PortletDefinition;
+
+/**
+ * <p>
+ * TestSimpleDeployment
+ * </p>
+ * 
+ * @author <a href="mailto:weaver@apache.org">Scott T. Weaver </a>
+ * @version $Id: TestSimpleDeployment.java 208755 2005-07-01 12:58:35Z ate $
+ *  
+ */
+public class TestSimpleDeployment extends RegistrySupportedTestCase
+{
+    protected static final String TEST_PORTLET_APP_NAME = "HW_App";
+    protected String webAppsDir;
+
+    protected File deploySrc;
+
+    protected File deployRootFile;
+
+    protected String testDb;
+    private PortletApplicationWar paWar1;
+    private PortletApplicationWar paWar2;
+    private PortletApplicationWar paWar3;
+    protected File webAppsDirFile;
+    protected File copyFrom;
+    protected PortletWindowAccessor windowAccess;
+    protected PortletFactory portletFactory;
+    protected ApplicationServerManager manager;
+ 
+
+    /**
+     * Start the tests.
+     * 
+     * @param args
+     *            the arguments. Not used
+     */
+    public static void main( String args[] )
+    {
+        junit.awtui.TestRunner.main(new String[]{TestSimpleDeployment.class.getName()});
+    }
+
+    /**
+     * Creates the test suite.
+     * 
+     * @return a test suite (<code>TestSuite</code>) that includes all
+     *         methods starting with "test"
+     */
+    public static Test suite()
+    {
+        // All methods starting with "test" will be executed in the test suite.
+        // return new JetspeedTestSuite(TestSimpleDeployment.class);
+        return new TestSuite(TestSimpleDeployment.class);
+    }
+    public void testFileSystemHelperOnWar() throws Exception
+    {
+        File demoApp = new File(deploySrc, "demo.war");
+           
+        JarHelper jarHelper = new JarHelper(demoApp, true);
+        File rootDirectory = jarHelper.getRootDirectory();
+        File webXml = new File(rootDirectory, "WEB-INF/web.xml");
+        assertTrue(webXml.exists());
+        jarHelper.close();          
+        assertFalse(webXml.exists());
+        
+        // Test for keeping jar temp files around
+        jarHelper = new JarHelper(demoApp, false);
+        assertTrue(webXml.exists());
+        jarHelper.close();          
+        assertTrue(webXml.exists());
+    }
+    
+    public void testFileSystemManagerOnDir() throws Exception
+    {
+        File demoApp = new File("./test/testdata/deploy/webapp");
+        assertTrue(demoApp.exists());
+        
+        DirectoryHelper dirHelper = new DirectoryHelper(demoApp);
+        File webXml = new File(dirHelper.getRootDirectory(), "WEB-INF/web.xml");
+        assertTrue(webXml.exists());
+             
+    }
+    
+    /*    
+    
+    public void testDeploy() throws Exception
+    {
+
+        System.out.println("Deployment src: " + deploySrc);
+        manager = new TomcatManager("", "", 0, "", 0, "", "");
+        SimpleRegistry simpleRegistry = new InMemoryRegistryImpl();
+        DeployDecoratorEventListener ddel = new DeployDecoratorEventListener(simpleRegistry, deployRootFile
+                .getAbsolutePath());
+
+        DeployPortletAppEventListener dpal = new DeployPortletAppEventListener(webAppsDir, new FileSystemPAM(
+                webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager), portletRegistry );
+        ArrayList eventListeners = new ArrayList(2);
+        eventListeners.add(ddel);
+        eventListeners.add(dpal);
+        // Use a -1 delay to disable auto scan
+        StandardDeploymentManager autoDeployment = new StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners );
+        
+        autoDeployment.start();
+        autoDeployment.fireDeploymentEvent();
+
+        File decoratorVm = new File(deployRootFile.getAbsolutePath() + File.separator + "generic" + File.separator + "html" + File.separator
+                + "portletstd" + File.separator + "decorator.vm");
+        
+        File demoAppDeployed = new File(webAppsDirFile, TEST_PORTLET_APP_NAME);
+        File demoApp = demoAppDeployed;
+        File securityApp = new File(webAppsDirFile, "TestSecurityRoles");
+
+        assertTrue(decoratorVm.getCanonicalPath() + " was not created!", decoratorVm.exists());
+
+        verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
+        verifyDemoAppCreated("TestSecurityRoles", securityApp);
+       
+        MutablePortletApplication jetspeedApp = portletRegistry.getPortletApplicationByIdentifier("jetspeed");
+        assertNotNull("jetspeed was not registered into the portlet registery.", jetspeedApp);
+        assertFalse("local app, jetspeed, got deployed when it should have only been registered.", new File(webAppsDir
+                + "/jetspeed").exists());
+
+        //make sure we can load registered app's classes
+        Iterator portletDefItr = jetspeedApp.getPortletDefinitions().iterator();
+        while (portletDefItr.hasNext())
+        {
+            PortletDefinition def = (PortletDefinition) portletDefItr.next();
+            try
+            {
+                Portlet portlet = JetspeedPortletFactoryProxy.loadPortletClass(def.getClassName());
+                assertNotNull("Could not load portlet class: "+def.getClassName(), portlet);
+            }
+            catch (Exception e)
+            {
+                assertNull("Unable to load registered portlet class, " + def.getClassName(), e);
+            }
+
+        }
+        
+        // test undeploy
+        File demoWar = new File(deploySrc, "demo.war");
+        demoWar.delete();
+        autoDeployment.fireUndeploymentEvent();        
+        verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp);    
+        
+        // test deploy again        
+        copyDeployables();
+        autoDeployment.fireDeploymentEvent();
+        verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
+        demoWar.delete();
+        autoDeployment.fireUndeploymentEvent();
+        verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp);
+        
+        // test redeploy
+        
+        // So, first deploy the typical demo.war we have been using before.
+        copyDeployables();
+        autoDeployment.fireDeploymentEvent();
+        verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
+        DirectoryHelper demoAppDeployedDir = new DirectoryHelper(demoAppDeployed);
+        long beforeSize = new File(demoAppDeployedDir.getRootDirectory(), "WEB-INF/portlet.xml").length();
+        
+        // Trigger re-deployment using a demo.war that has a slightly larger portlet.xml
+        // then the one we just deployed.  We will use size comparisons as or litmus test.
+        File redeployDemoWar = new File("./test/deployment/redeploy/demo.war");
+        FileChannel srcDemoWarChannel = new FileInputStream(redeployDemoWar).getChannel();
+        FileChannel dstDemoWarChannel = new FileOutputStream(demoWar).getChannel();
+        dstDemoWarChannel.transferFrom(srcDemoWarChannel, 0, srcDemoWarChannel.size());
+        srcDemoWarChannel.close();
+        dstDemoWarChannel.close();
+        
+        // Make sure the demo.war that will trigger redeploy has a larger portlet.xml then the current one
+        JarHelper rdDemoWar = new JarHelper(demoWar, true);
+        assertTrue(new File(rdDemoWar.getRootDirectory(), "WEB-INF/portlet.xml").length() > beforeSize);
+        
+        // Need to slow it down so the timestamp check works
+        Thread.sleep(500);
+        demoWar.setLastModified(System.currentTimeMillis());
+        autoDeployment.fireRedeploymentEvent();
+      
+        long afterSize = new File(demoAppDeployedDir.getRootDirectory(), "WEB-INF/portlet.xml").length();
+        // The portlet.xml in re-deploy has an additional portlet entry in portlet.xml, so it should be bigger
+        assertTrue(afterSize > beforeSize);
+        autoDeployment.stop();
+        
+    }
+    
+    
+    public void testUndeployVersusRedeploy() throws Exception
+    {
+        manager = new TomcatManager("", "", 0, "", 0, "", "");
+        
+        DeployPortletAppEventListener dpal = new DeployPortletAppEventListener(webAppsDir, new FileSystemPAM(
+                webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager), portletRegistry );
+        ArrayList eventListeners = new ArrayList(1);
+        
+        eventListeners.add(dpal);
+        
+        // Use a -1 delay to disable auto scan
+        StandardDeploymentManager autoDeployment = new StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners );        
+        autoDeployment.start();
+
+        buildEntityTestData(autoDeployment);       
+        
+        
+        MutablePortletEntity entity = entityAccess.getPortletEntity("testEnity");
+        
+        PreferenceSetCtrl prefs = (PreferenceSetCtrl) entity.getPreferenceSet();
+        List values = new ArrayList(1);
+        values.add("some value");
+        prefs.add("pref1", values);
+        
+        entity.store();
+        
+        assertNotNull(entity);
+        
+        Preference pref = entity.getPreferenceSet().get("pref1");
+        
+        assertNotNull(pref);
+        
+        //test entity removal via undeploy
+        File demoWar = new File(deploySrc, "demo.war");
+        demoWar.delete();
+        
+        autoDeployment.fireUndeploymentEvent();
+        
+                
+        entity = entityAccess.getPortletEntity("testEnity");
+        
+        assertNull(entity);
+        
+        // Now test that redploy DOES NOT kill the entity
+        buildEntityTestData(autoDeployment);
+        
+        entity = entityAccess.getPortletEntity("testEnity");
+        
+        assertNotNull(entity);
+        
+        pref = entity.getPreferenceSet().get("pref1");
+        
+        assertNull("Preference was not deleted with last undeploy",pref);
+        
+        demoWar.setLastModified(System.currentTimeMillis());
+        
+        autoDeployment.fireRedeploymentEvent();        
+        
+        entity = entityAccess.getPortletEntity("testEnity");
+        
+        assertNotNull(entity);
+        
+    }
+*/   
+
+    /**
+     * <p>
+     * buildEntityTestData
+     * </p>
+     *
+     * @param autoDeployment
+     * @throws IOException
+     * @throws PortletEntityNotStoredException
+     */
+    protected void buildEntityTestData( StandardDeploymentManager autoDeployment ) throws Exception
+    {
+        copyDeployables();
+        
+        File demoApp = new File(webAppsDirFile, TEST_PORTLET_APP_NAME);
+                
+        autoDeployment.fireDeploymentEvent();
+        
+        verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp);
+        
+        MutablePortletApplication app = portletRegistry.getPortletApplication(TEST_PORTLET_APP_NAME);
+        
+        PortletDefinition portlet = (PortletDefinition) app.getPortletDefinitionList().iterator().next();
+        
+        MutablePortletEntity entity = entityAccess.newPortletEntityInstance(portlet);
+        entity.setId("testEnity");
+        
+        entityAccess.storePortletEntity(entity);
+        
+        
+        
+    }
+
+    /**
+     * <p>
+     * verifyDemoAppCreated
+     * </p>
+     *
+     * @param demoApp
+     */
+    private void verifyDemoAppCreated( String appName, File appFile )
+    {
+        assertNotNull(appName + " was not registered into the portlet registery.", portletRegistry
+                .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME));
+        assertTrue(appName + " directory was not created, app not deployed.", appFile.exists());
+    }
+    
+
+    
+    
+
+    /**
+     * <p>
+     * verifyDemoAppDeleted
+     * </p>
+     *
+     * @param demoApp
+     */
+    private void verifyDemoAppDeleted( String appName, File appFile )
+    {
+        assertNull(appName + " was not removed from the registry.", portletRegistry
+                .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME));
+        assertFalse(appName+" directory was not deleted.", appFile.exists());
+    }
+
+    /**
+     * @see junit.framework.TestCase#setUp()
+     */
+    public void setUp()
+    {
+
+        try
+        {
+            super.setUp();
+            copyFrom = new File("./test/deployment/deploy");
+            deploySrc = new File("./target/deployment/deploy");
+            deploySrc.mkdirs();
+            deployRootFile = new File("./target/deployment/templates/decorators");
+            deployRootFile.mkdirs();
+            webAppsDirFile = new File("./target/deployment/webapps");
+            webAppsDirFile.mkdirs();
+
+            webAppsDir = webAppsDirFile.getCanonicalPath();
+            testDb = new File("./test/db/hsql/Registry").getCanonicalPath();           
+            
+            copyDeployables();
+            windowAccess = new PortletWindowAccessorImpl(entityAccess, true);  
+        }
+        catch (Exception e)
+        {
+            e.printStackTrace();
+            throw new AssertionFailedError("Unable to set up test environment " + e.toString());
+        }
+
+    }
+
+    /**
+     * <p>
+     * copyDeployables
+     * </p>
+     * @throws IOException
+     */
+    protected void copyDeployables() throws IOException
+    {      
+        
+  
+        copyFiles(copyFrom, deploySrc);
+        
+    }
+    
+    
+
+    /**
+     * <p>
+     * copyFiles
+     * </p>
+     *
+     * @throws IOException
+     * @throws FileNotFoundException
+     */
+    protected void copyFiles(File srcDir, File dstDir) throws IOException, FileNotFoundException
+    {
+        File[] children = srcDir.listFiles();
+        for(int i=0; i<children.length; i++)
+        {
+            File child = children[i];
+            if(child.isFile())
+            {
+                File toFile = new File(dstDir, child.getName());
+                toFile.createNewFile();
+                FileChannel srcChannel = new FileInputStream(child).getChannel();
+                FileChannel dstChannel = new FileOutputStream(toFile).getChannel();
+                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
+                srcChannel.close();
+                dstChannel.close();
+            }
+            else
+            {
+                File newSubDir = new File(dstDir, child.getName());
+                newSubDir.mkdir();
+                copyFiles(child, newSubDir);
+            }
+        }
+    }
+
+    /**
+     * @see junit.framework.TestCase#tearDown()
+     */
+    public void tearDown() throws Exception
+    {
+/*        
+        manager = new TomcatManager("", "", 0, "", 0, "", "");
+        FileSystemPAM pam = new FileSystemPAM(webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager);
+
+        try
+        {
+            DirectoryHelper dirHelper = new DirectoryHelper(new File(webAppsDir + "/" + TEST_PORTLET_APP_NAME));
+            paWar1 = new PortletApplicationWar(dirHelper, TEST_PORTLET_APP_NAME, "/"
+                    + TEST_PORTLET_APP_NAME);
+            pam.undeploy(paWar1);
+        }
+        catch (Exception e1)
+        {
+
+        }
+
+        pam.unregister("jetspeed");
+
+        try
+        {
+            DirectoryHelper dirHelper = new DirectoryHelper(new File(webAppsDir + "/TestSecurityRoles"));
+            paWar3 = new PortletApplicationWar(dirHelper, "TestSecurityRoles", "/TestSecurityRoles" );
+
+            pam.undeploy(paWar3);
+        }
+        catch (Exception e3)
+        {
+
+        }
+
+        // DirectoryUtils.rmdir(new File("./target/deployment"));
+        new DirectoryHelper(new File("./target/deployment")).remove();
+*/        
+        super.tearDown();
+
+    }
+
+    
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/AbstractEngineTest.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/AbstractEngineTest.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/AbstractEngineTest.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/AbstractEngineTest.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2000-2001,2004 The Apache Software Foundation.
+ * 
+ * Licensed 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.engine;
+
+import java.io.FileInputStream;
+
+import javax.servlet.ServletConfig;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.jetspeed.Jetspeed;
+import org.apache.jetspeed.PortalTestConstants;
+import org.apache.jetspeed.components.ComponentManagement;
+import org.jmock.Mock;
+
+import com.mockrunner.mock.web.MockServletConfig;
+import com.mockrunner.mock.web.MockServletContext;
+
+/**
+ * <p>
+ * AbstractEngineTest
+ * </p>
+ * 
+ * @author <a href="mailto:weaver@apache.org">Scott T. Weaver</a>
+ * @version $Id: AbstractEngineTest.java 187753 2004-10-15 21:47:25Z ate $
+ */
+public abstract class AbstractEngineTest extends TestCase
+{
+
+    /**
+     * 
+     */
+    public AbstractEngineTest()
+    {
+        super();
+    }
+
+    /**
+     * @param arg0
+     */
+    public AbstractEngineTest(String arg0)
+    {
+        super(arg0);
+    }
+
+    protected Engine engine;
+
+    protected Object[] keysToCheck;
+
+    public void testEngine() throws Exception
+    {
+        assertNotNull(engine.getComponentManager());
+        assertNotNull(engine.getComponentManager().getRootContainer());
+        if (keysToCheck != null)
+        {
+            verifyComponents(keysToCheck);
+        }
+    }
+
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+        // need to flag internal JNDI on...
+        System.setProperty(AbstractEngine.JNDI_SUPPORT_FLAG_KEY, "true");
+        PropertiesConfiguration config = new PropertiesConfiguration();
+        config.load(new FileInputStream(PortalTestConstants.JETSPEED_PROPERTIES_PATH));
+        Mock servletConfigMock = new Mock(ServletConfig.class);
+        MockServletConfig msc = new MockServletConfig();
+        msc.setServletContext(new MockServletContext());
+        engine = Jetspeed.createEngine(config, PortalTestConstants.PORTAL_WEBAPP_PATH, msc, getEngineClass());
+
+    }
+
+    protected void tearDown() throws Exception
+    {
+
+        super.tearDown();
+    }
+
+    protected void verifyComponents(Object[] keys)
+    {
+        ComponentManagement cm = engine.getComponentManager();
+        for (int i = 0; i < keys.length; i++)
+        {
+            assertNotNull("Could not get component insatance " + keys[i], cm.getComponent(keys[i]));
+            System.out.println("Load componenet " + cm.getComponent(keys[i]).getClass() + " for key " + keys[i]);
+        }
+    }
+
+    protected abstract Class getEngineClass();
+}

Added: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/TestSpringEngine.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/TestSpringEngine.java?rev=209328&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/TestSpringEngine.java (added)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/engine/TestSpringEngine.java Tue Jul  5 14:55:37 2005
@@ -0,0 +1,82 @@
+/*
+ * Created on Jul 16, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Generation - Code and Comments
+ */
+package org.apache.jetspeed.engine;
+
+import javax.servlet.ServletConfig;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.jetspeed.aggregator.PageAggregator;
+import org.apache.jetspeed.aggregator.PortletAggregator;
+import org.apache.jetspeed.aggregator.PortletRenderer;
+import org.apache.jetspeed.capabilities.Capabilities;
+import org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent;
+import org.apache.jetspeed.components.portletregistry.PortletRegistry;
+import org.apache.jetspeed.container.state.NavigationalStateComponent;
+import org.apache.jetspeed.container.window.PortletWindowAccessor;
+import org.apache.jetspeed.page.PageManager;
+import org.apache.jetspeed.prefs.PreferencesProvider;
+import org.apache.jetspeed.prefs.PropertyManager;
+import org.apache.jetspeed.profiler.Profiler;
+import org.apache.jetspeed.request.RequestContextComponent;
+import org.apache.jetspeed.security.GroupManager;
+import org.apache.jetspeed.security.PermissionManager;
+import org.apache.jetspeed.security.RoleManager;
+import org.apache.jetspeed.security.SecurityProvider;
+import org.apache.jetspeed.security.UserManager;
+import org.apache.jetspeed.security.impl.RdbmsPolicy;
+import org.apache.jetspeed.userinfo.UserInfoManager;
+import org.apache.pluto.services.information.StaticInformationProvider;
+
+/**
+ * <p>
+ * TestSpringEngine
+ * </p>
+ * <p>
+ * 
+ * </p>
+ * 
+ * @author <a href="mailto:weaver@apache.org">Scott T. Weaver </a>
+ * @version $Id: TestSpringEngine.java 188438 2005-03-23 22:57:11Z ate $
+ *  
+ */
+public class TestSpringEngine extends AbstractEngineTest
+{
+    public TestSpringEngine()
+    {
+        System.out.println(System.getProperty("org.apache.jetspeed.database.user"));
+        keysToCheck = new Object[] {"IdGenerator", "DecorationLocator", "TemplateLocator", "IdGenerator", "PageFileCache", PageManager.class, 
+                                     PortletRegistry.class, PortletEntityAccessComponent.class, "PortalServices",
+                                     Profiler.class, Capabilities.class, PropertyManager.class, PreferencesProvider.class, UserManager.class,
+                                     GroupManager.class, RoleManager.class, PermissionManager.class, RdbmsPolicy.class, SecurityProvider.class,
+                                     UserInfoManager.class, NavigationalStateComponent.class, RequestContextComponent.class, PortletWindowAccessor.class,
+                                     PortletRenderer.class, PageAggregator.class, PortletAggregator.class, "PAM",
+                                     "deploymentManager", "portletFactory", ServletConfig.class, 
+                                     StaticInformationProvider.class};
+    }
+    
+    public static Test suite()
+    {
+        // All methods starting with "test" will be executed in the test suite.
+        return new TestSuite(TestSpringEngine.class);
+    }
+
+    /**
+     * <p>
+     * getEngineClass
+     * </p>
+     * 
+     * @see org.apache.jetspeed.engine.AbstractEngineTest#getEngineClass()
+     * @return
+     */
+    protected Class getEngineClass()
+    {
+        return SpringEngine.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