@Override public void validate(final FacesContext context) { context .getApplication() .publishEvent(context, PreValidateEvent.class, UIValidateForm.class, this); BeanManager manager = BeanManagerAccessor.getBeanManager(); manager.fireEvent(this, BEFORE); Validator validator = context.getApplication().createValidator(validatorId); if (validator == null) { throw new IllegalArgumentException( "Could not create Validator with id: [" + validatorId + "]"); } try { UIComponent parent = this.getParent(); validator.validate(context, parent, components); } catch (ValidatorException e) { setValid(false); for (UIInput comp : components.values()) { comp.setValid(false); // TODO Put this back when attributes can control it // context.addMessage(comp.getClientId(), e.getFacesMessage()); } context.addMessage(null, e.getFacesMessage()); } manager.fireEvent(this, AFTER); context .getApplication() .publishEvent(context, PostValidateEvent.class, UIValidateForm.class, this); }
/** * Collect all messages associated with components identified by <code>for</code> attribute and * return it. An empty list will be returned when there are no messages. * * @param context The involved faces context. * @param component The messages component. * @return All messages associated with components identified by <code>for</code> attribute. */ protected List<FacesMessage> getMessages(FacesContext context, OmniMessages component) { String forClientIds = component.getFor(); if (forClientIds == null) { return component.isGlobalOnly() ? context.getMessageList(null) : context.getMessageList(); } List<FacesMessage> messages = new ArrayList<>(); for (String forClientId : forClientIds.split("\\s+")) { UIComponent forComponent = component.findComponent(forClientId); if (forComponent == null) { continue; } messages.addAll(context.getMessageList(forComponent.getClientId(context))); if (!(forComponent instanceof UIInput)) { for (UIInput child : findComponentsInChildren(forComponent, UIInput.class)) { messages.addAll(context.getMessageList(child.getClientId(context))); } } } return messages; }
private UIComponent getNameField(FacesContext context, EventEditorDialog dialog) { UIInput nameField = Components.getOrCreateFacet( context, dialog, HtmlInputText.COMPONENT_TYPE, "nameField", UIInput.class); nameField.getAttributes().put("styleClass", "o_fullWidth"); return nameField; }
public void validateEndDate(FacesContext context, UIComponent component, Object value) throws ValidatorException { Date endDate = (Date) value; if (endDate == null) { ZVotesUtils.throwValidatorException("EndDateNotSet"); } UIInput startDateComponent = (UIInput) (context.getViewRoot().findComponent("pollEditForm:startDate")); Date startDate = (Date) startDateComponent.getValue(); if (startDate.after(endDate)) { ZVotesUtils.throwValidatorException("EndDateBeforeStartDate"); } if (endDate.before(new Date())) { ZVotesUtils.throwValidatorException("EndDateBeforeNow"); } if (current.getId() != null) { Date previousEndDate = getFacade().find(current.getId()).getEndDate(); if ((current.getPollState().equals(PollState.PUBLISHED) || current.getPollState().equals(PollState.STARTED) || current.getPollState().equals(PollState.VOTING)) && endDate.before(previousEndDate)) { ZVotesUtils.throwValidatorException("EndDateCantBeMovedToEarlierTime"); } } }
private UIComponent createDateTimeFields( FacesContext context, final EventEditorDialog dialog, final String idPrefix) { DateChooser dateField = Components.getOrCreateFacet( context, dialog, DateChooser.COMPONENT_TYPE, idPrefix + "DateField", DateChooser.class); HtmlOutputText nbsp = Components.createOutputText(context, HTML.NBSP_ENTITY, false); UIInput timeField = Components.getOrCreateFacet( context, dialog, HtmlInputText.COMPONENT_TYPE, idPrefix + "TimeField", UIInput.class); String timeCls = Styles.mergeClassNames( (String) timeField.getAttributes().get("styleClass"), "o_eventEditor_timeField"); timeField.getAttributes().put("styleClass", timeCls); final UIComponent[][] components = new UIComponent[][] {{dateField, nbsp, timeField}}; return new UIComponentBase() { @Override public String getFamily() { return null; } @Override public void encodeBegin(FacesContext context) throws IOException { new TableRenderer(idPrefix + "Fields", 0, 0, 0, null).render(dialog, components); } }; }
@Override protected void writeFormRow( FacesContext context, ResponseWriter w, FormLayout c, ComputedFormData formData, UIFormLayoutRow row) throws IOException { ComputedRowData rowData = createRowData(context, c, formData, row); UIInput edit = row.getForComponent(); if (edit != null) { // Write the error messages, if any if (!formData.isDisableRowError()) { Iterator<FacesMessage> msg = ((DominoFacesContext) context).getMessages(edit.getClientId(context)); if (msg.hasNext()) { while (msg.hasNext()) { FacesMessage m = msg.next(); writeFormRowError(context, w, c, row, edit, m, rowData); } } } } // The write the children writeFormRowData(context, w, c, formData, row, edit, rowData); }
/** Validate if password and confirm password field is equals */ @Override public void validate(FacesContext context, UIComponent component, Object value) { String password = value.toString(); UIInput uiInputConfirmPassword = (UIInput) component.getAttributes().get("confirmPassword"); String confirmPassword = uiInputConfirmPassword.getSubmittedValue().toString(); // Password and confirmPassword are required if (password == null || password.isEmpty() || confirmPassword == null || confirmPassword.isEmpty()) { return; } // If password and confirmPassword aren´t equal if (!password.equals(confirmPassword)) { uiInputConfirmPassword.setValid(false); FacesMessage msg = guiUtils.getFacesMessage( context, FacesMessage.SEVERITY_ERROR, "edit.user.passwordNotEqual"); throw new ValidatorException(msg); } }
private UIComponent getDescriptionField(FacesContext context, EventEditorDialog dialog) { UIInput descriptionField = Components.getOrCreateFacet( context, dialog, HtmlInputTextarea.COMPONENT_TYPE, "descriptionArea", UIInput.class); descriptionField.getAttributes().put("styleClass", "o_fullWidthAndHeight"); descriptionField.getAttributes().put("style", "resize: none"); return descriptionField; }
/** * Implements {@link ClientSideConverter#generateClientSideConverter(FacesContext, UIComponent)} */ public String generateClientSideConverter(FacesContext context, UIComponent component) { UIInput input = (UIInput) component; DateTimeConverter converter = (DateTimeConverter) input.getConverter(); String dateType = converter.getType(); int valueType = TYPE_TIMESTAMP; if (StringUtil.isNotEmpty(dateType)) { if (dateType.equals(DateTimeConverter.TYPE_DATE)) { valueType = TYPE_DATE; } else if (dateType.equals(DateTimeConverter.TYPE_TIME)) { valueType = TYPE_TIME; } } // TODO in 9.0.2, should update this to handle message changes for SPR#MKEE7TXMLG String message; if (TYPE_DATE == valueType) { message = getMessageDate(); } else if (TYPE_TIME == valueType) { message = getMessageTime(); } else { message = getMessageBoth(); } DojoModuleResource module; StringBuilder builder = new StringBuilder(); switch (valueType) { case TYPE_DATE: { module = ISO_DATE_CONVERTER_MODULE; builder.append("new extlib.date.IsoDateConverter({message:"); // $NON-NLS-1$ JavaScriptUtil.addMessage(builder, message); builder.append("})"); // $NON-NLS-1$ break; } case TYPE_TIME: { module = ISO_TIME_CONVERTER_MODULE; builder.append("new extlib.date.IsoTimeConverter({message:"); // $NON-NLS-1$ JavaScriptUtil.addMessage(builder, message); builder.append("})"); // $NON-NLS-1$ break; } default: { // TYPE_TIMESTAMP module = ISO_DATE_TIME_CONVERTER_MODULE; builder.append("new extlib.date.IsoDateTimeConverter({message:"); // $NON-NLS-1$ JavaScriptUtil.addMessage(builder, message); builder.append("})"); // $NON-NLS-1$ break; } } if (null != module) { UIViewRootEx rootEx = (UIViewRootEx) context.getViewRoot(); rootEx.addEncodeResource(context, module); } return builder.toString(); }
private void encode(UIInput year, UIInput month, UIInput day, LocalDate localDate) { if (localDate == null) { return; } year.setValue(normalize(localDate.getYear())); month.setValue(normalize(localDate.getMonthOfYear())); day.setValue(normalize(localDate.getDayOfMonth())); }
private void addParameter(FaceletContext context, MessageParameterTagHandler paramHandler) throws IOException { if (paramHandler == null) return; UIInput tempValueHolder = new HtmlInputText(); paramHandler.apply(context, tempValueHolder); if (params == null) params = new ArrayList<String>(); params.add(tempValueHolder.getValue().toString()); }
/** * Test to verify that a class that registers itself is properly found using the search mechanism. * The J2SE classes are used for their inheritance hierarchy to test that converters registered to * interfaces and superclasses are properly found. * * <p>This test is meant for inheritance lookup only. */ public void testConverterInheritance(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Testing ConverterInheritance"); Converter converter; UIInput text = new UIInput(); text.setId("my_date_converter"); root.getChildren().add(text); // java.lang.Integer extends java.lang.Number. // Test to show that the standard converter registered to // java.lang.Integer should chosen over the inherited // java.lang.Number converter application.addConverter(java.lang.Number.class, "javax.faces.convert.NumberConverter"); converter = application.createConverter(java.lang.Integer.class); assertTrue(converter != null); assertTrue(converter instanceof javax.faces.convert.IntegerConverter); // java.sql.Date extends java.util.Date // Test to find converter registered to java.util.Date application.addConverter(java.util.Date.class, "javax.faces.convert.DateTimeConverter"); converter = null; converter = application.createConverter(java.sql.Date.class); assertTrue(converter != null); // java.util.HashSet is a subclass of java.util.AbstractSet which is // a subclass of java.util.AbstractCollection // Test to find the converter registered to java.util.AbstractCollection application.addConverter( java.util.AbstractCollection.class, "javax.faces.convert.DateTimeConverter"); converter = null; try { converter = application.createConverter(java.util.HashSet.class); } catch (javax.faces.FacesException fe) { } assertTrue(converter != null); // java.lang.String implements java.lang.CharSequence // Test to find the converter registered to java.lang.CharSequence application.addConverter( java.text.CharacterIterator.class, "javax.faces.convert.CharacterConverter"); converter = null; converter = application.createConverter(java.text.StringCharacterIterator.class); assertTrue(converter != null); // java.text.StringCharacterIterator implements // java.text.CharacterIterator which has a super-interface // java.lang.Cloneable // Test to find the converter registered to java.lang.Cloneable application.addConverter(java.lang.Cloneable.class, "javax.faces.convert.CharacterConverter"); converter = null; converter = application.createConverter(java.text.StringCharacterIterator.class); assertTrue(converter != null); }
public void validate_Date(FacesContext context, UIComponent component, Object value) throws ValidatorException { UIInput datainizio = (UIInput) component.getAttributes().get("dates"); Date dataInizio = (Date) datainizio.getValue(); Date dataFine = (Date) value; if (dataFine.before(dataInizio)) { throw new ValidatorException( new FacesMessage("La data di fine validita' deve essere successiva a quella di inizio")); } }
public static void switchAddImageIntoForm(String formName, String fileName) { FacesContext context = FacesContext.getCurrentInstance(); UIInput txtImageName = (UIInput) context.getViewRoot().findComponent(formName + ":txtImageName"); txtImageName.setValue(fileName); txtImageName.setSubmittedValue(fileName); context.renderResponse(); }
@Override public Object getConvertedValue( FacesContext context, UIComponent component, Object submittedValue) throws ConverterException { UIInput uiInput = (UIInput) component; DateTimeConverter converter = (DateTimeConverter) uiInput.getConverter(); String value = (String) submittedValue; return getAsObject(context, uiInput, converter, value); }
@Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { UIInput passwordComponent = (UIInput) component.getAttributes().get("passwordComponent"); String password = (String) passwordComponent.getValue(); String confirmPassword = (String) value; if (confirmPassword != null && !confirmPassword.equals(password)) { throw new ValidatorException(new FacesMessage("Wprowadzone hasła nie są identyczne!")); } }
/* (non-Javadoc) * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp() */ public void setUp() throws Exception { super.setUp(); form = new HtmlForm(); form.setId("form"); form2 = new HtmlForm(); form2.setId("form2"); facesContext.getViewRoot().getChildren().add(form); facesContext.getViewRoot().getChildren().add(form2); stp1 = (UISimpleTogglePanel) application.createComponent("org.richfaces.SimpleTogglePanel"); stp1.setId("simpleTogglePanel1"); stp1.setOpened(true); stp1.setSwitchType(UISimpleTogglePanel.SERVER_SWITCH_TYPE); openMarker1 = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE); openMarker1.setId("openMarker"); openMarker1.setValue("open"); closeMarker1 = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE); closeMarker1.setId("closeMarker"); closeMarker1.setValue("close"); stp1.getFacets().put(openMarker1.getId(), openMarker1); stp1.getFacets().put(closeMarker1.getId(), closeMarker1); form.getChildren().add(stp1); stp2 = (UISimpleTogglePanel) application.createComponent("org.richfaces.SimpleTogglePanel"); stp2.setId("simpleTogglePanel2"); stp2.setOpened(false); stp2.setSwitchType(UISimpleTogglePanel.SERVER_SWITCH_TYPE); openMarker2 = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE); openMarker2.setId("openMarker"); openMarker2.setValue("open"); closeMarker2 = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE); closeMarker2.setId("closeMarker"); closeMarker2.setValue("close"); stp2.getFacets().put(openMarker2.getId(), openMarker2); stp2.getFacets().put(closeMarker2.getId(), closeMarker2); form2.getChildren().add(stp2); input = (UIInput) application.createComponent(UIInput.COMPONENT_TYPE); input.setValue(""); input.setId("opened"); input.getAttributes().put("onchange", "return true;"); stp1.getChildren().add(input); command = new HtmlCommandLink(); command.setId("command"); stp1.getChildren().add(command); }
/** * decode method * * @param context * @param component */ public void decode(FacesContext context, UIComponent component) { // we haven't added these attributes--yet--defensive programming... if (RendererUtil.isDisabledOrReadonly(component)) { return; } String clientId = component.getClientId(context); Map requestParameterMap = context.getExternalContext().getRequestParameterMap(); String newValue = (String) requestParameterMap.get(clientId); UIInput comp = (UIInput) component; comp.setSubmittedValue(newValue); }
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { UIInput passwordComponent = (UIInput) component.getAttributes().get("passwordComponent"); String password = (String) passwordComponent.getValue(); String confirm = (String) value; if (!password.equals(confirm)) { throw new ValidatorException(new FacesMessage("Senhas não são iguais.")); } }
public void validateGroupMessage(FacesContext context, UIComponent component, Object value) { String strValue = (String) value; if (StringUtils.isEmpty(strValue)) { UIComponent ui = component.findComponent("groupEmailRegexp"); UIInput input = (UIInput) ui; if (!StringUtils.isEmpty((String) input.getValue())) { FacesMessage error = new FacesMessage(); error.setSeverity(FacesMessage.SEVERITY_ERROR); error.setSummary("Поле обязательно для заполнения"); throw new ValidatorException(error); } } }
/** * Converts the value into an entity. The type of the entity depends on the type that the daoCrud * returns. * * @param facesContext current faces context * @param component current component * @param value current value submitted from user. * @return An Entity */ public Object getAsObject( final FacesContext facesContext, final UIComponent component, final String value) { logger.debug( String.format( "getAsObject() called value=%s, component=%s, value class=%s", value, component.getClientId(facesContext), value.getClass().getName())); UIInput input = (UIInput) component; if (value.equals("-1") && (input.isRequired() || component.getAttributes().get("required_bean") != null)) { logger.debug("Required field and the value was -1"); throw new ConverterException(new FacesMessage("Required", "Required")); } try { Serializable entityId = CrudUtils.getIdObject(value, this.idType); logger.debug(String.format("entityId %s", entityId)); if (dao == null) { ObjectRegistry objectRegistry = CrankContext.getObjectRegistry(); Map<String, GenericDao> repos = (Map<String, GenericDao>) objectRegistry.getObject("repos"); if (managedObject != null) { logger.debug("Looking up DAO by managedObject"); dao = repos.get(managedObject.getName()); } else { Object key = component.getAttributes().get("beanType"); logger.debug("Looking up DAO by beanType"); dao = repos.get((String) key); } } Object object = dao.read(entityId); logger.debug(String.format("Read object %s", object)); if (object == null) { if ("-1".equals(value)) { logger.debug("No object found and the value was -1"); throw new ConverterException(new FacesMessage("Required", "Required")); } else { throw new ConverterException( new FacesMessage( "Can't find object with id " + value, "Can't find object with id " + value)); } } LogUtils.debug(logger, "Returning converted object %s", object); return object; } catch (ConverterException ex) { throw ex; } catch (Exception ex) { logger.error("Unable to convert object", ex); String message = String.format("Unable to convert, fatal issue, %s ", ex.getMessage()); throw new ConverterException(new FacesMessage(message, message)); } }
private void encode( UIInput year, UIInput month, UIInput day, UIInput hour, UIInput min, Date date) { if (date == null) { return; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); year.setValue(normalize(calendar.get(Calendar.YEAR))); month.setValue(normalize(calendar.get(Calendar.MONTH) + 1)); day.setValue(normalize(calendar.get(Calendar.DAY_OF_MONTH))); hour.setValue(normalize(calendar.get(Calendar.HOUR_OF_DAY))); min.setValue(normalize(calendar.get(Calendar.MINUTE))); }
@Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { UIInput price = (UIInput) component.getAttributes().get("price"); Integer minPrice = Integer.parseInt(price.getValue().toString()); Integer maxPrice = Integer.parseInt(value.toString()); if (maxPrice < minPrice) { FacesMessage message = new FacesMessage("Product Price Till should be equal or larger then Product Price From."); message.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(message); } }
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { // Obtain the client ID of the first password field from f:attribute. String passwordId = (String) component.getAttributes().get("passwordID"); // Find the actual JSF component for the client ID. UIInput passwordInput = (UIInput) context.getViewRoot().findComponent(passwordId); // Get its value, the entered password of the first field. String password = (String) passwordInput.getValue(); // Cast the value of the entered password of the second field back to String. String confirm = (String) value; // Compare the first password with the second password. if (!password.equals(confirm)) { throw new ValidatorException(new FacesMessage("Passwords are not equal.")); } }
private String computeValueAsISOString(FacesContext context, UIInput input) { DateTimeConverter converter = (DateTimeConverter) input.getConverter(); // the submitted value takes precedence // As it is a string, no conversion should happen Object submittedValue = input.getSubmittedValue(); if (submittedValue != null) { return (String) submittedValue; } Object value = input.getValue(); if (null == value) { return ""; } return getAsString(context, input, converter, value); }
public void validatePartialCredit(FacesContext context, UIComponent toValidate, Object value) { Integer pCredit = null; boolean isValid = true; if ("0.0".equals(value.toString())) { pCredit = 0; } else { try { pCredit = Integer.parseInt(value.toString()); } catch (NumberFormatException e) { isValid = false; } } if (isValid && (pCredit == null || pCredit < 0 || pCredit > 99)) { isValid = false; } if (!isValid) { ((UIInput) toValidate).setValid(false); FacesMessage message = new FacesMessage(); message.setSeverity(FacesMessage.SEVERITY_ERROR); String summary = ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.AuthorMessages", "partial_credit_limit_summary"); String detail = ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.AuthorMessages", "partial_credit_limit_detail"); message.setSummary(summary); message.setDetail(detail); context.addMessage(toValidate.getClientId(context), message); } }
public void testNumberConverter(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Tesing NumberConverter"); UIInput text = new UIInput(); text.setId("my_input_number"); root.getChildren().add(text); Converter converter = application.createConverter("javax.faces.Number"); String stringToConvert = "99.9"; Object obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.lang.Number); String str = converter.getAsString(getFacesContext(), text, obj); assertTrue(str.equals(stringToConvert)); }
public void validateCaptcha(FacesContext context, UIComponent toValidate, Object value) { if (c != null) { Map map = context.getExternalContext().getRequestParameterMap(); String challenge = map.get("recaptcha_challenge_field").toString(); String response = map.get("recaptcha_response_field").toString(); HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); ReCaptchaResponse resp = r.checkAnswer(req.getRemoteAddr(), challenge, response); if (!resp.isValid() || hasValidationErrors) { Logger.getLogger(ContactUsPage.class.getName()) .info("INVALID RESPONSE: " + resp.getErrorMessage()); ((UIInput) toValidate).setValid(false); if (hasValidationErrors) { context.addMessage( toValidate.getClientId(context), new FacesMessage( "Some required information was entered incorrectly. Please press refresh below to get a new challenge, then correct the issue.")); hasValidationErrors = false; } else { context.addMessage( toValidate.getClientId(context), new FacesMessage("Press refresh below to get a new challenge.")); hasValidationErrors = false; } } } }
/* * (non-Javadoc) * * @see javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent) */ public void broadcast(FacesEvent event) throws AbortProcessingException { if (event instanceof ActionEvent) { _commandBrige.broadcast(event); } else { super.broadcast(event); } }
/* * (non-Javadoc) * * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent) */ public void queueEvent(FacesEvent event) { if (event instanceof ActionEvent) { _commandBrige.queueEvent(event); } else { super.queueEvent(event); } }