예제 #1
0
  public int doStartTag() throws JspException {
    JspWriter out = pageContext.getOut();
    if (Log.isEnabled(this, Log.DEBUG)) {
      Log.println(this, StringUtil.beanToString(this, null, TagSupport.class, true));
    }
    link =
        WebAppEnvironmentPlugin.getEnvironment()
            .getConfigurableResources()
            .getParameter("helppath");

    String onClickMessage = this.onClickMessage;
    if (onClickMessage == null && onClickMessageKey != null) {
      onClickMessage = RequestUtils.message(pageContext, null, null, onClickMessageKey);
    }
    String title = this.title;
    if (title == null && titleKey != null) {
      title = RequestUtils.message(pageContext, null, null, titleKey);
    }
    if (link != null && link.length() > 0) {
      Map parameters = new HashMap();
      if (context != null) {
        parameters.put("context", context);
      }
      link = ServletParameterHelper.replaceDynamicParameters(link, parameters);

      try {
        out.write(
            "<a href=\""
                + addContextPath(link)
                + "\" "
                + (style != null ? "class=\"" + style + "\" " : "")
                + " "
                + (target != null ? " target=\"" + target + "\"" : "")
                + (onClickMessage != null
                    ? " onClick=\"return confirm('" + onClickMessage + "')\""
                    : "")
                + (title != null ? " title=\"" + title + "\" " : "")
                + ">");
        return EVAL_BODY_INCLUDE;
      } catch (IOException e) {
        link = null;
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
    return SKIP_BODY;
  }
예제 #2
0
  /**
   * Initialize the <code>Validator</code> to perform validation.
   *
   * @param key The key that the validation rules are under (the form elements
   * name attribute).
   * @param bean The bean validation is being performed on.
   * @param application servlet context
   * @param request The current request object.
   * @param errors The object any errors will be stored in.
   * @param page This in conjunction with  the page property of a
   * <code>Field<code> can control the processing of fields.  If the field's
   * page is less than or equal to this page value, it will be processed.
   */
  public static Validator initValidator(
      String key,
      Object bean,
      ServletContext application,
      HttpServletRequest request,
      ActionMessages errors,
      int page) {

    ValidatorResources resources = Resources.getValidatorResources(application, request);

    Locale locale = RequestUtils.getUserLocale(request, null);

    Validator validator = new Validator(resources, key);
    validator.setUseContextClassLoader(true);

    validator.setPage(page);

    validator.setParameter(SERVLET_CONTEXT_PARAM, application);
    validator.setParameter(HTTP_SERVLET_REQUEST_PARAM, request);
    validator.setParameter(Validator.LOCALE_PARAM, locale);
    validator.setParameter(ACTION_MESSAGES_PARAM, errors);
    validator.setParameter(Validator.BEAN_PARAM, bean);

    return validator;
  }
  /**
   * Introspect our form bean configuration to identify the supported properties.
   *
   * @param config The FormBeanConfig instance describing the properties of the bean to be created
   * @exception IllegalArgumentException if the bean implementation class specified in the
   *     configuration is not DynaActionForm (or a subclass of DynaActionForm)
   */
  protected void introspect(FormBeanConfig config) {

    this.config = config;

    // Validate the ActionFormBean implementation class
    try {
      beanClass = RequestUtils.applicationClass(config.getType());
    } catch (Throwable t) {
      throw new IllegalArgumentException(
          "Cannot instantiate ActionFormBean class '" + config.getType() + "': " + t);
    }
    if (!DynaActionForm.class.isAssignableFrom(beanClass)) {
      throw new IllegalArgumentException(
          "Class '"
              + config.getType()
              + "' is not a subclass of "
              + "'org.apache.struts.action.DynaActionForm'");
    }

    // Set the name we will know ourselves by from the form bean name
    this.name = config.getName();

    // Look up the property descriptors for this bean class
    FormPropertyConfig descriptors[] = config.findFormPropertyConfigs();
    if (descriptors == null) {
      descriptors = new FormPropertyConfig[0];
    }

    // Create corresponding dynamic property definitions
    properties = new DynaProperty[descriptors.length];
    for (int i = 0; i < descriptors.length; i++) {
      properties[i] = new DynaProperty(descriptors[i].getName(), descriptors[i].getTypeClass());
      propertiesMap.put(properties[i].getName(), properties[i]);
    }
  }
  /**
   * Make sure that the specified <code>className</code> identfies a class which can be found and
   * which implements the <code>ActionContext</code> interface.
   *
   * @param className Fully qualified name of
   * @throws ServletException If an error occurs during initialization
   * @throws UnavailableException if class does not implement ActionContext or is not found
   */
  private void setActionContextClassName(String className) throws ServletException {
    if ((className != null) && (className.trim().length() > 0)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("setActionContextClassName: requested context class: " + className);
      }

      try {
        Class actionContextClass = RequestUtils.applicationClass(className);

        if (!ActionContext.class.isAssignableFrom(actionContextClass)) {
          throw new UnavailableException(
              "ActionContextClass "
                  + "["
                  + className
                  + "]"
                  + " must implement ActionContext interface.");
        }

        this.setActionContextClass(actionContextClass);
      } catch (ClassNotFoundException e) {
        throw new UnavailableException("ActionContextClass " + className + " not found.");
      }
    } else {
      if (LOG.isDebugEnabled()) {
        LOG.debug("setActionContextClassName: no className specified");
      }

      this.setActionContextClass(null);
    }
  }
예제 #5
0
  /**
   * Create a controller from specified classname
   *
   * @param classname Controller classname.
   * @return org.apache.struts.tiles.Controller
   * @throws InstantiationException if an error occur while instanciating Controller : (classname
   *     can't be instanciated, Illegal access with instanciated class, Error while instanciating
   *     class, classname can't be instanciated.
   */
  public static Controller createControllerFromClassname(String classname)
      throws InstantiationException {

    try {
      Class requestedClass = RequestUtils.applicationClass(classname);
      Object instance = requestedClass.newInstance();

      if (log.isDebugEnabled()) {
        log.debug("Controller created : " + instance);
      }
      return (Controller) instance;

    } catch (java.lang.ClassNotFoundException ex) {
      throw new InstantiationException("Error - Class not found :" + ex.getMessage());

    } catch (java.lang.IllegalAccessException ex) {
      throw new InstantiationException("Error - Illegal class access :" + ex.getMessage());

    } catch (java.lang.InstantiationException ex) {
      throw ex;

    } catch (java.lang.ClassCastException ex) {
      throw new InstantiationException(
          "Controller of class '"
              + classname
              + "' should implements 'Controller' or extends 'Action'");
    }
  }
  /**
   * Create Definition factory from provided classname. If a factory class name is provided, a
   * factory of this class is created. Otherwise, a default factory is created. Factory must have a
   * constructor taking ServletContext and Map as parameter.
   *
   * @param classname Class name of the factory to create.
   * @param servletContext Servlet Context passed to newly created factory.
   * @param properties Map of name/property passed to newly created factory.
   * @return newly created factory.
   * @throws DefinitionsFactoryException If an error occur while initializing factory
   */
  public ComponentDefinitionsFactory createFactoryFromClassname(
      ServletContext servletContext, Map properties, String classname)
      throws DefinitionsFactoryException {

    if (classname == null) {
      return createFactory(servletContext, properties);
    }

    // Try to create from classname
    try {
      Class factoryClass = RequestUtils.applicationClass(classname);
      ComponentDefinitionsFactory factory =
          (ComponentDefinitionsFactory) factoryClass.newInstance();
      factory.initFactory(servletContext, properties);
      return factory;

    } catch (ClassCastException ex) { // Bad classname
      throw new DefinitionsFactoryException(
          "Error - createDefinitionsFactory : Factory class '"
              + classname
              + " must implements 'ComponentDefinitionsFactory'.",
          ex);

    } catch (ClassNotFoundException ex) { // Bad classname
      throw new DefinitionsFactoryException(
          "Error - createDefinitionsFactory : Bad class name '" + classname + "'.", ex);

    } catch (InstantiationException ex) { // Bad constructor or error
      throw new DefinitionsFactoryException(ex);

    } catch (IllegalAccessException ex) {
      throw new DefinitionsFactoryException(ex);
    }
  }
예제 #7
0
 private String getMessageResource(PageContext pageContext, String key) {
   try {
     return RequestUtils.message(
         pageContext, "PUBLIC_DEGREE_INFORMATION", Globals.LOCALE_KEY, key);
   } catch (JspException e) {
     return "???" + key + "???";
   }
 }
예제 #8
0
 @Override
 protected String getDirectLinkContext(HttpServletRequest request) {
   Unit unit = getUnit(request);
   Site site = unit.getSite();
   try {
     return site == null
         ? null
         : RequestUtils.absoluteURL(request, site.getReversePath()).toString();
   } catch (MalformedURLException e) {
     return null;
   }
 }
예제 #9
0
  /**
   * Gets the <code>ActionMessage</code> based on the <code>ValidatorAction</code> message and the
   * <code>Field</code>'s arg objects.
   *
   * @param request the servlet request
   * @param va Validator action
   * @param field the validator Field
   */
  public static ActionMessage getActionMessage(
      HttpServletRequest request, ValidatorAction va, Field field) {

    String args[] =
        getArgs(
            va.getName(),
            getMessageResources(request),
            RequestUtils.getUserLocale(request, null),
            field);

    String msg = field.getMsg(va.getName()) != null ? field.getMsg(va.getName()) : va.getMsg();

    return new ActionMessage(msg, args);
  }
예제 #10
0
  /** Process the start tag */
  public int doStartTag() throws javax.servlet.jsp.JspException {

    // Look up the requested property value
    if (name != null) {
      Object beanValue = RequestUtils.lookup(pageContext, name, property, scope);
      if (cat.isDebugEnabled()) cat.debug("Value is : '" + beanValue + "'");
      if (beanValue == null) return (EVAL_BODY_TAG);

      // set the property as value
      setValue(beanValue.toString());
    }

    // Continue processing this page
    return (EVAL_BODY_TAG);
  }
예제 #11
0
 private ActionForm createNewActionForm(ActionMapping mapping, HttpServletRequest request) {
   String name = mapping.getName();
   FormBeanConfig config = moduleConfig.findFormBeanConfig(name);
   if (config == null) {
     log.warn("No FormBeanConfig found under '" + name + "'");
     return (null);
   }
   ActionForm instance = RequestUtils.createActionForm(config, servlet);
   if ("request".equals(mapping.getScope())) {
     request.setAttribute(mapping.getAttribute(), instance);
   } else {
     HttpSession session = request.getSession();
     session.setAttribute(mapping.getAttribute(), instance);
   }
   return instance;
 }
  public Object createObject(Attributes attributes) {

    // Identify the name of the class to instantiate
    String className = attributes.getValue("className");
    if (className == null) {
      ModuleConfig mc = (ModuleConfig) digester.peek(1);
      className = mc.getActionForwardClass();
    }

    // Instantiate the new object and return it
    Object actionForward = null;
    try {
      actionForward = RequestUtils.applicationInstance(className);
    } catch (Exception e) {
      digester.getLogger().error("ActionForwardFactory.createObject: ", e);
    }

    return actionForward;
  }
예제 #13
0
  /**
   * Gets the <code>ActionMessage</code> based on the <code>ValidatorAction</code> message and the
   * <code>Field</code>'s arg objects.
   *
   * @param validator the Validator
   * @param request the servlet request
   * @param va Validator action
   * @param field the validator Field
   */
  public static ActionMessage getActionMessage(
      Validator validator, HttpServletRequest request, ValidatorAction va, Field field) {

    Msg msg = field.getMessage(va.getName());
    if (msg != null && !msg.isResource()) {
      return new ActionMessage(msg.getKey(), false);
    }

    String msgKey = null;
    String msgBundle = null;
    if (msg == null) {
      msgKey = va.getMsg();
    } else {
      msgKey = msg.getKey();
      msgBundle = msg.getBundle();
    }

    if (msgKey == null || msgKey.length() == 0) {
      return new ActionMessage("??? " + va.getName() + "." + field.getProperty() + " ???", false);
    }

    ServletContext application =
        (ServletContext) validator.getParameterValue(SERVLET_CONTEXT_PARAM);
    MessageResources messages = getMessageResources(application, request, msgBundle);
    Locale locale = RequestUtils.getUserLocale(request, null);

    Arg[] args = field.getArgs(va.getName());
    String[] argValues = getArgValues(application, request, messages, locale, args);

    ActionMessage actionMessage = null;
    if (msgBundle == null) {
      actionMessage = new ActionMessage(msgKey, argValues);
    } else {
      String message = messages.getMessage(locale, msgKey, argValues);
      actionMessage = new ActionMessage(message, false);
    }
    return actionMessage;
  }
예제 #14
0
  /**
   * Instantiate any <code>RuleSet</code> classes defined in the <code>rulesets</code> property and
   * use them to add rules to our <code>Digester</code>.
   *
   * @param digester the Digester instance to add RuleSet objects to.
   * @throws ServletException
   */
  protected void applyRuleSets(Digester digester) throws ServletException {
    if ((this.rulesets == null) || (this.rulesets.trim().length() == 0)) {
      return;
    }

    rulesets = rulesets.trim();

    String ruleSet = null;

    while (rulesets.length() > 0) {
      int comma = rulesets.indexOf(",");

      if (comma < 0) {
        ruleSet = rulesets.trim();
        rulesets = "";
      } else {
        ruleSet = rulesets.substring(0, comma).trim();
        rulesets = rulesets.substring(comma + 1).trim();
      }

      if (log.isDebugEnabled()) {
        // TODO Internationalize msg
        log.debug("Configuring custom Digester Ruleset of type " + ruleSet);
      }

      try {
        RuleSet instance = (RuleSet) RequestUtils.applicationInstance(ruleSet);

        digester.addRuleSet(instance);
      } catch (Exception e) {
        // TODO Internationalize msg
        log.error("Exception configuring custom Digester RuleSet", e);
        throw new ServletException(e);
      }
    }
  }
예제 #15
0
 /**
  * @see javax.servlet.jsp.tagext.TagSupport#doEndTag() {@inheritDoc} Méthode de lancement du tag
  */
 public int doStartTag() throws JspException {
   // Publie
   String[] elementsTab = (String[]) RequestUtils.lookup(pageContext, name, property, null);
   FieldTag field = new FieldTag();
   field.setSize("60");
   if (elementsTab != null) {
     // On supprime les chaînes vides du tableau
     elementsTab = SqualeWebActionUtils.cleanValues(elementsTab);
   }
   // cas particulier, aucun champ n'a été rempli
   if (elementsTab == null || elementsTab.length == 0) {
     elementsTab = new String[] {""};
   }
   // charge la page dans le tag a exécuter
   field.setPageContext(pageContext);
   // premier champ obligatoire
   field.setIsRequired(isRequired);
   field.setKey(key);
   field.setProperty(property);
   field.setDisabled(disabled);
   field.setStyleClassLabel("td1");
   String result = "";
   for (int i = 0; i < elementsTab.length; i++) {
     if (i == 1) {
       field.setIsRequired("false");
     }
     // positionne la valeur
     field.setValue(elementsTab[i]);
     ResponseUtils.write(pageContext, "<tr class=\"fondClair\">");
     // lance le tag de welcom
     field.doStartTag();
     field.doEndTag();
     ResponseUtils.write(pageContext, "</tr>");
   }
   return SKIP_BODY;
 }
예제 #16
0
  /**
   * Render the specified error messages if there are any.
   *
   * @exception JspException if a JSP exception has occurred
   */
  public int doStartTag() throws JspException {

    // Were any error messages specified?
    ActionErrors errors = null;
    try {
      errors = RequestUtils.getActionErrors(pageContext, name);
    } catch (JspException e) {
      RequestUtils.saveException(pageContext, e);
      throw e;
    }

    if ((errors == null) || errors.isEmpty()) {
      return (EVAL_BODY_INCLUDE);
    }

    boolean headerPresent = RequestUtils.present(pageContext, bundle, locale, "errors.header");

    boolean footerPresent = RequestUtils.present(pageContext, bundle, locale, "errors.footer");

    boolean prefixPresent = RequestUtils.present(pageContext, bundle, locale, "errors.prefix");

    boolean suffixPresent = RequestUtils.present(pageContext, bundle, locale, "errors.suffix");

    // Render the error messages appropriately
    StringBuffer results = new StringBuffer();
    boolean headerDone = false;
    String message = null;
    Iterator reports = (property == null) ? errors.get() : errors.get(property);

    while (reports.hasNext()) {
      ActionError report = (ActionError) reports.next();
      if (!headerDone) {
        if (headerPresent) {
          message = RequestUtils.message(pageContext, bundle, locale, "errors.header");

          results.append(message);
          results.append(lineEnd);
        }
        headerDone = true;
      }

      if (prefixPresent) {
        message = RequestUtils.message(pageContext, bundle, locale, "errors.prefix");
        results.append(message);
      }

      message =
          RequestUtils.message(pageContext, bundle, locale, report.getKey(), report.getValues());

      if (message != null) {
        results.append(message);
        results.append(lineEnd);
      }

      if (suffixPresent) {
        message = RequestUtils.message(pageContext, bundle, locale, "errors.suffix");
        results.append(message);
      }
    }

    if (headerDone && footerPresent) {
      message = RequestUtils.message(pageContext, bundle, locale, "errors.footer");
      results.append(message);
      results.append(lineEnd);
    }

    ResponseUtils.write(pageContext, results.toString());

    return (EVAL_BODY_INCLUDE);
  }
  /**
   * Create an appropriate form bean in the appropriate scope, if one does not already exist.
   *
   * @param context FacesContext for the current request
   * @exception IllegalArgumentException if no ActionConfig for the specified action attribute can
   *     be located
   * @exception IllegalArgumentException if no FormBeanConfig for the specified form bean can be
   *     located
   * @exception IllegalArgumentException if no ModuleConfig can be located for this application
   *     module
   */
  public void createActionForm(FacesContext context) {

    // Look up the application module configuration information we need
    ModuleConfig moduleConfig = lookupModuleConfig(context);

    // Look up the ActionConfig we are processing
    String action = getAction();
    ActionConfig actionConfig = moduleConfig.findActionConfig(action);
    if (actionConfig == null) {
      throw new IllegalArgumentException("Cannot find action '" + action + "' configuration");
    }

    // Does this ActionConfig specify a form bean?
    String name = actionConfig.getName();
    if (name == null) {
      return;
    }

    // Look up the FormBeanConfig we are processing
    FormBeanConfig fbConfig = moduleConfig.findFormBeanConfig(name);
    if (fbConfig == null) {
      throw new IllegalArgumentException("Cannot find form bean '" + name + "' configuration");
    }

    // Does a usable form bean attribute already exist?
    String attribute = actionConfig.getAttribute();
    String scope = actionConfig.getScope();
    ActionForm instance = null;
    if ("request".equals(scope)) {
      instance = (ActionForm) context.getExternalContext().getRequestMap().get(attribute);
    } else if ("session".equals(scope)) {
      HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
      instance = (ActionForm) context.getExternalContext().getSessionMap().get(attribute);
    }
    if (instance != null) {
      if (fbConfig.getDynamic()) {
        String className = ((DynaBean) instance).getDynaClass().getName();
        if (className.equals(fbConfig.getName())) {
          if (log.isDebugEnabled()) {
            log.debug(
                " Recycling existing DynaActionForm instance " + "of type '" + className + "'");
          }
          return;
        }
      } else {
        try {
          Class configClass = RequestUtils.applicationClass(fbConfig.getType());
          if (configClass.isAssignableFrom(instance.getClass())) {
            if (log.isDebugEnabled()) {
              log.debug(
                  " Recycling existing ActionForm instance "
                      + "of class '"
                      + instance.getClass().getName()
                      + "'");
            }
            return;
          }
        } catch (Throwable t) {
          throw new IllegalArgumentException(
              "Cannot load form bean class '" + fbConfig.getType() + "'");
        }
      }
    }

    // Create a new form bean instance
    if (fbConfig.getDynamic()) {
      try {
        DynaActionFormClass dynaClass = DynaActionFormClass.createDynaActionFormClass(fbConfig);
        instance = (ActionForm) dynaClass.newInstance();
        if (log.isDebugEnabled()) {
          log.debug(
              " Creating new DynaActionForm instance " + "of type '" + fbConfig.getType() + "'");
          log.trace(" --> " + instance);
        }
      } catch (Throwable t) {
        throw new IllegalArgumentException(
            "Cannot create form bean of type '" + fbConfig.getType() + "'");
      }
    } else {
      try {
        instance = (ActionForm) RequestUtils.applicationInstance(fbConfig.getType());
        if (log.isDebugEnabled()) {
          log.debug(" Creating new ActionForm instance " + "of type '" + fbConfig.getType() + "'");
          log.trace(" --> " + instance);
        }
      } catch (Throwable t) {
        throw new IllegalArgumentException(
            "Cannot create form bean of class '" + fbConfig.getType() + "'");
      }
    }

    // Configure and cache the form bean instance in the correct scope
    ActionServlet servlet =
        (ActionServlet)
            context.getExternalContext().getApplicationMap().get(Globals.ACTION_SERVLET_KEY);
    instance.setServlet(servlet);
    if ("request".equals(scope)) {
      context.getExternalContext().getRequestMap().put(attribute, instance);
    } else if ("session".equals(scope)) {
      context.getExternalContext().getSessionMap().put(attribute, instance);
    }
  }
예제 #18
0
 /**
  * Get the <code>Locale</code> of the current user.
  *
  * @param request servlet request
  * @deprecated Use RequestUtils.getUserLocale() instead. This will be removed after Struts 1.2.
  */
 public static Locale getLocale(HttpServletRequest request) {
   return RequestUtils.getUserLocale(request, null);
 }
예제 #19
0
  /**
   * Gets the <code>Locale</code> sensitive value based on the key passed in.
   *
   * @param request servlet request
   * @param key the request key
   */
  public static String getMessage(HttpServletRequest request, String key) {
    MessageResources messages = getMessageResources(request);

    return getMessage(messages, RequestUtils.getUserLocale(request, null), key);
  }