/** * This is the action called from the Struts framework. * * @param mapping The ActionMapping used to select this instance. * @param request The HTTP Request we are processing. * @return */ @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); MessageResources messages = MessageResources.getMessageResources("com.myapp.struts.ApplicationResource"); Locale locale = request.getLocale(); if (getValores() == null || getValores().length < 1) { errors.add( "valores", new ActionMessage("errors.required", messages.getMessage(locale, "texto.valores"))); } if (getSstock() == null || getSstock().length() < 1) { stock = -1; } else { try { stock = Integer.parseInt(getSstock()); } catch (Exception Ex) { errors.add( "stock", new ActionMessage("errors.integer", messages.getMessage(locale, "texto.stock"))); } } if (getSprecio() != null && getSprecio().length() > 0) { try { Pattern pat = Pattern.compile("^[0-9]+([,.][0-9]{1,2})?$"); Matcher mat = pat.matcher(getSprecio()); if (mat.find()) { precio = new BigDecimal(getSprecio().replace(',', '.')); } else { errors.add("precio", new ActionMessage("errors.precio.mask")); } } catch (Exception Ex) { errors.add( "precio", new ActionMessage("errors.float", messages.getMessage(locale, "texto.precio"))); } } return errors; }
/** * Abstract base class for the various input tags. * * @version $Rev: 54929 $ $Date: 2005/11/16 10:51:48 $ */ public abstract class BaseInputTag extends BaseHandlerTag { // ----------------------------------------------------- Instance Variables /** The number of character columns for this field, or negative for no limit. */ protected String cols = null; /** The maximum number of characters allowed, or negative for no limit. */ protected String maxlength = null; /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); /** The name of the field (and associated property) being processed. */ protected String property = null; /** The number of rows for this field, or negative for no limit. */ protected String rows = null; /** * The value for this field, or <code>null</code> to retrieve the corresponding property from our * associated bean. */ protected String value = null; /** The name of the bean containing our underlying property. */ protected String name = Constants.BEAN_KEY; // ------------------------------------------------------------- Properties public String getName() { return (this.name); } public void setName(String name) { this.name = name; } /** Return the number of columns for this field. */ public String getCols() { return (this.cols); } /** * Set the number of columns for this field. * * @param cols The new number of columns */ public void setCols(String cols) { this.cols = cols; } /** Return the maximum length allowed. */ public String getMaxlength() { return (this.maxlength); } /** * Set the maximum length allowed. * * @param maxlength The new maximum length */ public void setMaxlength(String maxlength) { this.maxlength = maxlength; } /** Return the property name. */ public String getProperty() { return (this.property); } /** * Set the property name. * * @param property The new property name */ public void setProperty(String property) { this.property = property; } /** Return the number of rows for this field. */ public String getRows() { return (this.rows); } /** * Set the number of rows for this field. * * @param rows The new number of rows */ public void setRows(String rows) { this.rows = rows; } /** Return the size of this field (synonym for <code>getCols()</code>). */ public String getSize() { return (getCols()); } /** * Set the size of this field (synonym for <code>setCols()</code>). * * @param size The new size */ public void setSize(String size) { setCols(size); } /** Return the field value (if any). */ public String getValue() { return (this.value); } /** * Set the field value (if any). * * @param value The new field value, or <code>null</code> to retrieve the corresponding property * from the bean */ public void setValue(String value) { this.value = value; } // --------------------------------------------------------- Public Methods /** * Process the start of this tag. The default implementation does nothing. * * @exception JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { return (EVAL_BODY_TAG); } /** * Process the end of this tag. The default implementation does nothing. * * @exception JspException if a JSP exception has occurred */ public int doEndTag() throws JspException { return (EVAL_PAGE); } /** * Prepare the name element * * @return The element name. */ protected String prepareName() throws JspException { if (property == null) { return null; } // * @since Struts 1.1 if (indexed) { StringBuffer results = new StringBuffer(); prepareIndex(results, name); results.append(property); return results.toString(); } return property; } /** Release any acquired resources. */ public void release() { super.release(); name = Constants.BEAN_KEY; cols = null; maxlength = null; property = null; rows = null; value = null; } }
/** * An <strong>ExceptionHandler</strong> is configured in the Struts configuration file to handle a * specific type of exception thrown by an <code>Action.execute</code> method. * * @since Struts 1.1 */ public class ExceptionHandler { /** * The name of a configuration property which can be set to specify an alternative path which * should be used when the HttpServletResponse has already been committed. * * <p>To use this, in your <code>struts-config.xml</code> specify the exception handler like this: * * <pre> * <exception * key="GlobalExceptionHandler.default" * type="java.lang.Exception" * path="/ErrorPage.jsp"> * <set-property key="INCLUDE_PATH" value="/error.jsp" /> * </exception> * </pre> * * <p>You would want to use this when your normal ExceptionHandler path is a Tiles definition or * otherwise unsuitable for use in an <code>include</code> context. If you do not use this, and * you do not specify "SILENT_IF_COMMITTED" then the ExceptionHandler will attempt to forward to * the same path which would be used in normal circumstances, specified using the "path" attribute * in the <exception> element. * * @since Struts 1.3 */ public static final String INCLUDE_PATH = "INCLUDE_PATH"; /** * The name of a configuration property which indicates that Struts should do nothing if the * response has already been committed. This suppresses the default behavior, which is to use an * "include" rather than a "forward" in this case in hopes of providing some meaningful * information to the browser. * * <p>To use this, in your <code>struts-config.xml</code> specify the exception handler like this: * * <pre> * <exception * key="GlobalExceptionHandler.default" * type="java.lang.Exception" * path="/ErrorPage.jsp"> * <set-property key="SILENT_IF_COMMITTED" value="true" /> * </exception> * </pre> * * To be effective, this value must be defined to the literal String "true". If it is not defined * or defined to any other value, the default behavior will be used. * * <p>You only need to use this if you do not want error information displayed in the browser when * Struts intercepts an exception after the response has been committed. * * @since Struts 1.3 */ public static final String SILENT_IF_COMMITTED = "SILENT_IF_COMMITTED"; /** Commons logging instance. */ private static final Log LOG = LogFactory.getLog(ExceptionHandler.class); /** The message resources for this package. */ private static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.action.LocalStrings"); /** * Handle the Exception. Return the ActionForward instance (if any) returned by the called * ExceptionHandler. * * @param ex The exception to handle * @param ae The ExceptionConfig corresponding to the exception * @param mapping The ActionMapping we are processing * @param formInstance The ActionForm we are processing * @param request The servlet request we are processing * @param response The servlet response we are creating * @return The <code>ActionForward</code> instance (if any) returned by the called <code> * ExceptionHandler</code>. * @throws ServletException if a servlet exception occurs * @since Struts 1.1 */ public ActionForward execute( Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { LOG.debug("ExceptionHandler executing for exception " + ex); ActionForward forward; ActionMessage error; String property; // Build the forward from the exception mapping if it exists // or from the form input if (ae.getPath() != null) { forward = new ActionForward(ae.getPath()); } else { forward = mapping.getInputForward(); } // Figure out the error if (ex instanceof ModuleException) { error = ((ModuleException) ex).getActionMessage(); property = ((ModuleException) ex).getProperty(); } else { error = new ActionMessage(ae.getKey(), ex.getMessage()); property = error.getKey(); } this.logException(ex); // Store the exception request.setAttribute(Globals.EXCEPTION_KEY, ex); this.storeException(request, property, error, forward, ae.getScope()); if (!response.isCommitted()) { return forward; } LOG.debug( "Response is already committed, so forwarding will not work." + " Attempt alternate handling."); if (!silent(ae)) { handleCommittedResponse(ex, ae, mapping, formInstance, request, response, forward); } else { LOG.warn( "ExceptionHandler configured with " + SILENT_IF_COMMITTED + " and response is committed.", ex); } return null; } /** * Attempt to give good information when the response has already been committed when the * exception was thrown. This happens often when Tiles is used. Base implementation will see if * the INCLUDE_PATH property has been set, or if not, it will attempt to use the same path to * which control would have been forwarded. * * @param ex The exception to handle * @param config The ExceptionConfig we are processing * @param mapping The ActionMapping we are processing * @param formInstance The ActionForm we are processing * @param request The servlet request we are processing * @param response The servlet response we are creating * @param actionForward The ActionForward we are processing * @since Struts 1.3 */ protected void handleCommittedResponse( Exception ex, ExceptionConfig config, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response, ActionForward actionForward) { String includePath = determineIncludePath(config, actionForward); if (includePath != null) { if (includePath.startsWith("/")) { LOG.debug( "response committed, " + "but attempt to include results " + "of actionForward path"); RequestDispatcher requestDispatcher = request.getRequestDispatcher(includePath); try { requestDispatcher.include(request, response); return; } catch (IOException e) { LOG.error( "IOException when trying to include " + "the error page path " + includePath, e); } catch (ServletException e) { LOG.error( "ServletException when trying to include " + "the error page path " + includePath, e); } } else { LOG.warn( "Suspicious includePath doesn't seem likely to work, " + "so skipping it: " + includePath + "; expected path to start with '/'"); } } LOG.debug("Include not available or failed; " + "try writing to the response directly."); try { response.getWriter().println("Unexpected error: " + ex); response.getWriter().println("<!-- "); ex.printStackTrace(response.getWriter()); response.getWriter().println("-->"); } catch (IOException e) { LOG.error("Error giving minimal information about exception", e); LOG.error("Original exception: ", ex); } } /** * Return a path to which an include should be attempted in the case when the response was * committed before the <code>ExceptionHandler</code> was invoked. * * <p>If the <code>ExceptionConfig</code> has the property <code>INCLUDE_PATH</code> defined, then * the value of that property will be returned. Otherwise, the ActionForward path is returned. * * @param config Configuration element * @param actionForward Forward to use on error * @return Path of resource to include * @since Struts 1.3 */ protected String determineIncludePath(ExceptionConfig config, ActionForward actionForward) { String includePath = config.getProperty("INCLUDE_PATH"); if (includePath == null) { includePath = actionForward.getPath(); } return includePath; } /** * Logs the <code>Exception</code> using commons-logging. * * @param e The Exception to LOG. * @since Struts 1.2 */ protected void logException(Exception e) { LOG.debug(messages.getMessage("exception.LOG"), e); } /** * Default implementation for handling an <code>ActionMessage</code> generated from an <code> * Exception</code> during <code>Action</code> delegation. The default implementation is to set an * attribute of the request or session, as defined by the scope provided (the scope from the * exception mapping). An <code>ActionMessages</code> instance is created, the error is added to * the collection and the collection is set under the <code>Globals.ERROR_KEY</code>. * * @param request The request we are handling * @param property The property name to use for this error * @param error The error generated from the exception mapping * @param forward The forward generated from the input path (from the form or exception mapping) * @param scope The scope of the exception mapping. * @since Struts 1.2 */ protected void storeException( HttpServletRequest request, String property, ActionMessage error, ActionForward forward, String scope) { ActionMessages errors = new ActionMessages(); errors.add(property, error); if ("request".equals(scope)) { request.setAttribute(Globals.ERROR_KEY, errors); } else { request.getSession().setAttribute(Globals.ERROR_KEY, errors); } } /** * Indicate whether this Handler has been configured to be silent. In the base implementation, * this is done by specifying the value <code>"true"</code> for the property "SILENT_IF_COMMITTED" * in the ExceptionConfig. * * @param config The ExceptionConfiguration we are handling * @return True if Handler is silent * @since Struts 1.3 */ private boolean silent(ExceptionConfig config) { return "true".equals(config.getProperty(SILENT_IF_COMMITTED)); } }
/** * This class contains the validwhen validation that is used in the validator-rules.xml file. * * @since Struts 1.2 */ public class ValidWhen { /** Commons Logging instance. */ private static final Log log = LogFactory.getLog(ValidWhen.class); /** The message resources for this package. */ private static MessageResources sysmsgs = MessageResources.getMessageResources("org.apache.struts.validator.LocalStrings"); /** Returns true if <code>obj</code> is null or a String. */ private static boolean isString(Object obj) { return (obj == null) ? true : String.class.isInstance(obj); } /** * Checks if the field matches the boolean expression specified in <code>test</code> parameter. * * @param bean The bean validation is being performed on. * @param va The <code>ValidatorAction</code> that is currently being performed. * @param field The <code>Field</code> object associated with the current field being validated. * @param errors The <code>ActionMessages</code> object to add errors to if any validation errors * occur. * @param request Current request object. * @return <code>true</code> if meets stated requirements, <code>false</code> otherwise. */ public static boolean validateValidWhen( Object bean, ValidatorAction va, Field field, ActionMessages errors, Validator validator, HttpServletRequest request) { Object form = validator.getParameterValue(Validator.BEAN_PARAM); String value = null; boolean valid = false; int index = -1; if (field.isIndexed()) { String key = field.getKey(); final int leftBracket = key.indexOf("["); final int rightBracket = key.indexOf("]"); if ((leftBracket > -1) && (rightBracket > -1)) { index = Integer.parseInt(key.substring(leftBracket + 1, rightBracket)); } } if (isString(bean)) { value = (String) bean; } else { value = ValidatorUtils.getValueAsString(bean, field.getProperty()); } String test = null; try { test = Resources.getVarValue("test", field, validator, request, true); } catch (IllegalArgumentException ex) { String logErrorMsg = sysmsgs.getMessage( "validation.failed", "validwhen", field.getProperty(), validator.getFormName(), ex.toString()); log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } // Create the Lexer ValidWhenLexer lexer = null; try { lexer = new ValidWhenLexer(new StringReader(test)); } catch (Exception ex) { String logErrorMsg = "ValidWhenLexer Error for field ' " + field.getKey() + "' - " + ex; log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } // Create the Parser ValidWhenParser parser = null; try { parser = new ValidWhenParser(lexer); } catch (Exception ex) { String logErrorMsg = "ValidWhenParser Error for field ' " + field.getKey() + "' - " + ex; log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } parser.setForm(form); parser.setIndex(index); parser.setValue(value); try { parser.expression(); valid = parser.getResult(); } catch (Exception ex) { String logErrorMsg = "ValidWhen Error for field ' " + field.getKey() + "' - " + ex; log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } if (!valid) { errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field)); return false; } return true; } }
/** * Custom tag that retrieves an internationalized messages string (with optional parametric * replacement) from the <code>ActionResources</code> object stored as a context attribute by our * associated <code>ActionServlet</code> implementation. * * @version $Rev: 376840 $ $Date: 2005-09-16 09:38:33 -0400 (Fri, 16 Sep 2005) $ */ public class MessageTag extends TagSupport { /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.taglib.bean.LocalStrings"); // ------------------------------------------------------------- Properties /** The first optional argument. */ protected String arg0 = null; /** The second optional argument. */ protected String arg1 = null; /** The third optional argument. */ protected String arg2 = null; /** The fourth optional argument. */ protected String arg3 = null; /** The fifth optional argument. */ protected String arg4 = null; /** The servlet context attribute key for our resources. */ protected String bundle = null; /** The message key of the message to be retrieved. */ protected String key = null; /** Name of the bean that contains the message key. */ protected String name = null; /** Name of the property to be accessed on the specified bean. */ protected String property = null; /** The scope to be searched to retrieve the specified bean. */ protected String scope = null; /** The session scope key under which our Locale is stored. */ protected String localeKey = Globals.LOCALE_KEY; public String getArg0() { return (this.arg0); } public void setArg0(String arg0) { this.arg0 = arg0; } public String getArg1() { return (this.arg1); } public void setArg1(String arg1) { this.arg1 = arg1; } public String getArg2() { return (this.arg2); } public void setArg2(String arg2) { this.arg2 = arg2; } public String getArg3() { return (this.arg3); } public void setArg3(String arg3) { this.arg3 = arg3; } public String getArg4() { return (this.arg4); } public void setArg4(String arg4) { this.arg4 = arg4; } public String getBundle() { return (this.bundle); } public void setBundle(String bundle) { this.bundle = bundle; } public String getKey() { return (this.key); } public void setKey(String key) { this.key = key; } public String getName() { return (this.name); } public void setName(String name) { this.name = name; } public String getProperty() { return (this.property); } public void setProperty(String property) { this.property = property; } public String getScope() { return (this.scope); } public void setScope(String scope) { this.scope = scope; } public String getLocale() { return (this.localeKey); } public void setLocale(String localeKey) { this.localeKey = localeKey; } // --------------------------------------------------------- Public Methods /** * Process the start tag. * * @throws JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { String key = this.key; if (key == null) { // Look up the requested property value Object value = TagUtils.getInstance().lookup(pageContext, name, property, scope); if ((value != null) && !(value instanceof String)) { JspException e = new JspException(messages.getMessage("message.property", key)); TagUtils.getInstance().saveException(pageContext, e); throw e; } key = (String) value; } // Construct the optional arguments array we will be using Object[] args = new Object[] {arg0, arg1, arg2, arg3, arg4}; // Retrieve the message string we are looking for String message = TagUtils.getInstance().message(pageContext, this.bundle, this.localeKey, key, args); if (message == null) { Locale locale = TagUtils.getInstance().getUserLocale(pageContext, this.localeKey); String localeVal = (locale == null) ? "default locale" : locale.toString(); JspException e = new JspException( messages.getMessage( "message.message", "\"" + key + "\"", "\"" + ((bundle == null) ? "(default bundle)" : bundle) + "\"", localeVal)); TagUtils.getInstance().saveException(pageContext, e); throw e; } TagUtils.getInstance().write(pageContext, message); return (SKIP_BODY); } /** Release any acquired resources. */ public void release() { super.release(); arg0 = null; arg1 = null; arg2 = null; arg3 = null; arg4 = null; bundle = Globals.MESSAGES_KEY; key = null; name = null; property = null; scope = null; localeKey = Globals.LOCALE_KEY; } }
/** * An abstract <strong>Action</strong> that dispatches to a public method that is named by the * request parameter whose name is specified by the <code>parameter</code> property of the * corresponding ActionMapping. This Action is useful for developers who prefer to combine many * similar actions into a single Action class, in order to simplify their application design. * * <p>To configure the use of this action in your <code>struts-config.xml</code> file, create an * entry like this: <code> * <action path="/saveSubscription" * type="org.apache.struts.actions.DispatchAction" * name="subscriptionForm" * scope="request" * input="/subscription.jsp" * parameter="method"/> * </code> * * <p>which will use the value of the request parameter named "method" to pick the appropriate * "execute" method, which must have the same signature (other than method name) of the standard * Action.execute method. For example, you might have the following three methods in the same * action: * * <ul> * <li>public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest * request, HttpServletResponse response) throws Exception * <li>public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest * request, HttpServletResponse response) throws Exception * <li>public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest * request, HttpServletResponse response) throws Exception * </ul> * * <p>and call one of the methods with a URL like this: <code> * http://localhost:8080/myapp/saveSubscription.do?method=update * </code> * * <p><strong>NOTE</strong> - All of the other mapping characteristics of this action must be shared * by the various handlers. This places some constraints over what types of handlers may reasonably * be packaged into the same <code>DispatchAction</code> subclass. * * @author Niall Pemberton <*****@*****.**> * @author Craig R. McClanahan * @author Ted Husted * @version $Revision: 1.14 $ $Date: 2003/02/18 04:01:07 $ */ public abstract class DispatchAction extends Action { // ----------------------------------------------------- Instance Variables /** The Class instance of this <code>DispatchAction</code> class. */ protected Class clazz = this.getClass(); /** Commons Logging instance. */ protected static Log log = LogFactory.getLog(DispatchAction.class); /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.actions.LocalStrings"); /** * The set of Method objects we have introspected for this class, keyed by method name. This * collection is populated as different methods are called, so that introspection needs to occur * only once per method name. */ protected HashMap methods = new HashMap(); /** * The set of argument type classes for the reflected method call. These are the same for all * calls, so calculate them only once. */ protected Class types[] = { ActionMapping.class, ActionForm.class, HttpServletRequest.class, HttpServletResponse.class }; // --------------------------------------------------------- Public Methods /** * Process the specified HTTP request, and create the corresponding HTTP response (or forward to * another web component that will create it). Return an <code>ActionForward</code> instance * describing where and how control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @exception Exception if an exception occurs */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Identify the request parameter containing the method name String parameter = mapping.getParameter(); if (parameter == null) { String message = messages.getMessage("dispatch.handler", mapping.getPath()); log.error(message); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return (null); } // Identify the method name to be dispatched to. // dispatchMethod() will call unspecified() if name is null String name = request.getParameter(parameter); // Invoke the named method, and return the result return dispatchMethod(mapping, form, request, response, name); } /** * Method which is dispatched to when there is no value for specified request parameter included * in the request. Subclasses of <code>DispatchAction</code> should override this method if they * wish to provide default behavior different than producing an HTTP "Bad Request" error. */ protected ActionForward unspecified( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String message = messages.getMessage("dispatch.parameter", mapping.getPath(), mapping.getParameter()); log.error(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return (null); } // ----------------------------------------------------- Protected Methods /** * Dispatch to the specified method. * * @since Struts 1.1 */ protected ActionForward dispatchMethod( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String name) throws Exception { // Make sure we have a valid method name to call. // This may be null if the user hacks the query string. if (name == null) { return this.unspecified(mapping, form, request, response); } // Identify the method object to be dispatched to Method method = null; try { method = getMethod(name); } catch (NoSuchMethodException e) { String message = messages.getMessage("dispatch.method", mapping.getPath(), name); log.error(message, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return (null); } ActionForward forward = null; try { Object args[] = {mapping, form, request, response}; forward = (ActionForward) method.invoke(this, args); } catch (ClassCastException e) { String message = messages.getMessage("dispatch.return", mapping.getPath(), name); log.error(message, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return (null); } catch (IllegalAccessException e) { String message = messages.getMessage("dispatch.error", mapping.getPath(), name); log.error(message, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return (null); } catch (InvocationTargetException e) { // Rethrow the target exception if possible so that the // exception handling machinery can deal with it Throwable t = e.getTargetException(); if (t instanceof Exception) { throw ((Exception) t); } else { String message = messages.getMessage("dispatch.error", mapping.getPath(), name); log.error(message, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return (null); } } // Return the returned ActionForward instance return (forward); } /** * Introspect the current class to identify a method of the specified name that accepts the same * parameter types as the <code>execute</code> method does. * * @param name Name of the method to be introspected * @exception NoSuchMethodException if no such method can be found */ protected Method getMethod(String name) throws NoSuchMethodException { synchronized (methods) { Method method = (Method) methods.get(name); if (method == null) { method = clazz.getMethod(name, types); methods.put(name, method); } return (method); } } }
/** * Define a scripting variable based on the value(s) of the specified parameter received with this * request. * * @version $Rev: 54929 $ $Date: 2004-10-16 17:38:42 +0100 (Sat, 16 Oct 2004) $ */ public class ParameterTag extends TagSupport { // ------------------------------------------------------------- Properties /** The name of the scripting variable that will be exposed as a page scope attribute. */ protected String id = null; public String getId() { return (this.id); } public void setId(String id) { this.id = id; } /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.taglib.bean.LocalStrings"); /** Return an array of parameter values if <code>multiple</code> is non-null. */ protected String multiple = null; public String getMultiple() { return (this.multiple); } public void setMultiple(String multiple) { this.multiple = multiple; } /** The name of the parameter whose value is to be exposed. */ protected String name = null; public String getName() { return (this.name); } public void setName(String name) { this.name = name; } /** The default value to return if no parameter of the specified name is found. */ protected String value = null; public String getValue() { return (this.value); } public void setValue(String value) { this.value = value; } // --------------------------------------------------------- Public Methods /** * Retrieve the required property and expose it as a scripting variable. * * @exception JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { // Deal with a single parameter value if (multiple == null) { String value = pageContext.getRequest().getParameter(name); if ((value == null) && (this.value != null)) { value = this.value; } if (value == null) { JspException e = new JspException(messages.getMessage("parameter.get", name)); TagUtils.getInstance().saveException(pageContext, e); throw e; } pageContext.setAttribute(id, value); return (SKIP_BODY); } // Deal with multiple parameter values String values[] = pageContext.getRequest().getParameterValues(name); if ((values == null) || (values.length == 0)) { if (this.value != null) { values = new String[] {this.value}; } } if ((values == null) || (values.length == 0)) { JspException e = new JspException(messages.getMessage("parameter.get", name)); TagUtils.getInstance().saveException(pageContext, e); throw e; } pageContext.setAttribute(id, values); return (SKIP_BODY); } /** Release all allocated resources. */ public void release() { super.release(); id = null; multiple = null; name = null; value = null; } }
/** * Define a scripting variable that will contain the number of elements found in a specified array, * Collection, or Map. * * @version $Rev: 54929 $ $Date: 2006/02/01 15:32:57 $ */ public class SizeTag extends TagSupport { // ------------------------------------------------------------- Properties /** The actual collection to be counted. */ protected Object collection = null; public Object getCollection() { return (this.collection); } public void setCollection(Object collection) { this.collection = collection; } /** The name of the scripting variable that will be exposed as a page scope attribute. */ protected String id = null; public String getId() { return (this.id); } public void setId(String id) { this.id = id; } /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.taglib.bean.LocalStrings"); /** The name of the bean owning the property to be counted. */ protected String name = null; public String getName() { return (this.name); } public void setName(String name) { this.name = name; } /** The name of the property to be retrieved. */ protected String property = null; public String getProperty() { return (this.property); } public void setProperty(String property) { this.property = property; } /** The scope within which to search for the specified bean. */ protected String scope = null; public String getScope() { return (this.scope); } public void setScope(String scope) { this.scope = scope; } // --------------------------------------------------------- Public Methods /** * Retrieve the required property and expose it as a scripting variable. * * @exception JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { // Retrieve the required property value Object value = this.collection; if (value == null) { if (name == null) { // Must specify either a collection attribute or a name // attribute. JspException e = new JspException(messages.getMessage("size.noCollectionOrName")); TagUtils.getInstance().saveException(pageContext, e); throw e; } value = TagUtils.getInstance().lookup(pageContext, name, property, scope); } // Identify the number of elements, based on the collection type int size = 0; if (value == null) { JspException e = new JspException(messages.getMessage("size.collection")); TagUtils.getInstance().saveException(pageContext, e); throw e; } else if (value.getClass().isArray()) { size = Array.getLength(value); } else if (value instanceof Collection) { size = ((Collection) value).size(); } else if (value instanceof Map) { size = ((Map) value).size(); } else { JspException e = new JspException(messages.getMessage("size.collection")); TagUtils.getInstance().saveException(pageContext, e); throw e; } // Expose this size as a scripting variable pageContext.setAttribute(this.id, new Integer(size), PageContext.PAGE_SCOPE); return (SKIP_BODY); } /** Release all allocated resources. */ public void release() { super.release(); collection = null; id = null; name = null; property = null; scope = null; } }
/** * Custom tag that renders error messages if an appropriate request attribute has been created. The * tag looks for a request attribute with a reserved key, and assumes that it is either a String, a * String array, containing message keys to be looked up in the module's MessageResources, or an * object of type <code>org.apache.struts.action.ActionErrors</code>. * * <p>The following optional message keys will be utilized if corresponding messages exist for them * in the application resources: * * <ul> * <li><b>errors.header</b> - If present, the corresponding message will be rendered prior to the * individual list of error messages. * <li><b>errors.footer</b> - If present, the corresponding message will be rendered following the * individual list of error messages. * <li><b>errors.prefix</b> - If present, the corresponding message will be rendered before each * individual error message. * <li><b>errors.suffix</b> - If present, the corresponding message will be rendered after each * individual error message. * </ul> * * @version $Rev$ $Date: 2005-08-21 19:08:45 -0400 (Sun, 21 Aug 2005) $ */ public class ErrorsTag extends TagSupport { /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); // ----------------------------------------------------------- Properties /** The servlet context attribute key for our resources. */ protected String bundle = null; /** The session attribute key for our locale. */ protected String locale = Globals.LOCALE_KEY; /** The request attribute key for our error messages (if any). */ protected String name = Globals.ERROR_KEY; /** * The name of the property for which error messages should be returned, or <code>null</code> to * return all errors. */ protected String property = null; /** The message resource key for errors header. */ protected String header = null; /** The message resource key for errors footer. */ protected String footer = null; /** The message resource key for errors prefix. */ protected String prefix = null; /** The message resource key for errors suffix. */ protected String suffix = null; public String getBundle() { return (this.bundle); } public void setBundle(String bundle) { this.bundle = bundle; } public String getLocale() { return (this.locale); } public void setLocale(String locale) { this.locale = locale; } public String getName() { return (this.name); } public void setName(String name) { this.name = name; } public String getProperty() { return (this.property); } public void setProperty(String property) { this.property = property; } public String getHeader() { return (header == null) ? "errors.header" : header; } public void setHeader(String header) { this.header = header; } public String getFooter() { return (footer == null) ? "errors.footer" : footer; } public void setFooter(String footer) { this.footer = footer; } public String getPrefix() { return (prefix == null) ? "errors.prefix" : prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return (suffix == null) ? "errors.suffix" : suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } // ------------------------------------------------------- Public Methods /** * Render the specified error messages if there are any. * * @throws JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { // Were any error messages specified? ActionMessages errors = null; try { errors = TagUtils.getInstance().getActionMessages(pageContext, name); } catch (JspException e) { TagUtils.getInstance().saveException(pageContext, e); throw e; } if ((errors == null) || errors.isEmpty()) { return (EVAL_BODY_INCLUDE); } boolean headerPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getHeader()); boolean footerPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getFooter()); boolean prefixPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getPrefix()); boolean suffixPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getSuffix()); // 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()) { ActionMessage report = (ActionMessage) reports.next(); if (!headerDone) { if (headerPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getHeader()); results.append(message); } headerDone = true; } if (prefixPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getPrefix()); results.append(message); } if (report.isResource()) { message = TagUtils.getInstance() .message(pageContext, bundle, locale, report.getKey(), report.getValues()); } else { message = report.getKey(); } if (message != null) { results.append(message); } if (suffixPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getSuffix()); results.append(message); } } if (headerDone && footerPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getFooter()); results.append(message); } TagUtils.getInstance().write(pageContext, results.toString()); return (EVAL_BODY_INCLUDE); } /** Release any acquired resources. */ public void release() { super.release(); bundle = Globals.MESSAGES_KEY; locale = Globals.LOCALE_KEY; name = Globals.ERROR_KEY; property = null; header = null; footer = null; prefix = null; suffix = null; } }
/** @see es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBController */ public class NavegarETBControllerImpl extends NavegarETBController { private static final Logger logger = Logger.getLogger(NavegarETBControllerImpl.class); private static final MessageResources resources = MessageResources.getMessageResources("application-resources"); /** * @see * es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBController#navegarETB(org.apache.struts.action.ActionMapping, * es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public final void navegarETB( ActionMapping mapping, es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { /* * Se contemplan tres casos: * - idTermino != "0.0" y taxonomiaSession.taxonomia.jerarquia==null: Navegacion normal * - idTermino != "0.0" y taxonomiaSession.taxonomia.jerarquia!=null y taxonomiaSession.taxonomia.taxonPath == null: Seleccion de ruta padre * - idTermino == "0.0": preparar la seleccion de ruta padre */ String idTermino = form.getIdTermino(); TaxonomiaVO taxonomiaSession = this.getTesauroSession(request).getTaxonomia(); if (logger.isDebugEnabled()) logger.debug( "NavegarTesauro con parametros idTermino = " + idTermino + " y taxonomia (session) = " + taxonomiaSession); TaxonomiaVO taxonomia = null; if ("0.0".equals(idTermino)) { if (taxonomiaSession == null) throw new ValidatorException("Error de sesion: tesauroSession == null"); form.setIdTermino(null); taxonomia = new TaxonomiaVO(); taxonomia.setTaxonPath(null); TaxonVO[] rutasDisponibles = componerRutasDisponibles(taxonomiaSession.getJerarquia()); taxonomia.setHijos(rutasDisponibles); taxonomia.setIdioma(taxonomiaSession.getIdioma()); taxonomia.setNombreTaxonomia(taxonomiaSession.getNombreTaxonomia()); taxonomia.setTaxonomias(taxonomiaSession.getTaxonomias()); taxonomia.setJerarquia(taxonomiaSession.getJerarquia()); } else { if (taxonomiaSession != null && taxonomiaSession.getJerarquia() != null && taxonomiaSession.getTaxonPath() == null) { // Seleccion de ruta padre entre disponibles: idTermino es la posicion en el array de // jerarquia int posicion = Integer.parseInt(idTermino); if (logger.isDebugEnabled()) logger.debug("Elegida la ruta " + posicion + " de las rutas padres disponibles"); TaxonVO[] rutaElegida = taxonomiaSession.getJerarquia()[posicion].getJerarquia(); String idRecuperar = rutaElegida[rutaElegida.length - 1].getId(); taxonomia = this.getSrvHerramientaModificacion() .navegarTesauro(idRecuperar, null, LdapUserDetailsUtils.getIdioma()); taxonomia.setTaxonPath(rutaElegida); taxonomia.setJerarquia(null); } else { // Navegacion normal taxonomia = this.getSrvHerramientaModificacion() .navegarTesauro(idTermino, null, LdapUserDetailsUtils.getIdioma()); } } // Compruebo el codigo 0.0 en el el primer taxon de taxonPath. Si lo encuentro, lo sustituyo por // el mensaje i18n correspondiente. if (taxonomia.getTaxonPath() != null && taxonomia.getTaxonPath()[0].getValorTax().equals("0.0")) { taxonomia.getTaxonPath()[0].setValorTax( resources.getMessage( (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE), "tesauros.varias.rutas")); } this.getTesauroSession(request).setTaxonomia(taxonomia); form.setTaxonomia(taxonomia); form.setIdTermino(form.getIdTermino()); form.setIdiomaBuscadorBackingList( IdiomasBuscadorSingleton.getInstance().obtenerIdiomas(LdapUserDetailsUtils.getIdioma()), "idLocalizacion", "nombre"); } private TaxonVO[] componerRutasDisponibles(JerarquiaVO[] jerarquias) { TaxonVO[] hijos = new TaxonVO[jerarquias.length]; for (int i = 0; i < jerarquias.length; i++) { TaxonVO hijo = new TaxonVO(); hijo.setId(String.valueOf(i)); hijo.setEsHoja(Boolean.TRUE); hijo.setValorTax(componerRuta(jerarquias[i].getJerarquia())); hijos[i] = hijo; } return hijos; } /** * @see * es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBController#selectAction(org.apache.struts.action.ActionMapping, * es.pode.modificador.presentacion.configurar.cambios.navegarETB.SelectActionForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public final java.lang.String selectAction( ActionMapping mapping, es.pode.modificador.presentacion.configurar.cambios.navegarETB.SelectActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String action = form.getAction(); if (logger.isDebugEnabled()) logger.debug("action = " + action); String result = null; if (resources .getMessage( (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE), "tesauro.navegar.aceptar") .equals(action)) { result = "Aceptar"; } else { this.removeTesauroSession(request); result = "Volver"; } return result; } /** * @see * es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBController#guardarTermino(org.apache.struts.action.ActionMapping, * es.pode.modificador.presentacion.configurar.cambios.navegarETB.GuardarTerminoForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public final void guardarTermino( ActionMapping mapping, es.pode.modificador.presentacion.configurar.cambios.navegarETB.GuardarTerminoForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { TaxonomiaVO taxonomia = this.getTesauroSession(request).getTaxonomia(); this.removeTesauroSession(request); String xml = this.getSrvHerramientaModificacion().generarETB(taxonomia); if (logger.isDebugEnabled()) logger.debug("Taxonomia generada para añadir tesauro: " + xml); this.getCambioSession(request).setValorNuevo(xml); this.getCambioSession(request).setLomTerm("lom.classification.taxonPath"); this.getCambioSession(request).setIdLomTerm("9.2"); } /** * @see * es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBController#comprobarJerarquias(org.apache.struts.action.ActionMapping, * es.pode.modificador.presentacion.configurar.cambios.navegarETB.ComprobarJerarquiasForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public final java.lang.String comprobarJerarquias( ActionMapping mapping, es.pode.modificador.presentacion.configurar.cambios.navegarETB.ComprobarJerarquiasForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Comprobar si el nodo seleccionado tiene varias rutas padre String result = null; TaxonomiaVO taxonomia = this.getTesauroSession(request).getTaxonomia(); if (taxonomia != null && taxonomia.getJerarquia() != null && taxonomia.getJerarquia().length > 1) { // Varios padres disponibles result = "VariosPadres"; } else { result = "UnPadre"; } return result; } /** * @see * es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBController#selectActionRutas(org.apache.struts.action.ActionMapping, * es.pode.modificador.presentacion.configurar.cambios.navegarETB.SelectActionRutasForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public final java.lang.String selectActionRutas( ActionMapping mapping, es.pode.modificador.presentacion.configurar.cambios.navegarETB.SelectActionRutasForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String result = null; String posicion = form.getPosicion(); String idTermino = form.getIdTermino(); String action = form.getAction(); if (logger.isDebugEnabled()) logger.debug("selectActionRutas con idTermino = " + idTermino + " : posicion = " + posicion); if (resources .getMessage( (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE), "tesauro.seleccionar.ruta.padre.aceptar") .equals(action)) { // Modifico el objeto en sesion para que quede con la ruta padre elegida TaxonomiaVO taxonomia = this.getTesauroSession(request).getTaxonomia(); JerarquiaVO[] jerarquia = taxonomia.getJerarquia(); taxonomia.setJerarquia(null); int iPosicion = Integer.parseInt(posicion); TaxonVO[] taxonPath = jerarquia[iPosicion].getJerarquia(); taxonomia.setTaxonPath(taxonPath); this.getTesauroSession(request).setTaxonomia(taxonomia); result = "Aceptar"; } else { result = "Cancelar"; } return result; } /** * @see * es.pode.modificador.presentacion.configurar.cambios.navegarETB.NavegarETBController#prepararSeleccion(org.apache.struts.action.ActionMapping, * es.pode.modificador.presentacion.configurar.cambios.navegarETB.PrepararSeleccionForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public final void prepararSeleccion( ActionMapping mapping, es.pode.modificador.presentacion.configurar.cambios.navegarETB.PrepararSeleccionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { TaxonomiaVO taxonomia = new TaxonomiaVO(); taxonomia.setTaxonPath(null); taxonomia.setIdioma(this.getTesauroSession(request).getTaxonomia().getIdioma()); JerarquiaVO[] jerarquia = this.getTesauroSession(request).getTaxonomia().getJerarquia(); // Componemos un array de taxones con las rutas padres TaxonVO[] hijos = componerRutasDisponibles(jerarquia); taxonomia.setHijos(hijos); form.setTaxonomia(taxonomia); form.setIdiomaBuscadorBackingList( IdiomasBuscadorSingleton.getInstance().obtenerIdiomas(LdapUserDetailsUtils.getIdioma()), "idLocalizacion", "nombre"); } private String componerRuta(TaxonVO[] taxones) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < taxones.length; i++) { sb.append(taxones[i].getValorTax()); if (i < taxones.length - 1) sb.append(" -> "); } return sb.toString(); } }
/** @author asnr and scpo */ public class GroupStudentEnrolment extends FenixService { private static final MessageResources messages = MessageResources.getMessageResources("resources/GlobalResources"); @Checked("RolePredicates.STUDENT_PREDICATE") @Service public static Boolean run(Integer studentGroupCode, String username) throws FenixServiceException { final StudentGroup studentGroup = rootDomainObject.readStudentGroupByOID(studentGroupCode); if (studentGroup == null) { throw new InvalidArgumentsServiceException(); } final Registration registration = Registration.readByUsername(username); if (registration == null) { throw new InvalidArgumentsServiceException(); } final Grouping grouping = studentGroup.getGrouping(); final Attends studentAttend = grouping.getStudentAttend(registration); if (studentAttend == null) { throw new NotAuthorizedException(); } if (studentGroup.getAttends().contains(studentAttend)) { throw new InvalidSituationServiceException(); } final IGroupEnrolmentStrategyFactory enrolmentGroupPolicyStrategyFactory = GroupEnrolmentStrategyFactory.getInstance(); final IGroupEnrolmentStrategy strategy = enrolmentGroupPolicyStrategyFactory.getGroupEnrolmentStrategyInstance(grouping); boolean result = strategy.checkPossibleToEnrolInExistingGroup(grouping, studentGroup); if (!result) { throw new InvalidArgumentsServiceException(); } checkIfStudentIsNotEnrolledInOtherGroups( grouping.getStudentGroups(), studentGroup, studentAttend); studentGroup.addAttends(studentAttend); informStudents(studentGroup, registration, grouping); return Boolean.TRUE; } private static void informStudents( final StudentGroup studentGroup, final Registration registration, final Grouping grouping) { final StringBuilder executionCourseNames = new StringBuilder(); for (final ExecutionCourse executionCourse : grouping.getExecutionCourses()) { if (executionCourseNames.length() > 0) { executionCourseNames.append(", "); } executionCourseNames.append(executionCourse.getNome()); } } private static void checkIfStudentIsNotEnrolledInOtherGroups( final List<StudentGroup> studentGroups, final StudentGroup studentGroupEnrolled, final Attends studentAttend) throws InvalidSituationServiceException { for (final StudentGroup studentGroup : studentGroups) { if (studentGroup != studentGroupEnrolled && studentGroup.getAttends().contains(studentAttend)) { throw new InvalidSituationServiceException(); } } } }
/** * Abstract base class for the various conditional evaluation tags. * * @version $Rev$ $Date$ */ public abstract class ConditionalTagBase extends TagSupport { // ------------------------------------------------------------- Properties /** The name of the cookie to be used as a variable. */ protected String cookie = null; public String getCookie() { return (this.cookie); } public void setCookie(String cookie) { this.cookie = cookie; } /** The name of the HTTP request header to be used as a variable. */ protected String header = null; public String getHeader() { return (this.header); } public void setHeader(String header) { this.header = header; } /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.taglib.logic.LocalStrings"); /** * The name of the JSP bean to be used as a variable (if <code>property</code> is not specified), * or whose property is to be accessed (if <code>property</code> is specified). */ protected String name = null; public String getName() { return (this.name); } public void setName(String name) { this.name = name; } /** The name of the HTTP request parameter to be used as a variable. */ protected String parameter = null; public String getParameter() { return (this.parameter); } public void setParameter(String parameter) { this.parameter = parameter; } /** The name of the bean property to be used as a variable. */ protected String property = null; public String getProperty() { return (this.property); } public void setProperty(String property) { this.property = property; } /** The name of the security role to be checked for. */ protected String role = null; public String getRole() { return (this.role); } public void setRole(String role) { this.role = role; } /** The scope to search for the bean named by the name property, or "any scope" if null. */ protected String scope = null; public String getScope() { return (this.scope); } public void setScope(String scope) { this.scope = scope; } /** The user principal name to be checked for. */ protected String user = null; public String getUser() { return (this.user); } public void setUser(String user) { this.user = user; } // --------------------------------------------------------- Public Methods /** * Perform the test required for this particular tag, and either evaluate or skip the body of this * tag. * * @exception JspException if a JSP exception occurs */ public int doStartTag() throws JspException { if (condition()) return (EVAL_BODY_INCLUDE); else return (SKIP_BODY); } /** * Evaluate the remainder of the current page normally. * * @exception JspException if a JSP exception occurs */ public int doEndTag() throws JspException { return (EVAL_PAGE); } /** Release all allocated resources. */ public void release() { super.release(); cookie = null; header = null; name = null; parameter = null; property = null; role = null; scope = null; user = null; } // ------------------------------------------------------ Protected Methods /** * Evaluate the condition that is being tested by this particular tag, and return <code>true * </code> if the nested body content of this tag should be evaluated, or <code>false</code> if it * should be skipped. This method must be implemented by concrete subclasses. * * @exception JspException if a JSP exception occurs */ protected abstract boolean condition() throws JspException; }
/** * Metodo che inizializza e ottiene le istanze degli oggetti necessari alla creazione della * tabella */ private void initValues() throws Exception { getLogger().beginMethod("initValues()"); paginator = new Paginator( (HttpServletRequest) pageContext.getRequest(), businessDelegateName, businessDelegateMethodName, parameterName, this.useSmartLoading); // se in sessione è stato inserito il valore desiderato per il numero di elementi per pagina usa // quello Object businessDelegateParameter = SessionManager.getAttribute( ((HttpServletRequest) pageContext.getRequest()).getSession(false), parameterName); String attributeKey = PagerUtils.getKeyPaginatorModel( businessDelegateName, businessDelegateMethodName, businessDelegateParameter); String sessParamNumElementsPerPage = (String) pageContext.getSession().getAttribute(attributeKey + "_paramNumElementsPerPage"); if (sessParamNumElementsPerPage != null) { try { paginator.setMaxRowPage(Integer.parseInt(sessParamNumElementsPerPage)); } catch (NumberFormatException e1) { } } else { // altrimenti usa il parametro impostato nel tag del pager, se è stato valorizzato // se è stato specificato l'attributo maxRowsToShow // lo imposto al paginator if (maxRowsToShow != null && !maxRowsToShow.trim().equals("")) { try { paginator.setMaxRowPage(Integer.parseInt(maxRowsToShow)); } catch (NumberFormatException e1) { } } else try { paginator.setMaxRowPage(8); } catch (NumberFormatException e1) { } } // quale pagina devo visualizzare ? // String page = (String) pageContext.getRequest().getParameter( // "pageToShow"); String page = null; if (page == null) { if (pageToShowParamName == null) page = (String) pageContext.getRequest().getAttribute("pageToShow"); else { page = (String) pageContext.getRequest().getAttribute(pageToShowParamName); } if (page == null) page = (String) pageContext.getRequest().getParameter(pageToShowParamName); if (page == null || page.equals("")) { page = (String) pageContext.getRequest().getParameter("pageToShow"); } } PagerModel pagerModel = null; if (page == null) { pagerModel = (PagerModel) SessionManager.getAttribute( ((HttpServletRequest) pageContext.getRequest()).getSession(false), attributeKey); if (pagerModel == null) { pagerModel = new PagerModel(); // pagerModel.setTableModel(tableModel); SessionManager.addAttribute( ((HttpServletRequest) pageContext.getRequest()).getSession(false), attributeKey, pagerModel); } else { page = pagerModel.getActualPage() + ""; } } // se page non esiste o è un numero negativo, lo inizializzo ad 1 if (page != null) { try { pageToShow = Integer.parseInt(page); } catch (NumberFormatException e) { pageToShow = 1; } } else { pageToShow = 1; } // pageContext.getRequest().setAttribute("pageToShow", "" + pageToShow); if (pageToShowParamName == null) pageContext.getRequest().setAttribute("pageToShow", "" + pageToShow); else { pageContext.getRequest().setAttribute(pageToShowParamName, "" + pageToShow); } getLogger().debug("TableTag::Visualizzo la pagina numero " + pageToShow); columns = new Vector(); tableModel = new TableModel(); if ((bundle != null) && (!bundle.equals(""))) { messages = MessageResources.getMessageResources(bundle); } else { messages = MessageResources.getMessageResources( "it.mef.eidos.intese.resources.ApplicationResources"); } getLogger().debug("TableTag: fine initValues()"); }
/** * Abstract base class for comparison tags. Concrete subclasses need only define values for desired1 * and desired2. * * @version $Rev: 54929 $ $Date: 2004-10-16 17:38:42 +0100 (Sat, 16 Oct 2004) $ */ public abstract class CompareTagBase extends ConditionalTagBase { // ----------------------------------------------------- Instance Variables /** We will do a double/float comparison. */ protected static final int DOUBLE_COMPARE = 0; /** We will do a long/int comparison. */ protected static final int LONG_COMPARE = 1; /** We will do a String comparison. */ protected static final int STRING_COMPARE = 2; /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.taglib.logic.LocalStrings"); // ------------------------------------------------------------ Properties /** The value to which the variable specified by other attributes of this tag will be compared. */ public String value = null; public String getValue() { return (this.value); } public void setValue(String value) { this.value = value; } // --------------------------------------------------------- Public Methods /** Release all allocated resources. */ public void release() { super.release(); value = null; } // ------------------------------------------------------ Protected Methods /** * Evaluate the condition that is being tested by this particular tag, and return <code>true * </code> if the nested body content of this tag should be evaluated, or <code>false</code> if it * should be skipped. This method must be implemented by concrete subclasses. * * @exception JspException if a JSP exception occurs */ protected abstract boolean condition() throws JspException; /** * Evaluate the condition that is being tested by this particular tag, and return <code>true * </code> if the nested body content of this tag should be evaluated, or <code>false</code> if it * should be skipped. This method must be implemented by concrete subclasses. * * @param desired1 First desired value for a true result (-1, 0, +1) * @param desired2 Second desired value for a true result (-1, 0, +1) * @exception JspException if a JSP exception occurs */ protected boolean condition(int desired1, int desired2) throws JspException { // Acquire the value and determine the test type int type = -1; double doubleValue = 0.0; long longValue = 0; if ((type < 0) && (value.length() > 0)) { try { doubleValue = Double.parseDouble(value); type = DOUBLE_COMPARE; } catch (NumberFormatException e) {; } } if ((type < 0) && (value.length() > 0)) { try { longValue = Long.parseLong(value); type = LONG_COMPARE; } catch (NumberFormatException e) {; } } if (type < 0) { type = STRING_COMPARE; } // Acquire the unconverted variable value Object variable = null; if (cookie != null) { Cookie cookies[] = ((HttpServletRequest) pageContext.getRequest()).getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { if (cookie.equals(cookies[i].getName())) { variable = cookies[i].getValue(); break; } } } else if (header != null) { variable = ((HttpServletRequest) pageContext.getRequest()).getHeader(header); } else if (name != null) { Object bean = TagUtils.getInstance().lookup(pageContext, name, scope); if (property != null) { if (bean == null) { JspException e = new JspException(messages.getMessage("logic.bean", name)); TagUtils.getInstance().saveException(pageContext, e); throw e; } try { variable = PropertyUtils.getProperty(bean, property); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t == null) t = e; TagUtils.getInstance().saveException(pageContext, t); throw new JspException( messages.getMessage("logic.property", name, property, t.toString())); } catch (Throwable t) { TagUtils.getInstance().saveException(pageContext, t); throw new JspException( messages.getMessage("logic.property", name, property, t.toString())); } } else { variable = bean; } } else if (parameter != null) { variable = pageContext.getRequest().getParameter(parameter); } else { JspException e = new JspException(messages.getMessage("logic.selector")); TagUtils.getInstance().saveException(pageContext, e); throw e; } if (variable == null) { variable = ""; // Coerce null to a zero-length String } // Perform the appropriate comparison int result = 0; if (type == DOUBLE_COMPARE) { try { double doubleVariable = Double.parseDouble(variable.toString()); if (doubleVariable < doubleValue) result = -1; else if (doubleVariable > doubleValue) result = +1; } catch (NumberFormatException e) { result = variable.toString().compareTo(value); } } else if (type == LONG_COMPARE) { try { long longVariable = Long.parseLong(variable.toString()); if (longVariable < longValue) result = -1; else if (longVariable > longValue) result = +1; } catch (NumberFormatException e) { result = variable.toString().compareTo(value); } } else { result = variable.toString().compareTo(value); } // Normalize the result if (result < 0) result = -1; else if (result > 0) result = +1; // Return true if the result matches either desired value return ((result == desired1) || (result == desired2)); } }
/** * Define a scripting variable based on the value(s) of the specified bean property. * * @version $Rev: 376840 $ $Date: 2005-06-15 12:16:32 -0400 (Wed, 15 Jun 2005) $ */ public class DefineTag extends BodyTagSupport { /** Commons logging instance. */ private static final Log log = LogFactory.getLog(DefineTag.class); // ---------------------------------------------------- Protected variables /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.taglib.bean.LocalStrings"); /** The body content of this tag (if any). */ protected String body = null; // ------------------------------------------------------------- Properties /** The name of the scripting variable that will be exposed as a page scope attribute. */ protected String id = null; /** The name of the bean owning the property to be exposed. */ protected String name = null; /** The name of the property to be retrieved. */ protected String property = null; /** The scope within which to search for the specified bean. */ protected String scope = null; /** The scope within which the newly defined bean will be creatd. */ protected String toScope = null; /** The fully qualified Java class name of the value to be exposed. */ protected String type = null; /** The (String) value to which the defined bean will be set. */ protected String value = null; public String getId() { return (this.id); } public void setId(String id) { this.id = id; } public String getName() { return (this.name); } public void setName(String name) { this.name = name; } public String getProperty() { return (this.property); } public void setProperty(String property) { this.property = property; } public String getScope() { return (this.scope); } public void setScope(String scope) { this.scope = scope; } public String getToScope() { return (this.toScope); } public void setToScope(String toScope) { this.toScope = toScope; } public String getType() { return (this.type); } public void setType(String type) { this.type = type; } public String getValue() { return (this.value); } public void setValue(String value) { this.value = value; } // --------------------------------------------------------- Public Methods /** * Check if we need to evaluate the body of the tag * * @throws JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { return (EVAL_BODY_TAG); } /** * Save the body content of this tag (if any), or throw a JspException if the value was already * defined. * * @throws JspException if value was defined by an attribute */ public int doAfterBody() throws JspException { if (bodyContent != null) { body = bodyContent.getString(); if (body != null) { body = body.trim(); } if (body.length() < 1) { body = null; } } return (SKIP_BODY); } /** * Retrieve the required property and expose it as a scripting variable. * * @throws JspException if a JSP exception has occurred */ public int doEndTag() throws JspException { // Enforce restriction on ways to declare the new value int n = 0; if (this.body != null) { n++; } if (this.name != null) { n++; } if (this.value != null) { n++; } if (n > 1) { JspException e = new JspException(messages.getMessage("define.value", id)); TagUtils.getInstance().saveException(pageContext, e); throw e; } // Retrieve the required property value Object value = this.value; if ((value == null) && (name != null)) { value = TagUtils.getInstance().lookup(pageContext, name, property, scope); } if ((value == null) && (body != null)) { value = body; } if (value == null) { JspException e = new JspException(messages.getMessage("define.null", id)); TagUtils.getInstance().saveException(pageContext, e); throw e; } // Expose this value as a scripting variable int inScope = PageContext.PAGE_SCOPE; try { if (toScope != null) { inScope = TagUtils.getInstance().getScope(toScope); } } catch (JspException e) { log.warn("toScope was invalid name so we default to PAGE_SCOPE", e); } pageContext.setAttribute(id, value, inScope); // Continue processing this page return (EVAL_PAGE); } /** Release all allocated resources. */ public void release() { super.release(); body = null; id = null; name = null; property = null; scope = null; toScope = "page"; type = null; value = null; } }
/** * Tag for input fields of type "radio". * * @version $Rev$ $Date: 2005-06-14 14:26:17 -0400 (Tue, 14 Jun 2005) $ */ public class RadioTag extends BaseHandlerTag { // ----------------------------------------------------- Instance Variables /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); /** The name of the bean containing our underlying property. */ protected String name = Constants.BEAN_KEY; /** The property name for this field. */ protected String property = null; /** The body content of this tag (if any). */ protected String text = null; /** The server value for this option. */ protected String value = null; /** * Name of the bean (in some scope) that will return the value of the radio tag. * * <p>If an iterator is used to render a series of radio tags, this field may be used to specify * the name of the bean exposed by the iterator. In this case, the value attribute is used as the * name of a property on the <code>idName</code> bean that returns the value of the radio tag in * this iteration. */ protected String idName = null; public String getName() { return (this.name); } public void setName(String name) { this.name = name; } // ------------------------------------------------------------- Properties /** Return the property name. */ public String getProperty() { return (this.property); } /** * Set the property name. * * @param property The new property name */ public void setProperty(String property) { this.property = property; } /** Return the server value. */ public String getValue() { return (this.value); } /** * Set the server value. * * @param value The new server value */ public void setValue(String value) { this.value = value; } /** * Return the idName. * * @since Struts 1.1 */ public String getIdName() { return (this.idName); } /** * Set the idName. * * @param idName The new idName * @since Struts 1.1 */ public void setIdName(String idName) { this.idName = idName; } // --------------------------------------------------------- Public Methods /** * Generate the required input tag. [Indexed property since Struts 1.1] * * @throws JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { String radioTag = renderRadioElement(serverValue(), currentValue()); TagUtils.getInstance().write(pageContext, radioTag); this.text = null; return (EVAL_BODY_TAG); } /** * Return the String to be used in the radio tag's <code>value</code> attribute that gets sent to * the server on form submission. * * @throws JspException */ private String serverValue() throws JspException { // Not using indexed radio buttons if (this.idName == null) { return this.value; } String serverValue = this.lookupProperty(this.idName, this.value); return (serverValue == null) ? "" : serverValue; } /** * Acquire the current value of the bean specified by the <code>name</code> attribute and the * property specified by the <code>property</code> attribute. This radio button with this value * will be checked. * * @throws JspException */ private String currentValue() throws JspException { String current = this.lookupProperty(this.name, this.property); return (current == null) ? "" : current; } /** * Renders an HTML <input type="radio"> element. * * @param serverValue The data to be used in the tag's <code>value</code> attribute and sent to * the server when the form is submitted. * @param checkedValue If the serverValue equals this value the radio button will be checked. * @return A radio input element. * @throws JspException * @since Struts 1.1 */ protected String renderRadioElement(String serverValue, String checkedValue) throws JspException { StringBuffer results = new StringBuffer("<input type=\"radio\""); prepareAttribute(results, "name", prepareName()); prepareAttribute(results, "accesskey", getAccesskey()); prepareAttribute(results, "tabindex", getTabindex()); prepareAttribute(results, "value", TagUtils.getInstance().filter(serverValue)); if (serverValue.equals(checkedValue)) { results.append(" checked=\"checked\""); } results.append(prepareEventHandlers()); results.append(prepareStyles()); prepareOtherAttributes(results); results.append(getElementClose()); return results.toString(); } /** * Save the associated label from the body content. * * @throws JspException if a JSP exception has occurred */ public int doAfterBody() throws JspException { if (this.bodyContent != null) { String value = this.bodyContent.getString().trim(); if (value.length() > 0) { this.text = value; } } return (SKIP_BODY); } /** * Optionally render the associated label from the body content. * * @throws JspException if a JSP exception has occurred */ public int doEndTag() throws JspException { // Render any description for this radio button if (this.text != null) { TagUtils.getInstance().write(pageContext, text); } return (EVAL_PAGE); } /** * Prepare the name element * * @return The element name. */ protected String prepareName() throws JspException { if (property == null) { return null; } // * @since Struts 1.1 if (indexed) { StringBuffer results = new StringBuffer(); prepareIndex(results, name); results.append(property); return results.toString(); } return property; } /** Release any acquired resources. */ public void release() { super.release(); idName = null; name = Constants.BEAN_KEY; property = null; text = null; value = null; } }
/** * Custom tag that renders error messages if an appropriate request attribute has been created. The * tag looks for a request attribute with a reserved key, and assumes that it is either a String, a * String array, containing message keys to be looked up in the module's MessageResources, or an * object of type <code>org.apache.struts.action.ActionErrors</code>. * * <p>The following optional message keys will be utilized if corresponding messages exist for them * in the application resources: * * <ul> * <li><b>errors.header</b> - If present, the corresponding message will be rendered prior to the * individual list of error messages. * <li><b>errors.footer</b> - If present, the corresponding message will be rendered following the * individual list of error messages. * <li><b>errors.prefix</b> - If present, the corresponding message will be rendered before each * individual error message. * <li><b>errors.suffix</b> - If present, the corresponding message will be rendered after each * individual error message. * </ul> * * @author Craig R. McClanahan * @version $Revision: 1.21 $ $Date: 2003/05/15 23:43:42 $ */ public class ErrorsTag extends TagSupport { // ----------------------------------------------------------- Properties /** The servlet context attribute key for our resources. */ protected String bundle = null; public String getBundle() { return (this.bundle); } public void setBundle(String bundle) { this.bundle = bundle; } /** * The default locale on our server. * * @deprecated Use Locale.getDefault() directly. */ protected static Locale defaultLocale = Locale.getDefault(); /** The line ending string. */ protected static String lineEnd = System.getProperty("line.separator"); /** The session attribute key for our locale. */ protected String locale = Globals.LOCALE_KEY; public String getLocale() { return (this.locale); } public void setLocale(String locale) { this.locale = locale; } /** The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); /** The request attribute key for our error messages (if any). */ protected String name = Globals.ERROR_KEY; public String getName() { return (this.name); } public void setName(String name) { this.name = name; } /** * The name of the property for which error messages should be returned, or <code>null</code> to * return all errors. */ protected String property = null; public String getProperty() { return (this.property); } public void setProperty(String property) { this.property = property; } // ------------------------------------------------------- Public Methods /** * 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); } /** Release any acquired resources. */ public void release() { super.release(); bundle = Globals.MESSAGES_KEY; locale = Globals.LOCALE_KEY; name = Globals.ERROR_KEY; property = null; } }