portals-jetspeed-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tay...@apache.org
Subject cvs commit: jakarta-jetspeed-2/portals-bridges/frameworks/xdocs navigation.xml
Date Thu, 04 Nov 2004 18:09:33 GMT
taylor      2004/11/04 10:09:33

  Added:       portals-bridges/frameworks .classpath .project .cvsignore
                        project.xml project.properties
               portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/spring
                        ModelBeanImpl.java PortletApplicationModelImpl.java
               portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/model
                        ModelBean.java PortletApplicationModel.java
                        ForwardConstants.java
               portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/spring/validation
                        ValidationSupport.java
               portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks
                        GenericFrameworkPortlet.java
                        VelocityFrameworkPortlet.java
               portals-bridges/frameworks/xdocs navigation.xml
  Log:
  portlet application framework integrator for developing portlet applications with velocity, jsp + frameworks
  the first implementation is based on the Spring framework
  
  Revision  Changes    Path
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/.classpath
  
  Index: .classpath
  ===================================================================
  <?xml version="1.0" encoding="UTF-8"?>
  
  <classpath>
    <classpathentry excluding="" kind="src" path="src\java">
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/portlet-api/jars/portlet-api-1.0.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/servletapi/jars/servletapi-2.3.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/velocity/jars/velocity-1.4.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/velocity-tools/jars/velocity-tools-view-1.1-beta1.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/commons-validator/jars/commons-validator-1.1.3.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/springframework/jars/spring-core-1.1.1.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/commons-beanutils/jars/commons-beanutils-1.7.0.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/portals-bridges/jars/portals-bridges-common-0.1.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/hsqldb/jars/hsqldb-1.7.1.jar">
    </classpathentry>
    <classpathentry kind="var" path="MAVEN_REPO/commons-logging/jars/commons-logging-1.0.3.jar">
    </classpathentry>
    <classpathentry kind="output" path="target\classes">
    </classpathentry>
  </classpath>
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/.project
  
  Index: .project
  ===================================================================
  <?xml version="1.0" encoding="UTF-8"?>
  
  <projectDescription>
    <name>portals-bridges-velocity</name>
    <comment>Apache Portals Velocity Bridge</comment>
    <projects>
    </projects>
    <buildSpec>
      <buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
      </buildCommand>
    </buildSpec>
    <natures>
      <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
  </projectDescription>
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/.cvsignore
  
  Index: .cvsignore
  ===================================================================
  target
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/project.xml
  
  Index: project.xml
  ===================================================================
  <?xml version="1.0" encoding="UTF-8"?>
  <!--
  Copyright 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.
  
    $Id: project.xml,v 1.1 2004/11/04 18:09:33 taylor Exp $
  -->
  <project>
    <extend>${basedir}/../../project.xml</extend>
    <pomVersion>3</pomVersion>
    <groupId>portals-bridges</groupId>
    <id>portals-bridges-frameworks</id>
    <name>Apache Portals Bridges Frameworks</name>
    <currentVersion>0.1</currentVersion>
    <package>org.apache.portals.bridges.frameworks</package>
    <description>
      Apache Portals Bridges Frameworks
    </description>
    <shortDescription>Apache Portals Bridges Frameworks</shortDescription>
    <repository>
      <connection>scm:cvs:pserver:anoncvs@cvs.apache.org:/home/cvspublic:jakarta-jetspeed-2/portals-bridges/frameworks/</connection>
      <url>http://cvs.apache.org/viewcvs/jakarta-jetspeed-2/portals-bridges/frameworks/</url>
    </repository>
    <dependencies>
  	  <dependency>
        <groupId>portlet-api</groupId>
        <artifactId>portlet-api</artifactId>
        <version>1.0</version>
      </dependency>
       <dependency>
        <groupId>servletapi</groupId>
        <artifactId>servletapi</artifactId>
        <version>2.3</version>
      </dependency>
      <dependency>
        <id>velocity</id>
        <version>1.4</version>
      </dependency>
      <dependency>
        <id>velocity-tools:velocity-tools-view</id>
        <version>1.1-beta1</version>
        <url>http://jakarta.apache.org/velocity</url>
      </dependency>
      <dependency>
        <groupId>commons-validator</groupId>
        <artifactId>commons-validator</artifactId>
        <version>1.1.3</version>
        <url>http://jakarta.apache.org/commons/validator/</url>
        <properties>
          <war.bundle>true</war.bundle>
        </properties>    
      </dependency>
      <dependency>
        <id>springframework:spring-core</id>
        <version>1.1.1</version>
        <properties>
          <war.bundle>true</war.bundle>
        </properties>
      </dependency>
      <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.7.0</version>
        <url>http://jakarta.apache.org/commons/beanutils/</url>
        <properties>
          <war.bundle>true</war.bundle>
        </properties>
      </dependency>
  
      <dependency>
        <groupId>portals-bridges</groupId>
        <artifactId>portals-bridges-common</artifactId>
        <version>0.1</version>
      </dependency>
      
      <dependency>
        <groupId>portals-bridges</groupId>
        <artifactId>portals-bridges-velocity</artifactId>
        <version>0.1</version>
      </dependency>
      
    </dependencies>
    <build>
      <sourceDirectory>src/java</sourceDirectory>
      <resources>
        <resource>
          <directory>${basedir}/src/java</directory>
          <includes>
            <include>META-INF/*</include>
          </includes>
        </resource>
        <resource>
          <directory>${basedir}/src/java</directory>
          <includes>
             <include>**/*.xml</include>
          </includes>
        </resource>      
      </resources>
    </build>
    <reports>
      <report>maven-jdepend-plugin</report>
  <!--
      <report>maven-checkstyle-plugin</report>
  -->
      <report>maven-pmd-plugin</report>
      <report>maven-changelog-plugin</report>
      <report>maven-file-activity-plugin</report>
      <report>maven-developer-activity-plugin</report>
      <report>maven-license-plugin</report>
      <report>maven-javadoc-plugin</report>
      <report>maven-jxr-plugin</report>
      <report>maven-junit-report-plugin</report>
      <report>maven-jcoverage-plugin</report>
      <report>maven-linkcheck-plugin</report>
      <report>maven-tasklist-plugin</report>
    </reports>
  </project>
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/project.properties
  
  Index: project.properties
  ===================================================================
  # Copyright 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.
  #
  # $Id: project.properties,v 1.1 2004/11/04 18:09:33 taylor Exp $
  maven.multiproject.type=jar
  maven.license.licenseFile=${basedir}/../../LICENSE.TXT
  
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/spring/ModelBeanImpl.java
  
  Index: ModelBeanImpl.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks.spring;
  
  import org.apache.portals.bridges.frameworks.model.ModelBean;
  
  
  /**
   * BeanModelImpl
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: ModelBeanImpl.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public class ModelBeanImpl implements ModelBean
  {
  
      private String beanName;
      private int beanType;
      
      public ModelBeanImpl(String beanName, int beanType)
      {
          this.beanName = beanName;
          this.beanType = beanType;
      }
      
      /* (non-Javadoc)
       * @see org.apache.portals.bridges.velocity.model.ModelBean#getBeanName()
       */
      public String getBeanName()
      {
          return beanName;
      }
  
      /* (non-Javadoc)
       * @see org.apache.portals.bridges.velocity.model.ModelBean#getBeanType()
       */
      public int getBeanType()
      {
          return beanType;
      }
  
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/spring/PortletApplicationModelImpl.java
  
  Index: PortletApplicationModelImpl.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks.spring;
  
  import java.io.InputStream;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Map;
  
  import javax.portlet.PortletConfig;
  import javax.portlet.PortletException;
  
  import org.springframework.beans.factory.xml.XmlBeanFactory;
  
  import org.apache.commons.validator.Validator;
  import org.apache.commons.validator.ValidatorException;
  import org.apache.commons.validator.ValidatorResources;
  import org.apache.commons.validator.ValidatorResults;
  import org.apache.portals.bridges.frameworks.model.ModelBean;
  import org.apache.portals.bridges.frameworks.model.PortletApplicationModel;
  import org.apache.portals.bridges.frameworks.spring.ModelBeanImpl;
  import org.apache.portals.bridges.frameworks.spring.validation.ValidationSupport;
  
  
  /**
   * PortletApplicationModelImpl
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: PortletApplicationModelImpl.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public class PortletApplicationModelImpl implements PortletApplicationModel
  {
      /**
       * Spring configuration: view to bean name map
       */
      private static final String PORTLET_VIEW_BEAN_MAP = "portlet-view-bean-map";
      
      /**
       * Spring configuration: view to validator name map
       */
      private static final String PORTLET_VIEW_VALIDATOR_MAP = "portlet-view-validator-map";
      
      /**
       * logical view to template map
       */
      private static final String PORTLET_LOGICAL_VIEW_MAP = "portlet-views";
  
      /**
       * map for action forward definitions (success, failure)
       */
      private static final String PORTLET_ACTION_FORWARD_MAP = "portlet-action-forward-map";
          
      /**
       * Spring Factory 
       */
      private XmlBeanFactory springFactory = null;
  
      /**
       * View Bean Map
       */
      private Map viewBeanMap = null;
      
      /**
       * Validation resources
       */
      private ValidatorResources validations = null;
          
      /**
       * View Validation Map
       */
      private Map viewValidatorMap = null;
  
      /**
       * Map from logical views to templates
       */
      private Map logicalViewMap = null;
  
      /**
       * Map from view:status to view
       */    
      private Map actionForwardMap = null;
      
      private static Object semaphore = new Object();
      
      private String springConfig;
      private String validatorConfig = null;
      
      public PortletApplicationModelImpl(String springConfig, String validatorConfig)
      {
          this.springConfig = springConfig;
          this.validatorConfig = validatorConfig;
      }
      
      public void init(PortletConfig config)
      throws PortletException
      {
          // load Spring
          try 
          {
              synchronized (semaphore)
              {
                  if (null == springFactory)
                  {
                      InputStream is = config.getPortletContext().getResourceAsStream(springConfig);                    
                      springFactory = new XmlBeanFactory(is);
                      is.close();
                  }
              }
           } 
           catch (Exception e) 
           {
               throw new PortletException("Failed to load spring configuration.", e);
           }   
                             
           // load validator
           synchronized (semaphore)
           {             
               if (validatorConfig != null && null == validations)
               {
                   InputStream is = null;
                   
                   try
                   {
                       // TODO: support extensible user-defined validator resources
                       //is = this.getClass().getResourceAsStream("/org/apache/portals/bridges/velocity/validation/default-portlet-validation.xml");
                       is = config.getPortletContext().getResourceAsStream(validatorConfig);                    
                       
                       validations = new ValidatorResources(is);
                   }
                   catch (Exception e)
                   {
                       throw new PortletException("Failed to load validator configuration.", e);
                   }
                   finally 
                   {
                       // Make sure we close the input stream.
                       if (is != null) 
                       {
                           try
                           {
                               is.close();
                           }
                           catch (Exception e)
                           {}
                       }
                   }                     
               }
           }
  
           // Logical Views to templates
           synchronized (semaphore)
           {
               logicalViewMap = (Map)springFactory.getBean(PORTLET_LOGICAL_VIEW_MAP);
               if (logicalViewMap == null)
               {
                   logicalViewMap = new HashMap(); 
               }
           }
           
           // View to Validator Map
           synchronized (semaphore)
           {
               viewValidatorMap = (Map)springFactory.getBean(PORTLET_VIEW_VALIDATOR_MAP);
               if (viewValidatorMap == null)
               {
                   viewValidatorMap = new HashMap(); 
               }
           }
           
           // View to Bean Map
           synchronized (semaphore)
           {
               viewBeanMap = (Map)springFactory.getBean(PORTLET_VIEW_BEAN_MAP);
               if (viewBeanMap == null)
               {
                   viewBeanMap = new HashMap();              
               }
           }        
  
           // Action Forward map
           synchronized (semaphore)
           {
               actionForwardMap = (Map)springFactory.getBean(PORTLET_ACTION_FORWARD_MAP);
               if (actionForwardMap == null)
               {
                   actionForwardMap = new HashMap();              
               }
           }                          
      }
      
      public ModelBean getBean(String view)
      {
          String beanName = (String)viewBeanMap.get(view);
          if (beanName != null)
          {
              return new ModelBeanImpl(beanName, ModelBean.POJO);
          }
          return new ModelBeanImpl(beanName, ModelBean.PREFS_MAP);
      }
      
      public String getTemplate(String view)
      {
          return (String)logicalViewMap.get(view);
      }
      
      public Object createBean(ModelBean mb)
      {
          return springFactory.getBean(mb.getBeanName());
      }
  
      public Map createPrefsBean(ModelBean mb, Map original)
      {
          Map prefs = new HashMap();
          Iterator it = original.entrySet().iterator();
          while (it.hasNext())
          {
              Map.Entry entry = (Map.Entry)it.next();
              String key = (String)entry.getKey();
              Object value = entry.getValue();
              if (value instanceof String)
              {
                  prefs.put(key, value);
              }
              else if (value instanceof String[])
              {
                  prefs.put(key, ((String[])value)[0]);
              }
          }
          return prefs;        
      }
  
      public boolean validate(Object bean, String view)
      throws PortletException
      {
          if (validations == null)
          {
              return true; // no validation configured
          }
          // Get the bean name from the bean-view map
          String validatorFormName = (String)viewValidatorMap.get(view);
          if (validatorFormName == null)
          {
              return true; // no validation for this bean
          }
  
          // TODO: do we need to create a validator per request?
          Validator validator = new Validator(validations, validatorFormName);
  
          // Tell the validator which bean to validate against.
          validator.setParameter(Validator.BEAN_PARAM, bean);
          
          ValidatorResults results = null;
                  
          try
          {
              validator.setOnlyReturnErrors(true);
              results = validator.validate();
              if (results.isEmpty())
              {
                  return true;
              }
              ValidationSupport.printResults(bean, results, validations, validatorFormName);
          }
          catch (ValidatorException e)
          {
              throw new PortletException("Error in processing validation: ", e);            
          }
          
          return false;        
      }
      
      public String getForward(String view, String status)
      {
          return (String)actionForwardMap.get(view + ":" + status);
      }
  
      public String getForward(String view)
      {
          return (String)actionForwardMap.get(view);
      }
      
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/model/ModelBean.java
  
  Index: ModelBean.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks.model;
  
  
  /**
   * BeanModel
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: ModelBean.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public interface ModelBean
  {
      final int POJO = 0;
      final int PREFS_MAP = 1;
      final int DYNABEAN = 2;
      
      String getBeanName();
      
      int getBeanType();
             
      
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/model/PortletApplicationModel.java
  
  Index: PortletApplicationModel.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks.model;
  
  import java.util.Map;
  
  import javax.portlet.PortletConfig;
  import javax.portlet.PortletException;
  
  
  /**
   * PortletApplicationModel
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: PortletApplicationModel.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public interface PortletApplicationModel
  {
      void init(PortletConfig config)
      throws PortletException;
      
      ModelBean getBean(String view);
  
      String getTemplate(String view);
      
      Object createBean(ModelBean mb);
      
      Map createPrefsBean(ModelBean mb, Map prefs);
      
      boolean validate(Object bean, String view)
      throws PortletException;
          
      String getForward(String view, String status);
      
      String getForward(String actionForward);
      
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/model/ForwardConstants.java
  
  Index: ForwardConstants.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks.model;
  
  
  /**
   * ForwardConstants
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: ForwardConstants.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public interface ForwardConstants
  {
      final String SUCCESS = "success";
      final String FAILURE = "failure";
      
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/spring/validation/ValidationSupport.java
  
  Index: ValidationSupport.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks.spring.validation;
  
  import java.lang.reflect.InvocationTargetException;
  import java.text.MessageFormat;
  import java.util.Collection;
  import java.util.Iterator;
  import java.util.Locale;
  import java.util.Map;
  
  import org.apache.commons.beanutils.DynaBean;
  import org.apache.commons.beanutils.PropertyUtils;
  import org.apache.commons.validator.Arg;
  import org.apache.commons.validator.Field;
  import org.apache.commons.validator.Form;
  import org.apache.commons.validator.GenericTypeValidator;
  import org.apache.commons.validator.GenericValidator;
  import org.apache.commons.validator.ValidatorAction;
  import org.apache.commons.validator.ValidatorResources;
  import org.apache.commons.validator.ValidatorResult;
  import org.apache.commons.validator.ValidatorResults;
  import org.apache.commons.validator.util.ValidatorUtils;
  
  
  /**
   * ValidationSupport
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: ValidationSupport.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public class ValidationSupport
  {
      public static String getValueAsString(Object bean, String property)
      {
          Object value = null;
          
          if (bean instanceof Map)
          {
              value = ((Map)bean).get(property);
          }
          else if (bean instanceof DynaBean)
          {
              value = ((DynaBean)bean).get(property);            
          }
          else
          {
              try {
                  value = PropertyUtils.getProperty(bean, property);
      
              } catch(IllegalAccessException e) {
                  //log.error(e.getMessage(), e);
              } catch(InvocationTargetException e) {
                  //log.error(e.getMessage(), e);
              } catch(NoSuchMethodException e) {
                  //log.error(e.getMessage(), e);
              }
          }
          
          if (value == null) 
          {
              return null;
          }
  
          if (value instanceof String[]) 
          {
              return ((String[]) value).length > 0 ? value.toString() : "";
  
          } else if (value instanceof Collection) 
          {
              return ((Collection) value).isEmpty() ? "" : value.toString();
  
          } else {
              return value.toString();
          }        
      }
      
      /**
       * Checks if the field is required.
       *
       * @return boolean If the field isn't <code>null</code> and
       * has a length greater than zero, <code>true</code> is returned.  
       * Otherwise <code>false</code>.
       */
      public static boolean validateRequired(Object bean, Field field) 
      {
         String value = getValueAsString(bean, field.getProperty());
         boolean valid = !GenericValidator.isBlankOrNull(value);
         return valid;
      }
  
      public static boolean validateRange(Object bean, Field field) 
      {        
         String result = ValidatorUtils.getValueAsString(bean, field.getProperty());
         if (result == null)
             return false;
                
         Integer intValue = GenericTypeValidator.formatInt(result);
         if (intValue == null)
             return false;
         
         int value = intValue.intValue();
  
         String minResult = field.getVarValue("min");
         if (minResult == null)
             return false;
  
         String maxResult = field.getVarValue("max");
         if (maxResult == null)
             return false;
         
         int min = GenericTypeValidator.formatInt(minResult).intValue();
         int max = GenericTypeValidator.formatInt(maxResult).intValue();
         
         return GenericValidator.isInRange(value, min, max);
      }
  
      public static boolean validateDoubleRange(Object bean, Field field) 
      {
         String result = ValidatorUtils.getValueAsString(bean, field.getProperty());
         if (result == null)
             return false;
                
         Double doubleValue = GenericTypeValidator.formatDouble(result);
         if (doubleValue == null)
             return false;
         
         double value = doubleValue.intValue();
  
         String minResult = field.getVarValue("min");
         if (minResult == null)
             return false;
  
         String maxResult = field.getVarValue("max");
         if (maxResult == null)
             return false;
         
         double min = GenericTypeValidator.formatDouble(minResult).doubleValue();
         double max = GenericTypeValidator.formatDouble(maxResult).doubleValue();
         
         return GenericValidator.isInRange(value, min, max);
      }
   
      public static boolean validateMask(Object bean, Field field)
      {
          String mask = field.getVarValue("mask");
          String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
          
          try 
          {
              if (!GenericValidator.isBlankOrNull(value)
                  && !GenericValidator.matchRegexp(value, mask)) 
              {        
                //  errors.add(
                //  field.getKey(),
                //  Resources.getActionMessage(request, va, field));
          
                  return false;
              } 
              else 
              {
                  return true;
              }
          } 
          catch (Exception e) 
          {
              //log.error(e.getMessage(), e);
          }
          return true;
      }
      
  
      public static void printResults(
              Object bean,
              ValidatorResults results,
              ValidatorResources resources,
              String formName)
      {
                  
              boolean success = true;
  
              // Start by getting the form for the current locale and Bean.
              Form form = resources.getForm(Locale.getDefault(), formName);
  
              System.out.println("\n\nValidating:");
              System.out.println(bean);
  
              // Iterate over each of the properties of the Bean which had messages.
              Iterator propertyNames = results.getPropertyNames().iterator();
              while (propertyNames.hasNext()) {
                  String propertyName = (String) propertyNames.next();
  
                  // Get the Field associated with that property in the Form
                  Field field = form.getField(propertyName);
  
                  // Look up the formatted name of the field from the Field arg0
                  String prettyFieldName = propertyName; //apps.getString(field.getArg(0).getKey());
  
                  // Get the result of validating the property.
                  ValidatorResult result = results.getValidatorResult(propertyName);
  
                  // Get all the actions run against the property, and iterate over their names.
                  Map actionMap = result.getActionMap();
                  Iterator keys = actionMap.keySet().iterator();
                  while (keys.hasNext()) {
                      String actName = (String) keys.next();
  
                      // Get the Action for that name.
                      ValidatorAction action = resources.getValidatorAction(actName);
  
                      // If the result is valid, print PASSED, otherwise print FAILED
                      System.out.println(
                          propertyName
                              + "["
                              + actName
                              + "] ("
                              + (result.isValid(actName) ? "PASSED" : "FAILED")
                              + ")");
  
                      //If the result failed, format the Action's message against the formatted field name
                      if (!result.isValid(actName)) {
                          success = false;
                          String message = "invalid field"; // apps.getString(action.getMsg());
                          if (actName.equals("doubleRange"))
                          {                        
                              Arg f1 = field.getArg(1);
                              Arg f2 = field.getArg(2);
                              Arg f0 = field.getArg(0);
                              Object[] args = { prettyFieldName, field.getVar("min").getValue(), field.getVar("max").getValue()  };
                              System.out.println(
                                      "     Error message will be: "
                                      + MessageFormat.format(message, args));                        
                          }
                          else
                          {
                              Object[] args = { prettyFieldName };
                              System.out.println(
                                      "     Error message will be: "
                                      + MessageFormat.format(message, args));
                          }
  
                      }
                  }
              }
              if (success) {
                  System.out.println("FORM VALIDATION PASSED");
              } else {
                  System.out.println("FORM VALIDATION FAILED");
              }
  
          }
      
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/GenericFrameworkPortlet.java
  
  Index: GenericFrameworkPortlet.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks;
  
  import java.io.IOException;
  import java.lang.reflect.Method;
  import java.util.Iterator;
  import java.util.Map;
  import java.util.StringTokenizer;
  
  import javax.portlet.ActionRequest;
  import javax.portlet.ActionResponse;
  import javax.portlet.PortletConfig;
  import javax.portlet.PortletContext;
  import javax.portlet.PortletException;
  import javax.portlet.PortletMode;
  import javax.portlet.PortletModeException;
  import javax.portlet.PortletPreferences;
  import javax.portlet.PortletRequest;
  import javax.portlet.PortletRequestDispatcher;
  import javax.portlet.ReadOnlyException;
  import javax.portlet.RenderRequest;
  import javax.portlet.RenderResponse;
  import javax.portlet.WindowState;
  import javax.portlet.WindowStateException;
  
  import org.apache.commons.beanutils.BeanUtils;
  
  import org.apache.portals.bridges.frameworks.model.ForwardConstants;
  import org.apache.portals.bridges.frameworks.model.ModelBean;
  import org.apache.portals.bridges.frameworks.model.PortletApplicationModel;
  import org.apache.portals.bridges.frameworks.spring.PortletApplicationModelImpl;
  import org.apache.portals.bridges.velocity.GenericVelocityPortlet;
  
  /**
   * SpringVelocityPortlet
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: GenericFrameworkPortlet.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public class GenericFrameworkPortlet extends GenericVelocityPortlet
  {    
      /**
       * Init Parameter: default spring configuration property
       */
      private static final String INITPARAM_SPRING_CONFIG = "spring-configuration";
  
      /**
       * Init Parameter: default velocity configuration property
       */
      private static final String INITPARAM_VALIDATOR_CONFIG = "validator-configuration";
      
      /**
       * Action signature for calling velocity portlet actions
       */
      private static final Class[] VELOCITY_PORTLET_ACTION_SIGNATURE = 
      {
              ActionRequest.class,
              ActionResponse.class
      };
      
      private static PortletApplicationModel model = null;
      
      private static Object semaphore = new Object();
      
      public GenericFrameworkPortlet()
      {
      }
  
      public void init(PortletConfig config)
      throws PortletException
      {
          super.init(config);
  
          String springConfig = this.getInitParameter(INITPARAM_SPRING_CONFIG);
          if (springConfig == null)
          {
              throw new PortletException("Spring Configuration file not specified");    
          }
  
          String validatorConfig = this.getInitParameter(INITPARAM_VALIDATOR_CONFIG);
  
          synchronized (semaphore)
          {
              if (null == model)
              {
                  model = new PortletApplicationModelImpl(springConfig, validatorConfig);
                  model.init(config);
              }
          }        
      }
      
      /** 
       * Invoke the velocity portlet pipeline:
       * (1) determine the logical view
       * (2) restore state from Form to Bean
       * (3) validate the bean
       * -- or --
       * (2) restore state from Form to Prefs
       * 
       * (4) execute the velocity action
       * (5) forward to another view 
       * 
       */
      public void processAction(ActionRequest request, ActionResponse response)
      throws PortletException, IOException
      {
          // (1) Determine the current view        
          String view = determineLogicalView(request);
          
          Object bean = null;
          ModelBean mb = model.getBean(view); 
              
          if (mb.getBeanType() == ModelBean.PREFS_MAP)
          {
              // (2) restore state from Form to Prefs
              bean = formToPrefs(request, view, mb);
          }
          else
          {
              // (2) restore state from Form to Bean
              bean = formToBean(request, view, mb);
          }
          
          String forward = null;
          
          // (3) validate the bean
          if (model.validate(bean, view))
          {
          
              // (4) execute the velocity action
              String action = request.getParameter("velocity.action");
              if (null == action)
              {
                  if (mb.getBeanType() == ModelBean.PREFS_MAP)
                  {
                      // store prefs
                      storePreferences(request, (Map)bean);
                  }
                  
                  forward = model.getForward(view, ForwardConstants.SUCCESS);
              }
              else
              {
                  // call the specified action in the post params
                  String actionForward = invokeVelocityPortletAction(action, request, response);
                  forward = model.getForward(actionForward);                
              }            
          }                
          else
          {
              // failed validation
              forward = model.getForward(view, ForwardConstants.FAILURE); 
          }
  
          // (5) forward to another view 
          forwardToView(request, response, forward);
          
      }
      
      protected void forwardToView(PortletRequest request, ActionResponse response, String forward)
      {
          if (forward == null)
          {
              return; // stay on same page
          }
          
          StringTokenizer tokenizer = new StringTokenizer(forward, ",");
          while (tokenizer.hasMoreTokens())
          {
              String token = tokenizer.nextToken();
              if (token.startsWith("mode:"))
              {
                  setPortletMode(response, token.substring("mode:".length()));
              }
              else if (token.startsWith("state:"))
              {
                  setWindowState(response, token.substring("state:".length()));                
              }
              else
              {
                  setLogicalView(response, token);
              }
          }                                        
          
      }
  
      private void setWindowState(ActionResponse response, String forward)
      {
          try
          {
              if (forward.equals("maximized"))
              {
                  response.setWindowState(WindowState.MAXIMIZED);
              }
              else if (forward.equals("minimized"))
              {
                  response.setWindowState(WindowState.MINIMIZED);
              }
              else if (forward.equals("normal"))
              {
                  response.setWindowState(WindowState.NORMAL);
              }
          }
          catch (WindowStateException e)
          {
          }
      }
      
      private void setPortletMode(ActionResponse response, String forward)
      {
          try
          {
              if (forward.equals("view"))
              {
                  response.setPortletMode(PortletMode.VIEW);
              }
              else if (forward.equals("edit"))
              {
                  response.setPortletMode(PortletMode.EDIT);
              }
              else if (forward.equals("help"))
              {
                  response.setPortletMode(PortletMode.HELP);
              }            
          }
          catch (PortletModeException e)
          {
          }
      }
      
      protected void storePreferences(PortletRequest request, Map bean)
      throws IOException, PortletException
      {
          String key = "none";
          
          try
          {
              PortletPreferences prefs = request.getPreferences();
              Iterator it = bean.entrySet().iterator();
              while (it.hasNext())
              {
                  Map.Entry entry = (Map.Entry)it.next();
                  key = (String)entry.getKey();
                  if (!prefs.isReadOnly(key))
                  {
                      prefs.setValue(key, (String)entry.getValue());
                  }
              }
              prefs.store();
          }
          catch (ReadOnlyException roe)
          {
              throw new PortletException("Failed to set preference " + key + ", value is readonly");
          }
          
      }
          
      /**
       * Get the current logical view based on velocity.view request parameter
       * If the request parameter is not found, fall back to init param
       *  
       * @param request
       * @return the current view
       * @throws PortletException
       */
      protected String determineLogicalView(PortletRequest request)
      throws PortletException
      {
          // TODO: we could store the current view in the session
          String view = request.getParameter("velocity.view");
          if (view == null)
          {
              if (request.getPortletMode().equals(PortletMode.VIEW))
              {
                  view = this.getDefaultViewPage();
              }
              else if (request.getPortletMode().equals(PortletMode.EDIT))
              {
                  view = this.getDefaultEditPage();
              }
              else if (request.getPortletMode().equals(PortletMode.HELP))
              {
                  view = this.getDefaultHelpPage();
              }
              if (null == view)
              {
                  throw new PortletException("Portlet error: cant find view resource for portlet: " + this.getPortletName());
              }
          }
          return view;        
      }
          
      protected void setLogicalView(ActionResponse response, String view)
      {
          response.setRenderParameter("velocity.view", view);
      }
      
      protected Object formToBean(ActionRequest request, String view, ModelBean mb)
      throws PortletException
      {        
          
          // try to get the bean from the session first
          Object bean = request.getPortletSession().getAttribute(mb.getBeanName());
          if (bean == null)
          {
              bean = model.createBean(mb);            
              if (bean == null)
              {
                  throw new PortletException("Portlet Action error in creating bean for view: " + view);
              }
              request.getPortletSession().setAttribute(mb.getBeanName(), bean);
          }
          
          Map params = request.getParameterMap();
          try
          {
              BeanUtils.populate(bean, params);
          }
          catch (Exception e)
          {
              throw new PortletException("Portlet Action error in  populating bean: " + mb.getBeanName(), e);
          }
          return bean;
      }
      
      protected Object formToPrefs(ActionRequest request, String view, ModelBean mb)
      throws PortletException
      {        
          Map params = request.getParameterMap();
          Map bean = (Map)request.getPortletSession().getAttribute(view + ".prefs");
          if (bean == null)
          {
              PortletPreferences prefs = request.getPreferences();
              
              bean = model.createPrefsBean(mb, prefs.getMap());            
              
              request.getPortletSession().setAttribute(view + ".prefs", bean);            
          }
          
          try
          {
              Iterator it = params.entrySet().iterator();
              while (it.hasNext())
              {
                  Map.Entry entry = (Map.Entry)it.next();
                  Object value = entry.getValue();                
                  String key = (String)entry.getKey();
                  if (null == bean.get(key))
                  {
                      continue;
                  }
                  if (value instanceof String)
                  {
                      bean.put(key, value);
                  }
                  else if (value instanceof String[])
                  {
                      bean.put(key, ((String[])value)[0]);
                  }
              }           
          }
          catch (Exception e)
          {
              throw new PortletException("Portlet Action error in  populating bean: ", e);
          }
          return bean;
      }
      
      /**
       * Invokes a specific Velocity Portlet Action
       * All portlet actions must have the signature:
       * 
       * String methodName(ActionRequest request, ActionResponse response)
       * 
       * @param methodName
       */
      protected String invokeVelocityPortletAction(String methodName, ActionRequest request, ActionResponse response)
      throws PortletException
      {
          try
          {                                           
              Method method = this.getClass().getMethod(methodName, VELOCITY_PORTLET_ACTION_SIGNATURE);
              Object[] parameters = 
              {
                      request,
                      response
              };
              String result = (String)method.invoke(this, parameters);
              return result;
          }
          catch (Exception e)
          {
              throw new PortletException("Failed to invoke portlet action: " + methodName, e);
          }
      }
  
      public void doView(RenderRequest request, RenderResponse response)
      throws PortletException, IOException
      {
          doRender(request, response);
      }
  
      public void doHelp(RenderRequest request, RenderResponse response)
      throws PortletException, IOException
      {
          doRender(request, response);
      }
      
      public void doEdit(RenderRequest request, RenderResponse response)
      throws PortletException, IOException
      {
          doRender(request, response);
      }
      
      protected void doRender(RenderRequest request, RenderResponse response)
      throws PortletException, IOException
      {
          String view = determineLogicalView(request);
          if (view == null)
          {
              throw new PortletException("Logical View not found: " + view);
          }
          
          String template = model.getTemplate(view);
          if (template == null)
          {
              throw new PortletException("Template not found for Logical View: " + view);
          }
  
          ModelBean mb = model.getBean(view);
          if (mb.getBeanType() == ModelBean.PREFS_MAP)
          {
              prefsToContext(request, view, mb);
          }
          else
          {
              beanToContext(request, view, mb);
          }
          
          PortletContext context = getPortletContext();        
          PortletRequestDispatcher rd = context.getRequestDispatcher(template);
          rd.include(request, response);
      } 
          
      
      private void beanToContext(RenderRequest request, String view, ModelBean mb)
      {
          Object bean = request.getPortletSession().getAttribute(mb.getBeanName());
          if (bean == null)
          {
              bean = model.createBean(mb);
              if (bean == null)
              {
                  return;
              }
              request.getPortletSession().setAttribute(mb.getBeanName(), bean);
          }
          putRequestVariable(request, mb.getBeanName(), bean);        
      }
      
      private void prefsToContext(RenderRequest request, String view, ModelBean mb)
      {                   
          Map bean = (Map)request.getPortletSession().getAttribute(view + ".prefs");
          if (bean == null)
          {
              PortletPreferences prefs = request.getPreferences();            
              bean = model.createPrefsBean(mb, prefs.getMap());            
              request.getPortletSession().setAttribute(view + ".prefs", bean);            
          }
          putRequestVariable(request, "prefs", bean);        
      }
      
      /**
       * Specific for Velocity
       * 
       * @param name
       * @param value
       */
      protected void putRequestVariable(RenderRequest request, String name, Object value)
      {
          request.setAttribute(name, value);
      }
  
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/src/java/org/apache/portals/bridges/frameworks/VelocityFrameworkPortlet.java
  
  Index: VelocityFrameworkPortlet.java
  ===================================================================
  /*
   * 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.portals.bridges.frameworks;
  
  import javax.portlet.RenderRequest;
  
  
  /**
   * VelocityFrameworkPortlet
   * 
   * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
   * @version $Id: VelocityFrameworkPortlet.java,v 1.1 2004/11/04 18:09:33 taylor Exp $
   */
  public class VelocityFrameworkPortlet extends GenericFrameworkPortlet
  {
      /**
       * Specific for Velocity
       * 
       * @param name
       * @param value
       */
      protected void putRequestVariable(RenderRequest request, String name, Object value)
      {
          this.getContext(request).put(name, value);
      }
  
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portals-bridges/frameworks/xdocs/navigation.xml
  
  Index: navigation.xml
  ===================================================================
  <?xml version="1.0" encoding="ISO-8859-1"?>
  <!--
  Copyright 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.
  -->
  <project>
    <body>
        <links>
          <item name="Jetspeed 2" href="../../index.html"/>
        </links>
    </body>
  </project>
  
  
  

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


Mime
View raw message