Java Code Examples for javax.faces.component.UIInput

The following are top voted examples for showing how to use javax.faces.component.UIInput. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: atbash-octopus   File: FacesMessages.java   Source Code and License 9 votes vote down vote up
public void show() {
    FacesContext instance = FacesContext.getCurrentInstance();

    String msg;
    if (StringUtils.isEmpty(template)) {
        msg = text;
        if (severity == null) {  // If we are using text, and the developer didn't specify a severity => Assume ERROR.
            severity = FacesMessage.SEVERITY_ERROR;
        }
    } else {
        msg = messageContext.message().template(template).argument(arguments).toString();

        if (severity == null) {
            severity = determineSeverity(template);
        }
    }
    instance.addMessage(clientId, new FacesMessage(severity, msg, msg));
    if (clientId != null) {
        UIComponent component = instance.getViewRoot().findComponent(clientId);
        if (component instanceof UIInput && FacesMessage.SEVERITY_ERROR.equals(severity)) {
            ((UIInput) component).setValid(false);
        }
    }
    resetData();
}
 
Example 2
Project: oscm   File: JSFUtils.java   Source Code and License 7 votes vote down vote up
/**
 * Reset the values of all UIInput children. This might be necessary after a
 * validation error to successfully process an AJAX request. See [Bug 5449]
 * and http://wiki.apache.org/myfaces/ClearInputComponents
 * 
 * @param uiComponent
 *            the root component to be processed.
 */
public static void resetUIInputChildren(UIComponent uiComponent) {
    if (uiComponent != null) {
        List<UIComponent> children = uiComponent.getChildren();
        for (UIComponent child : children) {
            if (child instanceof UIInput) {
                UIInput uiInput = (UIInput) child;
                uiInput.setSubmittedValue(null);
                uiInput.setValue(null);
                uiInput.setLocalValueSet(false);
            } else {
                resetUIInputChildren(child);
            }
        }
    }
}
 
Example 3
Project: oscm   File: SubscriptionWizardConversationTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testValidateSubscriptionId() throws Exception {

    // given
    SubscriptionServiceInternal ssi = mock(SubscriptionServiceInternal.class);
    doReturn(true).when(ssi).validateSubscriptionIdForOrganization(
            anyString());
    doReturn(ssi).when(bean).getSubscriptionServiceInternal();

    UIComponent uiInputMock = mock(UIInput.class);
    FacesContext contextMock = mock(FacesContext.class);

    // when
    bean.validateSubscriptionId(contextMock, uiInputMock, "value");

    // then
    verify(ui, times(1)).handleError(anyString(),
            eq(SUBSCRIPTION_NAME_ALREADY_EXISTS), anyObject());
}
 
Example 4
Project: myfaces-trinidad   File: ComponentReferenceTest.java   Source Code and License 7 votes vote down vote up
public void testVerySimpleFinder()
{
  UIViewRoot root = facesContext.getViewRoot();
  root.setId("root");
  UIInput input1 = new UIInput(); input1.setId("input1");

  // build the Tree...
  root.getChildren().add(input1);

  // Get the ComponentReference util
  ComponentReference<UIInput> uiRef = ComponentReference.newUIComponentReference(input1);

  // find the component...
  UIInput referencedComp = uiRef.getComponent();

  assertEquals(input1, referencedComp);
}
 
Example 5
Project: myfaces-trinidad   File: ComponentReferenceTest.java   Source Code and License 7 votes vote down vote up
public void testNoComponentWithoutAnId()
{
  UIViewRoot root = facesContext.getViewRoot();
  root.setId("root");
  UIInput input1 = new UIInput();

  // build the Tree...
  root.getChildren().add(input1);

  ComponentReference ref = ComponentReference.newUIComponentReference(input1);

  // Get the ComponentReference util
  try
  {
    ref.getComponent();
    
    // find the component...
    fail("IllegalStateException expected");
  }
  catch (IllegalStateException e)
  {
    // suppress it - this is as expected
  }
}
 
Example 6
Project: Peking-University-Open-Research-Data-Platform   File: ManagePermissionsPage.java   Source Code and License 7 votes vote down vote up
public void validateGroupIdentifier(FacesContext context, UIComponent toValidate, Object rawValue) {
    String value = (String) rawValue;
    UIInput input = (UIInput) toValidate;
    input.setValid(true); // Optimistic approach
    
    if ( context.getExternalContext().getRequestParameterMap().get("DO_GROUP_VALIDATION") != null 
            && !StringUtils.isEmpty(value) ) {
        
        // cheap test - regex
        if (! Pattern.matches("^[a-zA-Z0-9\\_\\-]+$", value) ) {
            input.setValid(false);
            context.addMessage(toValidate.getClientId(),
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "", JH.localize("dataverse.permissions.explicitGroupEditDialog.groupIdentifier.invalid")));
        
        } else if ( explicitGroupSvc.findInOwner(getDvObject().getId(), value) != null ) {
            // Ok, see that the alias is not taken
            input.setValid(false);
            context.addMessage(toValidate.getClientId(),
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "", JH.localize("dataverse.permissions.explicitGroupEditDialog.groupIdentifier.taken")));
        }
    }
}
 
Example 7
Project: Peking-University-Open-Research-Data-Platform   File: BuiltinUserPage.java   Source Code and License 7 votes vote down vote up
public void validateUserName(FacesContext context, UIComponent toValidate, Object value) {
    String userName = (String) value;
    boolean userNameFound = false;
    BuiltinUser user = builtinUserService.findByUserName(userName);
    if (editMode == EditMode.CREATE) {
        if (user != null) {
            userNameFound = true;
        }
    } else {
        if (user != null && !user.getId().equals(builtinUser.getId())) {
            userNameFound = true;
        }
    }
    if (userNameFound) {
        ((UIInput) toValidate).setValid(false);
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, JH.localize("user.username.taken"), null);
        context.addMessage(toValidate.getClientId(context), message);
    }
}
 
Example 8
Project: Peking-University-Open-Research-Data-Platform   File: BuiltinUserPage.java   Source Code and License 7 votes vote down vote up
public void validateUserNameEmail(FacesContext context, UIComponent toValidate, Object value) {
    String userName = (String) value;
    boolean userNameFound = false;
    BuiltinUser user = builtinUserService.findByUserName(userName);
    if (user != null) {
        userNameFound = true;
    } else {
        BuiltinUser user2 = builtinUserService.findByEmail(userName);
        if (user2 != null) {
            userNameFound = true;
        }
    }
    if (!userNameFound) {
        ((UIInput) toValidate).setValid(false);
        FacesMessage message = new FacesMessage("Username or Email is incorrect.");
        context.addMessage(toValidate.getClientId(context), message);
    }
}
 
Example 9
Project: Peking-University-Open-Research-Data-Platform   File: DataversePage.java   Source Code and License 7 votes vote down vote up
public void validateAlias(FacesContext context, UIComponent toValidate, Object value) {
    if (!StringUtils.isEmpty((String) value)) {
        String alias = (String) value;

        boolean aliasFound = false;
        Dataverse dv = dataverseService.findByAlias(alias);
        if (editMode == DataversePage.EditMode.CREATE) {
            if (dv != null) {
                aliasFound = true;
            }
        } else {
            if (dv != null && !dv.getId().equals(dataverse.getId())) {
                aliasFound = true;
            }
        }
        if (aliasFound) {
            ((UIInput) toValidate).setValid(false);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "alias", "This Alias is already taken.");
            context.addMessage(toValidate.getClientId(context), message);
        }
    }
}
 
Example 10
Project: oscm   File: ExportBillingDataCtrlTest.java   Source Code and License 6 votes vote down vote up
@Test
public void billingTypeChanged() {
    // given
    UIInput input = mock(UIInput.class);
    ValueChangeEvent e = new ValueChangeEvent(input, null,
            BillingDataType.RevenueShare);

    // when
    ctrl.billingTypeChanged(e);

    // then
    assertEquals(BillingDataType.RevenueShare,
            model.getSelectedBillingDataType());
    assertNull(model.getFromDate());
    assertNull(model.getToDate());
    assertNull(model.getSelectedSharesResultType());
}
 
Example 11
Project: Peking-University-Open-Research-Data-Platform   File: LinkValidator.java   Source Code and License 6 votes vote down vote up
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    UIInput taglineInput = (UIInput) component.getAttributes().get("taglineInput");
    UIInput linkUrlInput = (UIInput) component.getAttributes().get("linkUrlInput");

    String taglineStr = (String) taglineInput.getSubmittedValue();
    String urlStr = (String) linkUrlInput.getSubmittedValue();

    FacesMessage msg = null;
    if (taglineStr.isEmpty() && !urlStr.isEmpty()) {
        msg = new FacesMessage("Please enter a tagline for the website to be hyperlinked with.");
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        FacesContext.getCurrentInstance().addMessage(taglineInput.getClientId(), msg);
    }

    if (msg != null) {
        throw new ValidatorException(msg);
    }

}
 
Example 12
Project: Peking-University-Open-Research-Data-Platform   File: RequiredCheckboxValidator.java   Source Code and License 6 votes vote down vote up
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    if (value.equals(Boolean.FALSE)) {
        String requiredMessage = ((UIInput) component).getRequiredMessage();
        if (requiredMessage == null) {
            Object label = component.getAttributes().get("label");
            if (label == null || (label instanceof String && ((String) label).length() == 0)) {
                label = component.getValueExpression("label");
            }
            if (label == null) {
                label = component.getClientId(context);
            }
            requiredMessage = MessageFormat.format(UIInput.REQUIRED_MESSAGE_ID, label);
        }
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, requiredMessage, requiredMessage));
    }
}
 
Example 13
Project: Peking-University-Open-Research-Data-Platform   File: AdvanceBuiltinUserSupervisorValidation.java   Source Code and License 6 votes vote down vote up
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    UIInput positionUI = (UIInput)component.findComponent("position");
    UIInput userTypeUI = (UIInput)component.findComponent("userType");
    String position = (String)positionUI.getLocalValue();
    UserType userType = (UserType)userTypeUI.getLocalValue();
    String inputValue = (String)value;
    if(position.equals("student") && userType == UserType.ADVANCE){
        if(inputValue == null || inputValue.trim().length()==0){
            FacesMessage message = new FacesMessage(
                    ResourceBundle.getBundle("ValidationMessages",context.getViewRoot().getLocale())
                            .getString("cn.edu.pku.lib.dataverse.validation.AdvanceBuiltinUserSupervisorValidation.message"));
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }
}
 
Example 14
Project: MapChat   File: AccountManager.java   Source Code and License 6 votes vote down vote up
/**
 * Make sure the correct password was entered
 * @param components the component to check
 * @return true is correct, false otherwise
 */
private boolean correctPasswordEntered(UIComponent components) {
    UIInput uiInputVerifyPassword = (UIInput) components.findComponent("verifyPassword");
    String verifyPassword = uiInputVerifyPassword.getLocalValue() == null ? ""
            : uiInputVerifyPassword.getLocalValue().toString();
    if (verifyPassword.isEmpty()) {
        statusMessage = "";
        return false;
    } else {
        if (verifyPassword.equals(password)) {
            return true;
        } else {
            statusMessage = "Invalid password entered!";
            return false;
        }
    }
}
 
Example 15
Project: photosOpen   File: PasswordValidator.java   Source Code and License 6 votes vote down vote up
/**
 * Make sure the passwords entered by the user match.
 *
 * @param o                 Object containing the password value.
 */
public void validateMatch(FacesContext facesContext, UIComponent uiComponent, Object o) throws ValidatorException {

    ResourceBundle resourceBundle = resourceBundleUtil.getResourceBundle(ResourceBundleUtil.USERS);

    String passwordConfirm = o.toString();
    String oriPassword;

    // Find the actual JSF component for the client ID.
    UIInput textInput = (UIInput) uiComponent.findComponent("passwordInputId");

    if (textInput == null || textInput.getSubmittedValue() == null) {
        oriPassword = this.password;
    }
    else {
        oriPassword = textInput.getSubmittedValue().toString();
    }

    if (!passwordConfirm.equals(oriPassword)) {
        createErrorMessage(resourceBundle.getString("errorPasswordValidationFailed"), resourceBundle.getString("errorPasswordsDontMatch"));
    }
}
 
Example 16
Project: jpasecurity   File: LoginActionListener.java   Source Code and License 6 votes vote down vote up
public void processAction(ActionEvent actionEvent) {
    FacesContext context = FacesContext.getCurrentInstance();
    UINamingContainer loginComponent
        = (UINamingContainer)context.getAttributes().get(UIComponent.CURRENT_COMPOSITE_COMPONENT);
    UIInput username = (UIInput)loginComponent.findComponent("loginDialog:loginForm:username");
    UIInput password = (UIInput)loginComponent.findComponent("loginDialog:loginForm:password");
    MethodExpression loginAction = (MethodExpression)loginComponent.getAttributes().get("loginAction");
    try {
        loginAction.invoke(context.getELContext(), new Object[] {username.getValue(), password.getValue()});
        NavigationHandler navigationHandler = context.getApplication().getNavigationHandler();
        String outcome = (String)context.getExternalContext().getRequestParameterMap().get("outcome");
        if (outcome != null) {
            navigationHandler.handleNavigation(context, null, outcome);
        }
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Login could not be established.", e);
        } else {
            LOG.info("Login could not be established: " + e.getMessage());
        }
    }
}
 
Example 17
Project: jk-faces   File: UIFacesVisitor.java   Source Code and License 6 votes vote down vote up
@Override
public VisitResult visit(final VisitContext context, final UIComponent target) {
	// if (!target.isRendered()) {
	// return VisitResult.REJECT;
	// }

	if (target instanceof UIInput) {
		this.inputs.add((UIInput) target);
	}
	if (target instanceof UIForm) {
		this.forms.add((UIForm) target);
	}

	if (target instanceof UICommand) {
		this.commands.add((UICommand) target);
	}
	if (target instanceof UIOutput) {
		this.outputs.add((UIOutput) target);
	}
	if (target instanceof UISubmenu) {
		this.subMenus.add((UISubmenu) target);
	}
	if (target instanceof Column) {
		this.columns.add((Column) target);
	}
	if (target instanceof DataTable) {
		this.tables.add((DataTable) target);
	}
	if (target instanceof UISelectItems) {
		this.selectItems.add((UISelectItems) target);
	}
	if (target instanceof PanelGrid) {
		this.panelGrids.add((PanelGrid) target);
	}
	return VisitResult.ACCEPT;
}
 
Example 18
Project: jk-faces   File: JKJsfUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Calculate checksum.
 *
 * @param component
 *            the component
 * @return the long
 */
public static long calculateChecksum(final UIComponent component) {
	try {
		final Checksum checksumHandler = new CRC32();
		final UIFacesVisitor visitors = JKJsfUtil.visitComponent(component);
		final List<UIInput> inputs = visitors.getInputs();
		for (final UIInput uiInput : inputs) {
			if (uiInput.getValue() == null) {
				checksumHandler.update("null".getBytes(), 0, 0);
			} else {
				final byte[] bytes = uiInput.getValue().toString().getBytes("UTF-8");
				checksumHandler.update(bytes, 0, bytes.length);
			}
		}
		return checksumHandler.getValue();
	} catch (final Exception e) {
		JKExceptionUtil.handle(e);
		// unreachable
		return -1;
	}
}
 
Example 19
Project: jk-faces   File: JSFComponentFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new JSFComponent object.
 *
 * @param label
 *            the label
 * @param type
 *            the type
 * @return the UI input
 */
public static UIInput createInput(final String label, final Class type) {
	UIInput input = null;
	if (JKObjectUtil.isTime(type)) {
		input = (javax.faces.component.UIInput) JSFComponentFactory.createComponent(TimePicker.COMPONENT_TYPE);
	} else if (JKObjectUtil.isTimeStamp(type)) {
		input = (javax.faces.component.UIInput) JSFComponentFactory.createComponent(Calendar.COMPONENT_TYPE);
	} else if (JKObjectUtil.isDate(type)) {
		input = (javax.faces.component.UIInput) JSFComponentFactory.createComponent(Calendar.COMPONENT_TYPE);
	} else if (JKObjectUtil.isBoolean(type)) {
		input = (javax.faces.component.UIInput) JSFComponentFactory.createComponent(SelectBooleanCheckbox.COMPONENT_TYPE);
	} else {
		input = JSFComponentFactory.createInputText(null);
	}
	input.getAttributes().put("label", label);
	return input;
}
 
Example 20
Project: gluu   File: FacesComponentUtility.java   Source Code and License 6 votes vote down vote up
private static void resetInputComponents(UIComponent rootUIComponent) {
	if ((rootUIComponent == null) || (rootUIComponent.getChildCount() == 0)) {
		return;
	}

	for (UIComponent comp : rootUIComponent.getChildren()) {
		if (comp instanceof UIInput) {
			UIInput uiInput = (UIInput) comp;
			uiInput.setSubmittedValue(null);
			uiInput.setValid(true);
			uiInput.setLocalValueSet(false);
			uiInput.resetValue();
		}
		resetInputComponents(comp);
	}
}
 
Example 21
Project: parco   File: NumeroScontrinoValidator.java   Source Code and License 6 votes vote down vote up
public void validate(FacesContext context, UIComponent component, Object value)
    throws ValidatorException
{
    String ns = (String) value;

    String nsr = (String) component.getAttributes().get("numeroScontrinoRichiesta");

    if ( StringUtils.isEmpty( ns ) || StringUtils.isEmpty( nsr ) )
    {
        return; 
    }

    if ( !StringUtils.equalsIgnoreZeros( ns, nsr ) )
    {
    	((UIInput) component).setValid( false );
    	log.debugv( "Scontrino {0} diverso dal numero scontrino {1} sul rifornimento", ns, nsr );
    	
        String text = bundleManager.getMessage( "valodator.scon.wrong" );
        
        throw new ValidatorException( new FacesMessage( text ) );
    }
}
 
Example 22
Project: development   File: JSFUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Reset the values of all UIInput children. This might be necessary after a
 * validation error to successfully process an AJAX request. See [Bug 5449]
 * and http://wiki.apache.org/myfaces/ClearInputComponents
 * 
 * @param uiComponent
 *            the root component to be processed.
 */
public static void resetUIInputChildren(UIComponent uiComponent) {
    if (uiComponent != null) {
        List<UIComponent> children = uiComponent.getChildren();
        for (UIComponent child : children) {
            if (child instanceof UIInput) {
                UIInput uiInput = (UIInput) child;
                uiInput.setSubmittedValue(null);
                uiInput.setValue(null);
                uiInput.setLocalValueSet(false);
            } else {
                resetUIInputChildren(child);
            }
        }
    }
}
 
Example 23
Project: development   File: SubscriptionWizardConversationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testValidateSubscriptionId() throws Exception {

    // given
    SubscriptionServiceInternal ssi = mock(SubscriptionServiceInternal.class);
    doReturn(true).when(ssi).validateSubscriptionIdForOrganization(
            anyString());
    doReturn(ssi).when(bean).getSubscriptionServiceInternal();

    UIComponent uiInputMock = mock(UIInput.class);
    FacesContext contextMock = mock(FacesContext.class);

    // when
    bean.validateSubscriptionId(contextMock, uiInputMock, "value");

    // then
    verify(ui, times(1)).handleError(anyString(),
            eq(SUBSCRIPTION_NAME_ALREADY_EXISTS), anyObject());
}
 
Example 24
Project: development   File: ExportBillingDataCtrlTest.java   Source Code and License 6 votes vote down vote up
@Test
public void billingTypeChanged() {
    // given
    UIInput input = mock(UIInput.class);
    ValueChangeEvent e = new ValueChangeEvent(input, null,
            BillingDataType.RevenueShare);

    // when
    ctrl.billingTypeChanged(e);

    // then
    assertEquals(BillingDataType.RevenueShare,
            model.getSelectedBillingDataType());
    assertNull(model.getFromDate());
    assertNull(model.getToDate());
    assertNull(model.getSelectedSharesResultType());
}
 
Example 25
Project: submerge   File: UserLoginValidator.java   Source Code and License 6 votes vote down vote up
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
	UIInput cpntPasswordLogin = (UIInput) component.getAttributes().get(PWD_FIELD);
	String userName = (String) cpntPasswordLogin.getValue();
	String password = (String) value;

	if (password == null || StringUtils.isEmpty(userName)) {
		throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, MISSING_INFORMATION, null));
	}

	String hash = this.userService.hashPassword(password);
	UserBO result = this.userService.findByName(userName);
	if (result == null || !result.getPassword().equals(hash)) {
		throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, INCORRECT_USER_LOGIN, null));
	}
}
 
Example 26
Project: ButterFaces   File: ReadonlyPartRenderer.java   Source Code and License 6 votes vote down vote up
public void renderReadonly(final HtmlInputComponent component, final ResponseWriter writer) throws IOException {
    final UIInput uiComponent = (UIInput) component;

    final boolean readonly = component.isReadonly();
    final Object value = component.getValue();

    if (readonly) {
        writer.startElement(HtmlBasicRenderer.ELEMENT_DIV, uiComponent);
        final StringBuilder sb = new StringBuilder("butter-component-value butter-component-value-readonly");
        if (component.isHideLabel()) {
            sb.append(" butter-component-value-hiddenLabel");
        }
        writer.writeAttribute("class", sb.toString(), null);
        writer.startElement("span", uiComponent);
        writer.writeAttribute("class", "butter-component-value-readonly-wrapper", "styleClass");
        writer.writeText(this.getReadonlyDisplayValue(value, uiComponent, uiComponent.getConverter()), null);
        writer.endElement("span");
        writer.endElement(HtmlBasicRenderer.ELEMENT_DIV);
    }
}
 
Example 27
Project: ButterFaces   File: ReadonlyPartRenderer.java   Source Code and License 6 votes vote down vote up
/**
 * Should return value string for the readonly view mode. Can be overridden
 * for custom components.
 */
private String getReadonlyDisplayValue(final Object value, final UIInput component, final Converter converter) {
    if (value == null || "".equals(value)) {
        return "-";
    } else if (converter != null) {
        final String asString = converter.getAsString(FacesContext.getCurrentInstance(), component, value);
        return asString == null ? "-" : asString;
    }

    if (component instanceof HtmlCheckBox) {
        HtmlCheckBox checkBoxComponent = (HtmlCheckBox) component;
        final StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotEmpty(checkBoxComponent.getDescription())) {
            sb.append(checkBoxComponent.getDescription()).append(": ");
        }
        sb.append((Boolean) value ? "ja" : "nein");
        return sb.toString();
    }

    return String.valueOf(value);
}
 
Example 28
Project: sakai   File: InputColorRenderer.java   Source Code and License 6 votes vote down vote up
/**
 * 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(context, 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);
}
 
Example 29
Project: sakai   File: ColorPickerRenderer.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 30
Project: music-albums-obermueller   File: PasswordValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void thatEqualPasswordInputsAreCorrect(){
    when(mockedValue.toString()).thenReturn("password");
    UIInput uiInput= new UIInput();
    uiInput.setSubmittedValue("password");
    Map<String, Object> mapAttributes = new HashMap<>();
    mapAttributes.put("confirmPassword", uiInput);
    when(mockedUIComponent.getAttributes()).thenReturn(mapAttributes);
    when(mockedGuiUtils.getFacesMessage(mockedFacesContext, FacesMessage.SEVERITY_ERROR,
            "edit.user.passwordNotEqual")).thenReturn(new FacesMessage("edit.user.passwordNotEqual"));

    try {
        passwordValidator.validate(mockedFacesContext, mockedUIComponent, mockedValue);

    } catch(ValidatorException ex) {
        fail("Should not throw a ValidationException");
    }
}
 
Example 31
Project: music-albums-obermueller   File: PasswordValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test (expected = ValidatorException.class)
public void thatNotEqualPasswordInputsThrowsValidationExceptionAndSetInputFieldFalse() {
    when(mockedValue.toString()).thenReturn("password");
    UIInput uiInput= new UIInput();
    uiInput.setSubmittedValue("password2");
    Map<String, Object> mapAttributes = new HashMap<>();
    mapAttributes.put("confirmPassword", uiInput);
    when(mockedUIComponent.getAttributes()).thenReturn(mapAttributes);

    when(mockedGuiUtils.getFacesMessage(mockedFacesContext, FacesMessage.SEVERITY_ERROR,
            "edit.user.passwordNotEqual")).thenReturn(new FacesMessage("edit.user.passwordNotEqual"));

    passwordValidator.validate(mockedFacesContext, mockedUIComponent, mockedValue);

    assertThat("UIInput should be false", uiInput.isValid(), is(false));
}
 
Example 32
Project: Miscellany   File: AceFormTableRenderer.java   Source Code and License 6 votes vote down vote up
@Override
protected void writeFormRowError(final FacesContext facesContext, final ResponseWriter w, final FormLayout c, final UIFormLayoutRow row, final UIInput input, final FacesMessage msg, final ComputedRowData data) throws IOException {
	//		w.startElement("div", row);
	//		String className = "";
	//		if(msg.getSeverity().equals(FacesMessage.SEVERITY_ERROR)) {
	//			className = "alert-danger";
	//		} else if(msg.getSeverity().equals(FacesMessage.SEVERITY_FATAL)) {
	//			className = "alert-danger";
	//		} else if(msg.getSeverity().equals(FacesMessage.SEVERITY_INFO)) {
	//			className = "alert-info";
	//		} else if(msg.getSeverity().equals(FacesMessage.SEVERITY_WARN)) {
	//			className = "alert-warning";
	//		}
	//		w.writeAttribute("class", "alert " + className, null);
	//		w.writeText(msg.getSummary(), null);
	//
	//		w.endElement("div");
}
 
Example 33
Project: Miscellany   File: AceDateTimeHelperRenderer.java   Source Code and License 6 votes vote down vote up
@Override
protected void writeDateTimeAttributes(final FacesContext context, final UIComponent component, final ResponseWriter w, final String paramString) throws IOException {
	DateTimeConverter converter = (DateTimeConverter)((UIInput)component).getConverter();
	switch(PickerType.valueFor(context, component)) {
	case DATE:
		w.writeAttribute("data-date-format", convertDojoPatternForJQuery(converter.getDatePattern(context)), null);
		break;
	case TIME:
		w.writeAttribute("data-time-format", convertDojoPatternForJQuery(converter.getTimePattern(context)), null);
		break;
	case DATETIME:
		w.writeAttribute("data-date-format", convertDojoPatternForJQuery(converter.getBothDatePattern(context)), null);
		w.writeAttribute("data-time-format", convertDojoPatternForJQuery(converter.getBothTimePattern(context)), null);
		break;
	}


	super.writeDateTimeAttributes(context, component, w, paramString);
}
 
Example 34
Project: sakai   File: ColorPickerRenderer.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 35
Project: jsf-renderer-extensions   File: RequiredMarkerInitializer.java   Source Code and License 6 votes vote down vote up
@Override
public void configureComponent(FacesContext facesContext, UIComponent uiComponent, Map<String, Object> metaData) {
    if (uiComponent instanceof OutputLabel) {
        OutputLabel label = (OutputLabel) uiComponent;
        if (label.getFor() != null && !label.getFor().trim().isEmpty()) {
            UIComponent targetComponent = label.findComponent(label.getFor());

            if (targetComponent != null) {
                informationManager.determineInformation(facesContext, targetComponent);
                initializerManager.performInitialization(facesContext, targetComponent);
            } else {
                logger.warn("target component specified in for ('" + label.getFor() + "') not found from component " + label.getClientId(facesContext));
            }
        }
    }

    if (uiComponent instanceof UIInput) {
        UIInput input = (UIInput) uiComponent;

        if (metaData.containsKey(CommonMetaDataKeys.REQUIRED.getKey())) {
            input.setRequired(true);
        }
    }

}
 
Example 36
Project: community-edition-old   File: MultilingualTextAreaGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public UIComponent generateAndAdd(FacesContext context, UIPropertySheet propertySheet,
         PropertySheetItem item)
{
   UIComponent component = super.generateAndAdd(context, propertySheet, item);
   
   if ((component instanceof UIInput) && (component instanceof UISelectOne) == false)
   {
      component.setRendererType(RepoConstants.ALFRESCO_FACES_MLTEXTAREA_RENDERER);
   }
   else if ((component instanceof UIOutput))
   {
      component.setRendererType(RepoConstants.ALFRESCO_FACES_MLTEXT_RENDERER);
   }
   
   return component;
}
 
Example 37
Project: community-edition-old   File: LoginBean.java   Source Code and License 6 votes vote down vote up
/**
 *  Validate that field "confirm" matches to the field "password" 
 */
public void validateMatch(FacesContext context, UIComponent component, Object value)
      throws ValidatorException
{
    String confirm = (String)value;
    
    String field1Id = (String) component.getAttributes().get("passwd1Id");
    UIInput passComponent = (UIInput) context.getViewRoot().findComponent(field1Id);
    String pass = (String) passComponent.getSubmittedValue();
    if (pass == null)
    {
        pass = (String) passComponent.getValue();
    }
    
    if (!pass.equals(confirm))
    {
        String err = Application.getMessage(context, UsersDialog.ERROR_PASSWORD_MATCH);
        throw new ValidatorException(new FacesMessage(err));
    }
}
 
Example 38
Project: karaku   File: RequiredPhaseListener.java   Source Code and License 6 votes vote down vote up
private void processUIComponent(UIComponent uiComponent) {

		if (uiComponent instanceof PickerUpdater) {
			PickerUpdater pu = (PickerUpdater) uiComponent;
			if (pu.isRequired()) {
				markOutputRequired(lastOutput);
			}
			return;
		}
		if (uiComponent instanceof UIInput) {
			processInput((UIInput) uiComponent);
			return;
		}
		if (uiComponent instanceof UIOutput) {
			processUIOutput((UIOutput) uiComponent);
			return;
		}
	}
 
Example 39
Project: BootsFaces-OSP   File: CoreRenderer.java   Source Code and License 6 votes vote down vote up
/**
 * Renders the CSS pseudo classes for required fields and for the error levels.
 *
 * @param input
 * @param rw
 * @param clientId
 * @throws IOException
 */
protected void generateErrorAndRequiredClass(UIInput input, ResponseWriter rw, String clientId,
		String additionalClass1, String additionalClass2, String additionalClass3) throws IOException {
	String styleClass = getErrorAndRequiredClass(input, clientId);
	if (null != additionalClass1) {
		additionalClass1 = additionalClass1.trim();
		if (additionalClass1.trim().length() > 0) {
			styleClass += " " + additionalClass1;
		}
	}
	if (null != additionalClass2) {
		additionalClass2 = additionalClass2.trim();
		if (additionalClass2.trim().length() > 0) {
			styleClass += " " + additionalClass2;
		}
	}
	if (null != additionalClass3) {
		additionalClass3 = additionalClass3.trim();
		if (additionalClass3.trim().length() > 0) {
			styleClass += " " + additionalClass3;
		}
	}
	rw.writeAttribute("class", styleClass, "class");
}
 
Example 40
Project: oxTrust   File: FacesComponentUtility.java   Source Code and License 6 votes vote down vote up
private static void resetInputComponents(UIComponent rootUIComponent) {
	if ((rootUIComponent == null) || (rootUIComponent.getChildCount() == 0)) {
		return;
	}

	for (UIComponent comp : rootUIComponent.getChildren()) {
		if (comp instanceof UIInput) {
			UIInput uiInput = (UIInput) comp;
			uiInput.setSubmittedValue(null);
			uiInput.setValid(true);
			uiInput.setLocalValueSet(false);
			uiInput.resetValue();
		}
		resetInputComponents(comp);
	}
}
 
Example 41
Project: oxTrust   File: ConfigureCacheRefreshAction.java   Source Code and License 6 votes vote down vote up
public void validateProperty(FacesContext context, UIComponent comp,
		Object value) {

	System.out.println("inside validate method");
	String newkeyAttr = (String) value;
	int size= keyAttributes.size();
	
	for(SimpleProperty keyAttribute :  keyAttributes){
		int i = 0;
		if(newkeyAttr.equalsIgnoreCase(keyAttribute.getValue())){
			i=i+1;
			if(i==2){
			((UIInput) comp).setValid(false);
			FacesMessage message = new FacesMessage(
					"key attribute already Exist! ");
			//message.setSeverity(Severity.ERROR);
			context.addMessage(comp.getClientId(context), message);
			}
		}
		
	}		
}
 
Example 42
Project: XPagesExtensionLibrary   File: FormTableRenderer.java   Source Code and License 6 votes vote down vote up
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 = getMessages(context, 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);
}
 
Example 43
Project: XPagesExtensionLibrary   File: FormTableRenderer.java   Source Code and License 6 votes vote down vote up
protected void writeFormRowLabel(FacesContext context, ResponseWriter w, FormLayout c, ComputedFormData formData, UIFormLayoutRow row, UIInput edit, String label) throws IOException {
    if(StringUtil.isNotEmpty(label)) {
        w.startElement("label", c); // $NON-NLS-1$
        if(edit!=null &&
            !ReadOnlyAdapterRenderer.isReadOnly(context, edit)) {
            w.writeAttribute("for", edit.getClientId(context), null); // $NON-NLS-1$
        }
        // Required mark
        if(edit!=null && !formData.isDisableRequiredMarks() && edit.isRequired()) {
            writeFormRowRequiredContent(context, w, c, row, edit);
        }
        // Label text
        writeFormRowDataLabel(context, w, c, row, edit, label);
        w.endElement("label"); // $NON-NLS-1$
    } else {
        UIComponent facet = row.getFacet(UIFormLayoutRow.FACET_LABEL);
        if(facet!=null) {
            writeFormRowDataLabelFacet(context, w, c, row, edit, facet);
        } else {
            JSUtil.writeTextBlank(w); // &nbsp;
        }
    }
}
 
Example 44
Project: XPagesExtensionLibrary   File: FormLayoutRenderer.java   Source Code and License 6 votes vote down vote up
protected void writeFormRowDataHelp(FacesContext context, ResponseWriter w, FormLayout c, UIFormLayoutRow row, UIInput edit, String helpId) throws IOException {
    // TODO: how should the help be implemented?
    w.startElement("a", c);
    w.writeAttribute("href", "javascript:;", null); // $NON-NLS-1$ $NON-NLS-2$
    w.writeAttribute("aria-haspopup", "true", null); // $NON-NLS-1$ $NON-NLS-2$
    w.writeAttribute("aria-owns", helpId, null); // $NON-NLS-1$
    w.startElement("img", c); // $NON-NLS-1$
    String style = (String)getProperty(PROP_HELPIMGSTYLE);
    if(StringUtil.isNotEmpty(style)) {
        w.writeAttribute("style", style, null); // $NON-NLS-1$
    }
    String cls = (String)getProperty(PROP_HELPIMGCLASS);
    if(StringUtil.isNotEmpty(cls)) {
        w.writeAttribute("class", cls, null); // $NON-NLS-1$
    }
    String bgif = (String)getProperty(PROP_HELPIMGSRC);
    if(StringUtil.isNotEmpty(bgif)) {
        w.writeAttribute("src",HtmlRendererUtil.getImageURL(context,bgif),null); // $NON-NLS-1$
    }
    String alt = (String)getProperty(PROP_HELPIMGALT);
    if(StringUtil.isNotEmpty(alt)) {
        w.writeAttribute("alt", alt, null); // $NON-NLS-1$
    }
    w.endElement("img"); // $NON-NLS-1$
    w.endElement("a");
}
 
Example 45
Project: XPagesExtensionLibrary   File: DojoToggleButtonRenderer.java   Source Code and License 6 votes vote down vote up
@Override
protected void writeValueAttribute(FacesContext context, UIInput component, ResponseWriter writer, String currentValue) throws IOException {
    UIDojoToggleButton ck = (UIDojoToggleButton)component;
    Object oCheckedValue = ck.getCheckedValue();
    String checkedValue = null;
    if (oCheckedValue != null) {
    	checkedValue = oCheckedValue.toString();
    }
    if(checkedValue==null) {
        checkedValue = UIDojoCheckBox.CHECKED_VALUE_DEFAULT;
    }
    if(StringUtil.equals(checkedValue, currentValue)) {
        // Should it be a dojo attribute instead?
        writer.writeAttribute("value", "on", null); //$NON-NLS-1$ //$NON-NLS-2$
    }
}
 
Example 46
Project: XPagesExtensionLibrary   File: UIFormLayoutRow.java   Source Code and License 6 votes vote down vote up
/**
 * Find the edit component associated to this row.
 * @return the UIInput, or null if none is found
 */
public UIInput getForComponent() {
    // Find the component based on its id
    String id = getFor();
    if(StringUtil.isNotEmpty(id)) {
        UIComponent edit = FacesUtil.getComponentFor(this, id);
        if(edit==null) {
            throw new FacesExceptionEx(null,"Unknown component {0} assigned to the \"for\" property of the form row",id); // $NLX-UIFormLayoutRow.Unknowncomponent0assignedtothefor-1$
        }
        if(!(edit instanceof UIInput)) {
            return null;
            //throw new FacesExceptionEx(null,"The for component {0} must be an input component",id);
        }
        return (UIInput)edit;
    }
    
    // Else, look for the first child that is an edit component
    return findEdit(this);
}
 
Example 47
Project: XPagesExtensionLibrary   File: FormTableRenderer.java   Source Code and License 6 votes vote down vote up
@Override
protected void writeFormRowHelp(FacesContext context, ResponseWriter w, FormLayout c, UIFormLayoutRow row, UIInput edit) throws IOException {
    String helpId = row.getHelpId();
    String helpStyle = (String)getProperty(PROP_HELPROWSTYLE);
    if(StringUtil.isNotEmpty(helpStyle)) {
        w.writeAttribute("style", helpStyle, null); // $NON-NLS-1$
    }
    if(StringUtil.isNotEmpty(helpId)) {
        String forClientId = null;
        UIComponent forComponent = FacesUtil.getComponentFor(c, helpId);
        if(forComponent == null) {
            UIComponent p = (UIComponent)FacesUtil.getNamingContainer(c);
            if(p!=null) {
               forClientId = p.getClientId(context)+":"+helpId;
            }
        } else {
            forClientId = forComponent.getClientId(context);
        }
        writeFormRowDataHelp(context, w, c, row, edit, forClientId);
    } else {
        UIComponent facet = row.getFacet(UIFormLayoutRow.FACET_HELP);
        if(facet!=null) {
            writeFormRowDataHelpFacet(context, w, c, row, edit, facet);
        }
    }
}
 
Example 48
Project: XPagesExtensionLibrary   File: MobileTypeAheadInputRenderer.java   Source Code and License 6 votes vote down vote up
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
    
    Map<String, Object> attrs = TypedUtil.getAttributes(component);
    String initializedKey = "_initialized_MobileTypeAheadInputRenderer"; //$NON-NLS-1$
    if( null == attrs.get(initializedKey) ){
        UIInput input = (UIInput) component;
        XspTypeAhead typeAhead = findTypeAheadChild(input);
        if( null != typeAhead && typeAhead.isTypeAheadEnabled(context)){
            initTypeAhead(context, input, typeAhead);
            validateNoSeparator(context, input, typeAhead);
        }
        attrs.put(initializedKey, "true"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    
    super.encodeBegin(context, component);
}
 
Example 49
Project: XPagesExtensionLibrary   File: MobileTypeAheadInputRenderer.java   Source Code and License 6 votes vote down vote up
private void initTypeAhead(FacesContext context, UIInput input, XspTypeAhead typeAhead) {
    
    // prevent setParent after restoreState from overwriting the rendererType set in the theme file
    String themeConfiguredInputRendererType = input.getRendererType();
    typeAhead.setParentRendererType(themeConfiguredInputRendererType);
    
    // TODO have to do this overriding here instead of in the theme file
    // because XspTypeAhead doesn't implement ThemeControl
    String existingDojoType = typeAhead.getDojoType();
    if( null == existingDojoType ){
        String dojoType= COMBOBOX_MODULE.getName();
        typeAhead.setDojoType(dojoType);
    }
    
    String existingStoreType = typeAhead.getDojoStoreType();
    if( null == existingStoreType ){
        String storeType = "extlib.store.TypeAheadStore"; //$NON-NLS-1$
        typeAhead.setDojoStoreType(storeType);
    }
}
 
Example 50
Project: XPagesExtensionLibrary   File: InputDateRenderer.java   Source Code and License 6 votes vote down vote up
private boolean isUsingInputPlainText(FacesContext context, UIInput component) {
    
    // most browsers use <input type=datetime, but for iOS defaulting to type=text
    boolean isUseInputPlainTextOnIOS = true;
    String option = ((FacesContextEx)context).getProperty("xsp.theme.mobile.iOS.native.dateTime"); //$NON-NLS-1$
    if( null != option ){
        // explicitly configured whether to use type=datetime on iOS
        boolean isNativeOnIOS = "true".equals(option); //$NON-NLS-1$
        isUseInputPlainTextOnIOS = ! isNativeOnIOS;
    }
    if( isUseInputPlainTextOnIOS ){
        Object deviceBeanObj = ExtLibUtil.resolveVariable(context, "deviceBean"); //$NON-NLS-1$
        if( deviceBeanObj instanceof DeviceBean ){
            DeviceBean deviceBean = (DeviceBean)deviceBeanObj;
            boolean isIOS = deviceBean.isIphone()|| deviceBean.isIpad() || deviceBean.isIpod();
            if( isIOS ){
                // is iOS, so by use type=text
                return true;
            }
            // else other devices use type=datetime, not type=text
        }
    }
    // else always use type=datetime, don't need to whether check browser OS is iOS.
    return false;
}
 
Example 51
Project: GeoprocessingAppstore   File: InputSelectWithOther.java   Source Code and License 6 votes vote down vote up
/**
 * Triggered on the save event from the metadata editor.
 * <p/>
 * On this event, either HtmlSelectOneMenu input value or the HtmlInputText
 * value is propagated to the parameter's singleValue (depending on the 
 * whether or not the user has selected the "Other" option).
 * @param context the UI context
 * @param editorForm the Faces HtmlForm for the metadata editor
 * @param parameter the associated parameter
 * @throws SchemaException if an associated Faces UIComponent cannot be located
 */
@Override
public void unBind(UiContext context, 
                   UIComponent editorForm,
                   Parameter parameter) 
  throws SchemaException {
  UIInput menu = findInputComponent(context,editorForm);
  UIInput text = getOtherComponent().findInputComponent(context,editorForm);
  String sMenuValue = getInputValue(menu);
  String sTextValue = Val.chkStr(getInputValue(text));
  text.setValue(sTextValue);
  if (sMenuValue.equalsIgnoreCase(getOtherCodeKey())) {
    parameter.getContent().getSingleValue().setValue(sTextValue);
    if (text instanceof HtmlInputText) {
      ((HtmlInputText)text).setStyle("visibility:visible;");
    }
  } else {
    parameter.getContent().getSingleValue().setValue(sMenuValue);
    if (text instanceof HtmlInputText) {
      ((HtmlInputText)text).setStyle("visibility:hidden;");
    }
  }
}
 
Example 52
Project: GeoprocessingAppstore   File: InputDelimitedTextArea.java   Source Code and License 6 votes vote down vote up
/**
 * Triggered on the save event from the metadata editor.
 * <p/>
 * On this event, the multiple values associated with the parameter
 * (parameter.getMultipleValues()) are generated from the delimited 
 * input string.
 * @param context the UI context
 * @param editorForm the Faces HtmlForm for the metadata editor
 * @param parameter the associated parameter
 * @throws SchemaException if an associated Faces UIComponent cannot be located
 */
@Override
public void unBind(UiContext context, 
                   UIComponent editorForm,
                   Parameter parameter) 
  throws SchemaException {
  
  // tokenize the delimited input string
  UIInput input = findInputComponent(context,editorForm);
  String sDelimited = Val.chkStr(getInputValue(input));
  sDelimited = sDelimited.replaceAll("(\r\n|\r|\n|\n\r)",getDelimiter());
  String[] tokens = Val.tokenize(sDelimited,getDelimiter());
  
  // clear current values, append each token to the values collection
  parameter.getContent().clearAllValues();
  ContentValues values = parameter.getContent().getMultipleValues();
  for (String sValue: tokens) {
    if (sValue.length() > 0) {
      values.add(new ContentValue(sValue));
    }
  }
  input.setValue(makeDelimitedValue(parameter));
}
 
Example 53
Project: oscm   File: SubscriptionWizardConversation.java   Source Code and License 5 votes vote down vote up
public void validateSubscriptionId(FacesContext context,
        UIComponent toValidate, Object value) {
    model.setShowExternalConfigurator(false);
    String givenSubscriptionId = (String) value;
    boolean subscriptionIdAlreadyExists = getSubscriptionServiceInternal()
            .validateSubscriptionIdForOrganization(givenSubscriptionId);
    if (subscriptionIdAlreadyExists) {
        ((UIInput) toValidate).setValid(false);
        String clientFieldId = toValidate.getClientId(context);
        ui.handleError(clientFieldId, SUBSCRIPTION_NAME_ALREADY_EXISTS,
                new Object[] { givenSubscriptionId });
    }
}
 
Example 54
Project: oscm   File: BillingAdapterCtrl.java   Source Code and License 5 votes vote down vote up
public void validateDuplicatedId(final FacesContext context,
        final UIComponent component, final Object value) {

    String billingId = value.toString();
    POBillingAdapter billingAdapter = getBillingAdapter(billingId);

    if (billingAdapter.getBillingIdentifier() != null && billingId.equals(billingAdapter.getBillingIdentifier())) {
        ((UIInput) component).setValid(false);
        addMessage(component.getClientId(context),
                FacesMessage.SEVERITY_ERROR,
                ERROR_BILLING_ID_ALREADY_EXISTS,
                new Object[] { billingId });
    }
}
 
Example 55
Project: oscm   File: MessageListener.java   Source Code and License 5 votes vote down vote up
/**
 * Check if the component is an input component and if the style is the
 * error style.
 * 
 * @param uiComponent
 *            UI component
 * @return true if the component is an input component and if the style is
 *         the error style
 */
private boolean isErrorStyle(UIComponent uiComponent) {
    if (!(uiComponent instanceof UIInput)) {
        return false;
    }
    if (uiComponent instanceof UISelectBoolean) {
        return (STYLE_CHECKBOX_ERROR).equals(uiComponent.getAttributes()
                .get(ATTRIBUTE_STYLE));
    }
    return (STYLE_ERROR).equals(uiComponent.getAttributes().get(
            ATTRIBUTE_STYLE));
}
 
Example 56
Project: oscm   File: BillingAdapterCtrlTest.java   Source Code and License 5 votes vote down vote up
@Test
public void validateDuplicatedIds() throws SaaSApplicationException {
    FacesContext fc = mock(FacesContext.class);
    UIComponent component = mock(UIInput.class);
    doReturn(createBillingAdapter()).when(bean)
            .getBillingAdapter(any(String.class));

    bean.validateDuplicatedId(fc, component, "BILLING_ADAPTER1");
}
 
Example 57
Project: oscm   File: ExportBillingDataCtrlTest.java   Source Code and License 5 votes vote down vote up
@Test
public void billingTypeChanged_bug10285() {
    // given
    UIInput input = mock(UIInput.class);
    ValueChangeEvent e = new ValueChangeEvent(input, null, null);

    // when
    ctrl.billingTypeChanged(e);

    // then
    assertEquals(null, model.getSelectedBillingDataType());
}
 
Example 58
Project: myfaces-trinidad   File: ComponentReferenceTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testFailover() throws IOException, ClassNotFoundException
{
  UIViewRoot root = facesContext.getViewRoot();
  root.setId("root");
  UIInput input1 = new UIInput(); input1.setId("input1");

  // build the Tree...
  root.getChildren().add(input1);

  // Get the ComponentReference util
  ComponentReference<UIInput> uiRef = ComponentReference.newUIComponentReference(input1);

  // find the component...
  UIInput referencedComp = uiRef.getComponent();
  assertEquals(input1, referencedComp);
  
  // fake the failover
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);

  oos.writeObject(uiRef);
  oos.flush();

  ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream ois = new ObjectInputStream(bais);

  uiRef = (ComponentReference<UIInput>) ois.readObject();

  referencedComp = uiRef.getComponent();
  assertEquals(input1, referencedComp);
}
 
Example 59
Project: myfaces-trinidad   File: ComponentReferenceTest.java   Source Code and License 5 votes vote down vote up
public void testCustomFacet()
{
  UIViewRoot root = facesContext.getViewRoot();
  root.setId("root");
  UIForm form = new UIForm(); form.setId("form");
  UINamingContainer nc1 = new UINamingContainer(); nc1.setId("nc1");
  UINamingContainer nc2 = new UINamingContainer(); nc2.setId("nc2");
  UINamingContainer nc3 = new UINamingContainer(); nc3.setId("nc3");
  UIPanel panel = new UIPanel(); panel.setId("panel");
  UIInput input = new UIInput(); input.setId("input1");

  // build the Tree...
  panel.getFacets().put("fancyFacet", input);
  nc3.getChildren().add(panel);
  nc2.getChildren().add(new UIOutput());
  nc2.getChildren().add(new UIOutput());
  nc2.getChildren().add(nc3);
  nc1.getChildren().add(nc2);
  form.getChildren().add(new UIOutput());
  form.getChildren().add(new UIOutput());
  form.getChildren().add(new UIOutput());
  form.getChildren().add(nc1);
  root.getChildren().add(new UIOutput());
  root.getChildren().add(form);

  // Get the ComponentReference util
  ComponentReference<UIInput> uiRef = ComponentReference.newUIComponentReference(input);

  // find the component...
  UIInput referencedComp = uiRef.getComponent();
  assertEquals(input, referencedComp);
  
  // find it again!
  assertEquals(input, uiRef.getComponent());
}
 
Example 60
Project: myfaces-trinidad   File: ComponentReferenceTest.java   Source Code and License 5 votes vote down vote up
public void testCustomFacetWithFind()
{
  UIViewRoot root = new UIViewRoot();
  root.setId("root");
  UIForm form = new UIForm(); form.setId("form");
  UINamingContainer nc1 = new UINamingContainer(); nc1.setId("nc1");
  UINamingContainer nc2 = new UINamingContainer(); nc2.setId("nc2");
  UINamingContainer nc3 = new UINamingContainer(); nc3.setId("nc3");
  UIPanel panel = new UIPanel(); panel.setId("panel");
  UIInput input = new UIInput(); input.setId("input1");

  // build the Tree...
  panel.getFacets().put("fancyFacet", input);
  panel.getChildren().add(input);
  nc3.getChildren().add(panel);
  nc2.getChildren().add(new UIOutput());
  nc2.getChildren().add(new UIOutput());
  nc2.getChildren().add(nc3);
  nc1.getChildren().add(nc2);
  form.getChildren().add(new UIOutput());
  form.getChildren().add(new UIOutput());
  form.getChildren().add(new UIOutput());
  form.getChildren().add(nc1);
  root.getChildren().add(new UIOutput());
  root.getChildren().add(form);
  
  facesContext.setViewRoot(root);

  // Get the ComponentReference util
  ComponentReference<UIInput> uiRef = ComponentReference.newUIComponentReference(input);

  // find the component...
  UIInput referencedComp = uiRef.getComponent();
  assertEquals(input, referencedComp);

  // find it again!
  assertEquals(input, uiRef.getComponent());

}