/* * (non-Javadoc) * * @see org.hdiv.filter.IValidationHelper#endPage(javax.servlet.http. HttpServletRequest) */ public void endPage(HttpServletRequest request) { // End page in datacomposer boolean exist = HDIVUtil.isDataComposer(request); if (exist) { IDataComposer dataComposer = HDIVUtil.getDataComposer(request); dataComposer.endPage(); } }
/** * Gets the part of the url that represents the action to be executed in this request. * * @param request HttpServletRequest to validate * @return target Part of the url that represents the target action * @throws HDIVException */ protected String getTarget(HttpServletRequest request) { try { String requestUri = request.getRequestURI(); requestUri = HDIVUtil.stripSession(requestUri); return requestUri; } catch (Exception e) { String errorMessage = HDIVUtil.getMessage("helper.actionName"); throw new HDIVException(errorMessage, e); } }
protected final void setUp() throws Exception { String[] files = { "/org/hdiv/config/hdiv-core-applicationContext.xml", "/org/hdiv/config/hdiv-config.xml", "/org/hdiv/config/hdiv-validations.xml", "/org/hdiv/config/applicationContext-test.xml" }; if (this.applicationContext == null) { this.applicationContext = new ClassPathXmlApplicationContext(files); } // Servlet API mock HttpServletRequest request = (MockHttpServletRequest) this.applicationContext.getBean("mockRequest"); HttpSession httpSession = request.getSession(); ServletContext servletContext = httpSession.getServletContext(); HDIVUtil.setHttpServletRequest(request); // Initialize config this.config = (HDIVConfig) this.applicationContext.getBean("config"); // Initialize HttpSession InitListener initListener = new InitListener(); initListener.setConfig(this.config); initListener.initStrategies(this.applicationContext, httpSession); initListener.initCache(this.applicationContext, httpSession); initListener.initPageIdGenerator(this.applicationContext, httpSession); initListener.initHDIVState(this.applicationContext, httpSession); // Initialize HDIVConfig in ServletContext HDIVUtil.setHDIVConfig(this.config, servletContext); // Initialize IApplication in ServletContext IApplication application = (IApplication) this.applicationContext.getBean("application"); HDIVUtil.setApplication(application, servletContext); // Initialize MessageSource in ServletContext ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBeanClassLoader(this.applicationContext.getClassLoader()); String messageSourcePath = (String) this.applicationContext.getBean("messageSourcePath"); messageSource.setBasename(messageSourcePath); HDIVUtil.setMessageSource(messageSource, servletContext); // Initialize the IDataComposer DataComposerFactory dataComposerFactory = (DataComposerFactory) this.applicationContext.getBean("dataComposerFactory"); IDataComposer dataComposer = dataComposerFactory.newInstance(); HDIVUtil.setDataComposer(dataComposer, request); onSetUp(); }
@Override protected void setUp() throws Exception { super.setUp(); dataComposer = HDIVUtil.getDataComposer(request); dataComposer.beginRequest(Method.POST, "/testFormTag.do"); }
/* * (non-Javadoc) * * @see org.hdiv.filter.IValidationHelper#startPage(javax.servlet.http. HttpServletRequest) */ public void startPage(HttpServletRequest request) { // Don`t create IDataComposer if it is not necessary boolean exclude = this.hdivConfig.hasExtensionToExclude(request.getRequestURI()); if (!exclude) { // Init datacomposer IDataComposer dataComposer = this.dataComposerFactory.newInstance(request); HDIVUtil.setDataComposer(dataComposer, request); } }
/** * Generate the required input tag, followed by the optional rendered text. Support for <code> * write</code> property since Struts 1.1. * * @exception JspException if a JSP exception has occurred * @see org.hdiv.dataComposer.IDataComposer#composeFormField(String, String, boolean, String) */ public int doStartTag() throws JspException { try { String hiddenValue = value; Object lookupValue = null; if (value == null) { // locate and return the specified property of the specified bean lookupValue = TagUtils.getInstance().lookup(pageContext, name, property, null); if (lookupValue != null) { hiddenValue = lookupValue.toString(); } } HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest(); IDataComposer dataComposer = HDIVUtil.getDataComposer(request); this.encodedValue = dataComposer.composeFormField(prepareName(), hiddenValue, false, null); // Render the result to the output writer TagUtils.getInstance().write(this.pageContext, this.renderInputElement()); // Is rendering the value separately requested? if (!write) { return (EVAL_BODY_TAG); } // Calculate the value to be rendered separately // * @since Struts 1.1 String results = null; if (value != null) { results = TagUtils.getInstance().filter(value); } else { if (lookupValue == null) { results = ""; } else { results = TagUtils.getInstance().filter(lookupValue.toString()); } } // Render the result to the output writer TagUtils.getInstance().write(pageContext, results); return (EVAL_BODY_TAG); } catch (JspException e) { log.debug(e.getMessage()); throw e; } }
/** * Adds one parameter to the request. Since the HttpServletRequest object's parameters are * unchanged according to the Servlet specification, the instance of request should be passed as a * parameter of type RequestWrapper. * * @param request HttpServletRequest to validate * @param name new parameter name * @param value new parameter value * @throws HDIVException if the request object is not of type RequestWrapper */ protected void addParameterToRequest(HttpServletRequest request, String name, Object value) { RequestWrapper wrapper = null; if (request instanceof RequestWrapper) { wrapper = (RequestWrapper) request; } else { wrapper = (RequestWrapper) WebUtils.getNativeRequest(request, RequestWrapper.class); } if (wrapper != null) { wrapper.addParameter(name, value); } else { String errorMessage = HDIVUtil.getMessage("helper.notwrapper"); throw new HDIVException(errorMessage); } }
/** * Checks if all the received parameter <code>parameter</code> values are valid, that is, are * expected values. Received value number is checked and then these values are validated. * * @param request HttpServletRequest to validate * @param target Part of the url that represents the target action * @param state IState The restored state for this url * @param stateParameter parameter stored in state * @param parameter Parameter to validate * @param values parameter <code>parameter</code> values * @return valid result if the validation is correct. False otherwise. * @throws HDIVException if there is an error in parameter validation process. */ private ValidatorHelperResult validateParameterValues( HttpServletRequest request, String target, IState state, IParameter stateParameter, String parameter, String[] values) { try { // Only for required parameters must be checked if the number of received // values is the same as number of values in the state. If this wasn't // taken into account, this verification will be done for every parameter, // including for example, a multiple combo where hardly ever are all its // values received. if (stateParameter.isActionParam()) { if (values.length != stateParameter.getValues().size()) { String valueMessage = (values.length > stateParameter.getValues().size()) ? "extra value" : "more values expected"; this.logger.log(HDIVErrorCodes.VALUE_LENGTH_INCORRECT, target, parameter, valueMessage); return new ValidatorHelperResult(HDIVErrorCodes.VALUE_LENGTH_INCORRECT); } } ValidatorHelperResult result = this.hasRepeatedOrInvalidValues(target, parameter, values, stateParameter.getValues()); if (!result.isValid()) { return result; } // At this point, we know that the number of received values is the same // as the number of values sent to the client. Now we have to check if // the received values are all tha ones stored in the state. return this.validateReceivedValuesInState(request, target, state, parameter, values); } catch (Exception e) { String errorMessage = HDIVUtil.getMessage("validation.error", e.getMessage()); throw new HDIVException(errorMessage, e); } }
/** * Checks if the suffix added in the memory version to all requests in the HDIV parameter is the * same as the one stored in session, which is the original suffix. So any request using the * memory version should keep the suffix unchanged. * * @param value value received in the HDIV parameter * @return True if the received value of the suffix is valid. False otherwise. */ public boolean validateHDIVSuffix(String value) { int firstSeparator = value.indexOf("-"); int lastSeparator = value.lastIndexOf("-"); if (firstSeparator == -1) { return false; } if (firstSeparator >= lastSeparator) { return false; } try { // read hdiv's suffix from request String requestSuffix = value.substring(lastSeparator + 1); // read suffix from page stored in session String pageId = value.substring(0, firstSeparator); IPage currentPage = this.session.getPage(pageId); if (currentPage == null) { if (log.isErrorEnabled()) { log.error("Page with id [" + pageId + "] not found in session."); } throw new HDIVException(HDIVErrorCodes.PAGE_ID_INCORRECT); } return currentPage.getRandomToken().equals(requestSuffix); } catch (IndexOutOfBoundsException e) { String errorMessage = HDIVUtil.getMessage("validation.error", e.getMessage()); if (log.isErrorEnabled()) { log.error(errorMessage); } throw new HDIVException(errorMessage, e); } }
/** * Checks if the values of the parameters received in the request <code>request</code> are valid. * These values are valid if and only if the noneditable parameters haven't been modified.<br> * Validation process is as follows.<br> * 1. If the action to which the request is directed is an init page, then it is a valid request. * <br> * 2. if the cookies received in the request are not found in the user session, the validation is * incorrect.<br> * 3. if the state recover process has produced an error, incorrect validation.<br> * 4. If the action received in the request is different to the action of the recovered state, * incorrect validation.<br> * 5. If not, all the parameter values are checked and if all the received values are valid then * the request is valid. <br> * 5.1. If it is an init parameter or a HDIV parameter then it is a valid parameter.<br> * 5.2. If the received parameter is not in the state:<br> * 5.2.1. If it has been defined by the user as a no validation required parameter, then it is a * valid parameter.<br> * 5.2.2. otherwise, it is a no valid request.<br> * 5.3. If the parameter is editable, if validations have been defined values are checked.<br> * 5.4. If it is a noneditable parameter, all the received values are checked. * * @param request HttpServletRequest to validate * @return valid result If all the parameter values of the request <code>request</code> pass the * the HDIV validation. False, otherwise. * @throws HDIVException If the request doesn't pass the HDIV validation an exception is thrown * explaining the cause of the error. */ public ValidatorHelperResult validate(HttpServletRequest request) { String target = this.getTarget(request); String targetWithoutContextPath = this.getTargetWithoutContextPath(request, target); // Hook before the validation Boolean pre = this.preValidate(request, target); if (pre != null) { return new ValidatorHelperResult(pre.booleanValue()); } if (this.hdivConfig.hasExtensionToExclude(target)) { log.debug("The target " + target + " has an extension to exclude from validation"); return ValidatorHelperResult.VALID; } if (!this.hdivConfig.isValidationInUrlsWithoutParamsActivated()) { boolean requestHasParameters = (request.getParameterNames() != null) && (request.getParameterNames().hasMoreElements()); if (!requestHasParameters) { log.debug( "The url " + request.getRequestURI() + " is not be validated because it has not got parameters"); return ValidatorHelperResult.VALID; } } if (this.hdivConfig.isStartPage(targetWithoutContextPath, request.getMethod())) { return (this.validateStartPageParameters(request, target)); } if (this.hdivConfig.isCookiesIntegrityActivated()) { ValidatorHelperResult result = this.validateRequestCookies(request, target); if (!result.isValid()) { return result; } } // Restore state from request or from memory ValidatorHelperResult result = this.restoreState(request, target); if (!result.isValid()) { return result; } // Get resultant object, the stored state IState state = (IState) result.getValue(); result = this.isTheSameAction(request, target, state); if (!result.isValid()) { return result; } result = this.allRequiredParametersReceived(request, state, target); if (!result.isValid()) { return result; } // Hdiv parameter name String hdivParameter = getHdivParameter(request); Hashtable unauthorizedEditableParameters = new Hashtable(); Enumeration parameters = request.getParameterNames(); while (parameters.hasMoreElements()) { String parameter = (String) parameters.nextElement(); // Check if the HDIV validation must be applied to the parameter if (!this.hdivConfig.needValidation(parameter, hdivParameter)) { if (log.isDebugEnabled() && !parameter.equals(hdivParameter)) { log.debug("parameter " + parameter + " doesn't need validation"); } continue; } // If the parameter requires no validation it is considered a valid parameter if (this.isUserDefinedNonValidationParameter(targetWithoutContextPath, parameter)) { continue; } IParameter stateParameter = state.getParameter(parameter); if (stateParameter == null) { // If the parameter is not defined in the state, it is an error. // With this verification we guarantee that no extra parameters are added. this.logger.log(HDIVErrorCodes.PARAMETER_NOT_EXISTS, target, parameter, null); if (log.isDebugEnabled()) { log.debug( "Validation Error Detected: Parameter [" + parameter + "] does not exist in the state for action [" + target + "]"); } return new ValidatorHelperResult(HDIVErrorCodes.PARAMETER_NOT_EXISTS); } // At this point we are processing a noneditable parameter String[] values = request.getParameterValues(parameter); // Check if the parameter is editable if (stateParameter.isEditable()) { if (hdivConfig.existValidations() && (stateParameter.getEditableDataType() != null)) { this.validateEditableParameter( request, target, parameter, values, stateParameter.getEditableDataType(), unauthorizedEditableParameters); } continue; } try { result = this.validateParameterValues(request, target, state, stateParameter, parameter, values); if (!result.isValid()) { return result; } } catch (Exception e) { String errorMessage = HDIVUtil.getMessage("validation.error", e.getMessage()); throw new HDIVException(errorMessage, e); } } if (unauthorizedEditableParameters.size() > 0) { return this.processValidateParameterErrors(request, unauthorizedEditableParameters); } return ValidatorHelperResult.VALID; }