Java Code Examples for javax.faces.application.FacesMessage

The following are top voted examples for showing how to use javax.faces.application.FacesMessage. 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: myfaces-trinidad   File: LongRangeValidator.java   Source Code and License 7 votes vote down vote up
private FacesMessage _getMaximumMessage(
  FacesContext context,
  UIComponent component,
  Object value,
  Object max)
{

  Object msg   = _getRawMaximumMessageDetail();
  Object label = ValidatorUtils.getComponentLabel(component);

  Object[] params = {label, value, max};

  return MessageFactory.getMessage(context,
                                   MAXIMUM_MESSAGE_ID,
                                   msg,
                                   params,
                                   component);
}
 
Example 2
Project: oscm   File: OrganizationBean.java   Source Code and License 7 votes vote down vote up
/**
 * Save the current organization and user profile
 * 
 * @return the logical outcome.
 * @throws SaaSApplicationException
 * @throws ImageException
 *             Thrown in case the access to the uploaded file failed.
 */
public String save() throws SaaSApplicationException {

    VOUserDetails user = null;
    if (currentUser != null) {
        user = currentUser.getVOUserDetails();
    }
    getAccountingService().updateAccountInformation(organization, user,
            getMarketplaceId(), getImageUploader().getVOImageResource());
    currentUser = null;
    if (user != null) {
        // update the value object in the session
        setUserInSession(getCurrentUser().getVOUserDetails());
        addMessage(null, FacesMessage.SEVERITY_INFO,
                INFO_USER_PROFILE_SAVED, getUserFromSession().getUserId());
    } else if (organization != null) {
        addMessage(null, FacesMessage.SEVERITY_INFO,
                INFO_ORGANIZATION_SAVED, getUserFromSession()
                        .getOrganizationId());
    }
    organization = null; // load the organization again

    return OUTCOME_SUCCESS;
}
 
Example 3
Project: Trabalhos-FIAP   File: CadastroCategoriaMB.java   Source Code and License 7 votes vote down vote up
public void cadastrarCategoria(){
	NetgifxCommand command = new NetgifxCommand();

	if (command.buscarCategoria(descricaoCategoria) == null) {
		command.cadastrarCategoria(new Categoria(descricaoCategoria));
		
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Categoria cadastrada com sucesso!", "Categoria cadastrada com sucesso!"));

		this.descricaoCategoria = null;

	} else {
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
				"Categoria j� cadastrada!", "Categoria j� cadastrada!"));
	}
	
}
 
Example 4
Project: Trabalhos-FIAP   File: CadastroUsuarioMB.java   Source Code and License 7 votes vote down vote up
public void cadastrarUsuario(){
	 
	 NetgifxCommand command = new NetgifxCommand();
	 
	 if(command.buscarUsuario(usuario.getApelido()) == null){
		 
		 command.cadastrarUsuario(usuario);
		 FacesContext.getCurrentInstance().addMessage(
                 null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                 "Usu�rio cadastrado com sucesso!", "Usu�rio cadastrado com sucesso!"));
		 this.usuario = new Usuario();
	 }else{
		 FacesContext.getCurrentInstance().addMessage(
                 null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                 "J� existe cadastro com este apelido!", "J� existe cadastro com este apelido!"));			 
	 }

	 
}
 
Example 5
Project: oscm   File: MarketplaceBean.java   Source Code and License 7 votes vote down vote up
/**
 * Deletes a marketplace.
 */
public String deleteMarketplace() throws SaaSApplicationException {
    try {
        if (isTokenValid()) {
            getMarketplaceService().deleteMarketplace(
                    marketplace.getMarketplaceId());

            addMessage(null, FacesMessage.SEVERITY_INFO,
                    INFO_MARKETPLACE_DELETED,
                    marketplace.getMarketplaceId());
            resetToken();
        }
    } finally {
        checkMarketplaceDropdownAndMenuVisibility(null);
    }
    return null;
}
 
Example 6
Project: oscm   File: TechServiceBean.java   Source Code and License 7 votes vote down vote up
/**
 * Import an XML file with technical service definitions
 * 
 * @return the logical outcome.
 * @throws SaaSApplicationException
 *             Thrown from the business logic.
 */
public String xmlImport() throws SaaSApplicationException {
    
    if (PartHandler.isEmpty(uploadedFile)) {
        addMessage(null, FacesMessage.SEVERITY_ERROR, ERROR_EMPTY_FILE);
        return OUTCOME_ERROR;
    }
    
    try {          
        byte[] buffer = PartHandler.getBuffer(uploadedFile);
        getProvisioningService().importTechnicalServices(buffer);

        selectedTechnicalService = null;
        technicalServices = null;
        addMessage(null, FacesMessage.SEVERITY_INFO,
                INFO_TECH_SERVICE_IMPORTED);
    } catch (IOException e) {
        ImportException ex = new ImportException(e.getLocalizedMessage());
        logger.logError(Log4jLogger.SYSTEM_LOG, ex,
                LogMessageIdentifier.ERROR_IMPORT_XML_FAILED);
        throw ex;
    }

    return OUTCOME_SUCCESS;
}
 
Example 7
Project: tap17-muggl-javaee   File: AbstractBean.java   Source Code and License 7 votes vote down vote up
/**
 * <p>Add a localized message to the
 * <code>FacesContext</code> for the current request.</p>
 *
 * @param clientId Client identifier of the component this message relates
 * to, or <code>null</code> for global messages
 * @param key Message key of the message to include
 */
protected void message(String clientId, String key) {
    // Look up the requested message text
    String text;

    try {
        ResourceBundle bundle = ResourceBundle.getBundle(
                "javaeetutorial.dukesbookstore.web.messages.Messages",
                context().getViewRoot().getLocale());
        text = bundle.getString(key);
    } catch (Exception e) {
        text = "???" + key + "???";
    }

    // Construct and add a FacesMessage containing it
    context().addMessage(clientId, new FacesMessage(text));
}
 
Example 8
Project: oscm   File: UserImportBeanTest.java   Source Code and License 7 votes vote down vote up
/**
 * Bug 9177 - show a more specific error message on import error with user
 * with leading/trailing blanks on email.
 */
@Test
public void importUsers_MessageOnInvalidMail() throws Exception {
    final String email = " [email protected] ";

    // given
    givenClassicPortalUserAndRoleSelection();
    
    willThrow(
            new ValidationException(ReasonEnum.EMAIL, "email",
                    new Object[] { email })).given(identityService)
            .importLdapUsers(anyListOf(VOUserDetails.class), anyString());

    // when
    bean.importUsers();
    // then
    verify(bb, times(1)).addMessage(eq((String) null),
            eq(FacesMessage.SEVERITY_ERROR),
            eq(UserImportBean.ERROR_IMPORT_EMAIL), eq(email));
}
 
Example 9
Project: oscm   File: SubscriptionWizardConversationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void selectServiceHIDE_PAYMENT_INFO() {
    // given
    initDataForSelectServiceWithoutParams();
    doNothing().when(bean).addMessage(any(FacesMessage.Severity.class),
            anyString());
    doReturn(true).when(subscriptionService).isPaymentInfoHidden();
    
    VOUserDetails voUserDetails = new VOUserDetails();
    voUserDetails.setKey(1000L);
    Set<UserRoleType> userRoles = new HashSet<>();
    userRoles.add(UserRoleType.ORGANIZATION_ADMIN);
    voUserDetails.setUserRoles(userRoles);
    doReturn(voUserDetails).when(ui).getUserFromSessionWithoutException();
    VOSubscriptionDetails subscription = new VOSubscriptionDetails();
    bean.getModel().setSubscription(subscription);
    
    // when
    String result = bean.selectService();
    // then
    assertEquals("success", result);
}
 
Example 10
Project: oscm   File: ExternalServicePriceModelCtrl.java   Source Code and License 6 votes vote down vote up
public void upload(VOServiceDetails service) {
    try {
        PriceModel priceModel = getExternalPriceModelService()
                .getExternalPriceModelForService(service);
        if (priceModel == null) {
            throw new ExternalPriceModelException();
        }
        loadPriceModelContent(priceModel);

        addMessage(null, FacesMessage.SEVERITY_INFO,
                INFO_EXTERNAL_PRICE_UPLOADED);
    } catch (ExternalPriceModelException e) {
        addMessage(null, FacesMessage.SEVERITY_ERROR,
                ERROR_EXTERNAL_PRICEMODEL_NOT_AVAILABLE);
    }
}
 
Example 11
Project: oscm-app   File: ManageServiceInstanceCtrlTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getInitialize_Success() throws Exception {
    // given
    ctrl.setModel(null);
    List<ServiceInstance> serviceInstances = givenServiceInstances();
    EnumSet<InstanceOperation> operaions = EnumSet.of(
            InstanceOperation.DELETE, InstanceOperation.RESUME);
    doReturn(session).when(request).getSession();
    doReturn("1").when(session).getAttribute(
            SessionConstants.SESSION_CTRL_ID);
    doReturn(serviceInstances).when(serviceInstanceService)
            .getInstancesForController(anyString());
    doReturn(operaions).when(serviceInstanceService)
            .listOperationsForInstance(any(ServiceInstance.class));

    // when
    ctrl.getInitialize();

    // then
    verify(facesContext, times(0)).addMessage(anyString(),
            any(FacesMessage.class));
}
 
Example 12
Project: oscm   File: OrganizationBean.java   Source Code and License 6 votes vote down vote up
/**
 * Delete the current organization
 * 
 * @return the logical outcome.
 * @throws DeletionConstraintException
 *             Thrown if the organization has active subscriptions
 */
public String delete() throws DeletionConstraintException {
    if (logger.isDebugLoggingEnabled()) {

    }
    try {
        getAccountingService().deregisterOrganization();
    } catch (TechnicalServiceNotAliveException
            | TechnicalServiceOperationException e) {
        logger.logError(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.ERROR_ORGANIZATION_DELETION_FAILED);
        addMessage(null, FacesMessage.SEVERITY_ERROR,
                ERROR_DELETE_USER_FROM_EXPIRED_SUBSCRIPTION);
        return "";
    }
    if (logger.isDebugLoggingEnabled()) {

    }
    return OUTCOME_LOGIN;
}
 
Example 13
Project: ctsms   File: MoneyTransferBean.java   Source Code and License 6 votes vote down vote up
@Override
protected void initSpecificSets(boolean reset) {
	moneyTransferModel.setProbandId(in.getProbandId());
	moneyTransferModel.updateRowCount();
	filterBankAccounts = new ArrayList<SelectItem>(bankAccounts);
	filterBankAccounts.add(0, new SelectItem(CommonUtil.NO_SELECTION_VALUE, ""));
	filterTrials = WebUtil.getReimbursementTrials(probandId, null, null, null);
	filterTrials.add(0, new SelectItem(CommonUtil.NO_SELECTION_VALUE, ""));
	reimbursementTrials = WebUtil.getReimbursementTrials(probandId, null, payOffPaymentMethod, false);
	filterCostTypes = WebUtil.getMoneyTransferFilterCostTypes(null, null, null, probandId);
	openSummary = WebUtil.getProbandOpenReimbursementSummary(null, probandId, payOffPaymentMethod);
	proband = WebUtil.getProband(this.in.getProbandId(), null, null, null);
	trial = WebUtil.getTrial(this.in.getTrialId());
	if (proband != null) { // this bean is postconstructed for soem reason
		if (!WebUtil.isProbandPerson(proband)) {
			Messages.addLocalizedMessage(FacesMessage.SEVERITY_INFO, MessageCodes.PROBAND_NOT_PERSON);
		} else {
			if (WebUtil.isProbandLocked(proband)) {
				Messages.addLocalizedMessage(FacesMessage.SEVERITY_WARN, MessageCodes.PROBAND_LOCKED);
			}
			if (WebUtil.isTrialLocked(trial)) {
				Messages.addLocalizedMessage(FacesMessage.SEVERITY_WARN, MessageCodes.TRIAL_LOCKED);
			}
		}
	}
}
 
Example 14
Project: myfaces-trinidad   File: LocaleUtils.java   Source Code and License 6 votes vote down vote up
private static ResourceBundle _getDefaultFacesMessageBundle(
  Locale locale,
  ClassLoader loader
  )
{
  ResourceBundle bundle = null;
  try
  {
    bundle =
      ResourceBundle.getBundle(FacesMessage.FACES_MESSAGES, locale, loader);
  }
  catch (MissingResourceException missingResource)
  {
    _LOG.severe("UNABLE_LOAD_FACES_BUNDLE", FacesMessage.FACES_MESSAGES);
    _LOG.severe(missingResource);
  }
  return bundle;
}
 
Example 15
Project: oscm   File: ExportBillingDataCtrl.java   Source Code and License 6 votes vote down vote up
public String showBillingData() throws IOException {

        if (model.getBillingData() == null) {
            JSFUtils.addMessage(null, FacesMessage.SEVERITY_ERROR,
                    ERROR_SHOW_BILLING_DATA, null);
            logger.logError(LogMessageIdentifier.ERROR_EXECUTE_SHOW_BILLING_DATA_WITH_NULL_DATA);
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
        String filename = sdf.format(Calendar.getInstance().getTime())
                + "_BillingData.xml";
        String contentType = "text/xml";
        JSFUtils.writeContentToResponse(model.getBillingData(), filename,
                contentType);

        return "success";
    }
 
Example 16
Project: oscm   File: ServiceActivationBean.java   Source Code and License 6 votes vote down vote up
/**
 * Resumes a service.
 * 
 * @return the updated service
 */
public String resumeService() {

    Service selectedService = serviceDetailsModel.getSelectedService();
    if (selectedService != null) {
        try {
            setService(getProvisioningService().resumeService(
                    selectedService.getVO()));
        } catch (SaaSApplicationException ex) {
            ExceptionHandler.execute(ex);
            return OUTCOME_ERROR;
        }
    }
    addMessage(null, FacesMessage.SEVERITY_INFO, INFO_SERVICE_RESUMED);
    serviceDetailsModel.setSelectedServiceKey(serviceDetailsModel
            .getSelectedService().getKey() + "");

    return OUTCOME_SUCCESS;
}
 
Example 17
Project: oscm   File: AbsOrRelUrlValidator.java   Source Code and License 6 votes vote down vote up
/**
 * Validates that the given value is a relative or absolute URL
 * 
 * @param context
 *            FacesContext for the request we are processing
 * @param component
 *            UIComponent we are checking for correctness
 * @param value
 *            the value to validate
 * @throws ValidatorException
 *             if validation fails
 */
public void validate(FacesContext facesContext, UIComponent component,
        Object value) throws ValidatorException {
    if (value == null) {
        return;
    }
    String str = value.toString();
    if (str.length() == 0) {
        return;
    }

    if (ADMValidator.isAbsoluteOrRelativeUrl(str)) {
        return;
    }
    Object[] args = null;
    String label = JSFUtils.getLabel(component);
    if (label != null) {
        args = new Object[] { label };
    }
    ValidationException e = new ValidationException(
            ValidationException.ReasonEnum.URL, label, null);
    String text = JSFUtils.getText(e.getMessageKey(), args, facesContext);
    throw new ValidatorException(new FacesMessage(
            FacesMessage.SEVERITY_ERROR, text, null));
}
 
Example 18
Project: ctsms   File: VisitScheduleBean.java   Source Code and License 6 votes vote down vote up
private void initSets() {
	collidingProbandStatusEntryModelCache.clear();
	visitScheduleItemModel.setTrialId(in.getTrialId());
	visitScheduleItemModel.updateRowCount();
	visits = WebUtil.getVisits(in.getTrialId());
	probandGroups = WebUtil.getProbandGroups(in.getTrialId());
	filterProbandGroups = new ArrayList<SelectItem>(probandGroups);
	filterProbandGroups.add(0, new SelectItem(CommonUtil.NO_SELECTION_VALUE, ""));
	filterVisits = new ArrayList<SelectItem>(visits);
	filterVisits.add(0, new SelectItem(CommonUtil.NO_SELECTION_VALUE, ""));
	matrix.initPages();
	// loadMatrix();
	trial = WebUtil.getTrial(this.in.getTrialId());
	if (WebUtil.isTrialLocked(trial)) {
		Messages.addLocalizedMessage(FacesMessage.SEVERITY_WARN, MessageCodes.TRIAL_LOCKED);
	}
}
 
Example 19
Project: oscm   File: PaymentConfigurationBean.java   Source Code and License 6 votes vote down vote up
/**
 * Initialized if necessary and returns the payment types that are enabled
 * by the platform operator for the supplier.
 * 
 * @return the enabled payment types
 */
public List<SelectedPaymentType> getEnabledPaymentTypesForSupplier() {
    if (!getCfgService().isPaymentInfoAvailable()) {
        JSFUtils.addMessage(null, FacesMessage.SEVERITY_WARN, BaseBean.WARNING_PAYMENT_TYPES_NOT_USED, null);
    }
    if (enabledPaymentTypes == null) {
        Set<VOPaymentType> availablePaymentTypes = getAccountingService()
                .getAvailablePaymentTypesForOrganization();
        enabledPaymentTypes = new ArrayList<>();
        for (VOPaymentType pt : availablePaymentTypes) {
            enabledPaymentTypes.add(new SelectedPaymentType(pt));
        }
        Collections.sort(enabledPaymentTypes, paymentTypeComparator);
    }

    return enabledPaymentTypes;
}
 
Example 20
Project: myfaces-trinidad   File: DateRestrictionValidator.java   Source Code and License 6 votes vote down vote up
/**
 * Builds an error message indicating invalid week-day selection
 * @param context FacesContext
 * @param component inputDate instance
 * @param converter date converter instance
 * @param value user submitted value
 * @param dayOfTheWeekIndex Week day index as returned by Calendar.DAY_OF_WEEK on the value
 * @return FacesMessage
 */
private FacesMessage _getWrongWeekDayMessage(
  FacesContext  context,
  UIComponent   component,
  Converter     converter,
  Object        value,
  int           dayOfTheWeekIndex)
{ 
  RequestContext reqContext = RequestContext.getCurrentInstance();      
  Locale locale = reqContext.getFormattingLocale();

  if (locale == null)
  {
    locale = context.getViewRoot().getLocale();
  }
    
  Object cValue = _getConvertedValue(context, component, converter, value);
  Object msg   = _getRawInvalidDaysOfWeekMessageDetail();
  Object label = ValidatorUtils.getComponentLabel(component);
  String[] weekdays = new DateFormatSymbols(locale).getWeekdays();

  // Fetch the localized week name 
  Object[] params = {label, cValue, weekdays[dayOfTheWeekIndex]};

  return MessageFactory.getMessage(context, WEEKDAY_MESSAGE_ID, msg, params, component);
}
 
Example 21
Project: oscm   File: TechServiceBean.java   Source Code and License 6 votes vote down vote up
/**
 * Delete the selected technical service.
 * 
 * @return the logical outcome.
 * @throws SaaSApplicationException
 */
public String delete() throws SaaSApplicationException {

    if (isTokenValid()) {
        if (selectedTechnicalService != null) {
            try {
                getProvisioningService().deleteTechnicalService(
                        selectedTechnicalService.getVo());
                sessionBean.setSelectedTechnicalServiceKey(0);
                addMessage(null, FacesMessage.SEVERITY_INFO,
                        INFO_TECH_SERVICE_DELETED,
                        new Object[] { selectedTechnicalService
                                .getTechnicalServiceId() });
            } finally {
                selectedTechnicalService = null;
                technicalServices = null;
            }
        }
        resetToken();
    }

    return OUTCOME_SUCCESS;
}
 
Example 22
Project: oscm   File: ManageGroupCtrl.java   Source Code and License 6 votes vote down vote up
public String selectGroup() {
    getUi().findSessionBean().setSelectedGroupId(
            manageGroupModel.getSelectedGroupId());
    if (manageGroupModel.getSelectedGroupId() == null) {
        JSFUtils.addMessage(null, FacesMessage.SEVERITY_ERROR,
                BaseBean.ERROR_INVALID_GROUP, null);
        return BaseBean.OUTCOME_REFRESH;
    }
    try {
        getUserGroupService().getUserGroupDetails(
                Long.valueOf(manageGroupModel.getSelectedGroupId())
                        .longValue());
    } catch (ObjectNotFoundException e) {
        JSFUtils.addMessage(null, FacesMessage.SEVERITY_ERROR,
                BaseBean.ERROR_INVALID_GROUP, null);
        return BaseBean.OUTCOME_REFRESH;
    }
    return BaseBean.OUTCOME_EDIT_GROUP;
}
 
Example 23
Project: myfaces-trinidad   File: MessageFactory.java   Source Code and License 6 votes vote down vote up
private static FacesMessage _createFacesMessage(
  FacesMessage.Severity severity,
  ErrorMessages messageStrings,
  Object label
  )
{
  if (messageStrings instanceof BindingErrorMessages)
  {
     return new BindingFacesMessage(severity, messageStrings, label);
  }

  String summary = messageStrings.getMessage();
  String detail  = messageStrings.getDetailMessage();

  return new LabeledFacesMessage(severity, summary, detail, label);
}
 
Example 24
Project: oscm   File: UpgradeWizardConversation.java   Source Code and License 6 votes vote down vote up
public String actionLoadIframe() {
    String jsonParameters = jsonConverter.getServiceParametersAsJsonString(
            model.getServiceParameters(), model.isReadOnlyParams(), true);
    if (jsonParameters != null && jsonParameters.length() > 0) {
        model.setServiceParametersAsJSONString(jsonParameters);
        model.setLoadIframe(true);
        model.setShowExternalConfigurator(true);
        return null;
    } else {
        model.setHideExternalConfigurator(true);
        model.setServiceParametersAsJSONString(null);
        addMessage(FacesMessage.SEVERITY_ERROR,
                ERROR_EXTERNAL_TOOL_COMMUNICATION);
        return OUTCOME_ERROR;
    }
}
 
Example 25
Project: ProjetoFinalInitium   File: UsuarioBean.java   Source Code and License 6 votes vote down vote up
public String salvar() {
		this.usuario.setAdministrador(true);
	importa();
	if (senha.equals(confirmarSenha)) {
		if (this.usuario.getId() == null) {
			this.usuario.setSenha(criptografia.criptografar(senha, "MD5"));
		}
		if (!dao.save(this.usuario)) {
			adicionarMensagem("Erro ao cadastrar a Usuario.", FacesMessage.SEVERITY_ERROR);
		} else {
			adicionarMensagem("Usuario salva com sucesso.", FacesMessage.SEVERITY_INFO);
			nomeUsuarioFiltrada = this.usuario.getNome();
			listarUsuario();
		}
	} else {
		adicionarMensagem("As senhas n�o s�o iguais.", FacesMessage.SEVERITY_INFO);
	}
	return "usuario";
}
 
Example 26
Project: myfaces-trinidad   File: TestScript.java   Source Code and License 6 votes vote down vote up
public MessageTest(String severity, String summary, String detail,
                   String clientId)
{
  FacesMessage.Severity sev = FacesMessage.SEVERITY_INFO;

  if (severity != null)
  {
    if ("ERROR".equals(severity))
      sev = FacesMessage.SEVERITY_ERROR;
    else if ("WARN".equals(severity) || "WARNING".equals(severity))
      sev = FacesMessage.SEVERITY_WARN;
    else if ("FATAL".equals(severity))
      sev = FacesMessage.SEVERITY_FATAL;
  }
  
  _messages.put(clientId, new FacesMessage(sev, summary, detail));
}
 
Example 27
Project: oscm   File: CompletePwdRecoveryCtrl.java   Source Code and License 6 votes vote down vote up
/**
 * Complete password recovery procedure:Change user password
 *
 * @return String <br>
 *         OUTCOME_SUCCESS | OUTCOME_ERROR
 */
public String completePasswordRecovery() {

    final String userId = this.model.getUserId();
    final String newPassword = this.model.getNewPassword();

    final boolean changePassword = this.getPasswordRecoveryService().completePasswordRecovery(userId, newPassword);

    if (changePassword) {
        this.addMessage(null, FacesMessage.SEVERITY_INFO, INFO_RECOVERPASSWORD_SUCCESS);
        return OUTCOME_SUCCESS;
    }

    this.addMessage(null, FacesMessage.SEVERITY_ERROR, ERROR_USER_PWD_RESET);
    return OUTCOME_ERROR;
}
 
Example 28
Project: photoiff   File: MenuItemBean.java   Source Code and License 6 votes vote down vote up
public void gravarMenuItem() {
	try {
		if(getMenuItem().getId() != null) {
			menuItemService.merge(getMenuItem());
		} else {
			menuItemService.create(getMenuItem());
		}
		
		setMenuItem(new MenuItem());
		FacesContext.getCurrentInstance().addMessage("Sucesso!", new FacesMessage("Sub-Menu Cadastrado com Sucesso!"));
		atualizarMenuItem();
		RequestContext.getCurrentInstance().execute("PF('subMenuDl').hide()");
	} catch (Exception e) {
		FacesContext.getCurrentInstance().addMessage("Aviso!", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Aviso", "Ocorreu um erro ao incluir o usuário. Entre em contato com administrador!"));
		e.printStackTrace();
	}	
}
 
Example 29
Project: ctsms   File: Messages.java   Source Code and License 5 votes vote down vote up
public static void addFieldInputMessages(String index, FacesMessage.Severity severity, String message) {
	if (index != null && index.length() > 0) {
		Iterator<String> it = INPUT_FIELD_COMPONENT_CLIENT_ID_PREFIXES.iterator();
		while (it.hasNext()) {
			Messages.addMessageId(it.next() + index, severity, message);
		}
	} else {
		Messages.addMessage(severity, message);
	}
}
 
Example 30
Project: oscm   File: ServiceBean.java   Source Code and License 5 votes vote down vote up
/**
 * Delete the selected service.
 * 
 * @return the logical outcome.
 * @throws SaaSApplicationException
 *             Thrown from the business logic.
 */
public String delete() throws SaaSApplicationException {
    if (selectedService == null) {
        return OUTCOME_ERROR;
    }
    if (logger.isDebugLoggingEnabled()) {

    }

    try {
        getProvisioningService().deleteService(
                selectedService.getVoServiceDetails());
        addMessage(null, FacesMessage.SEVERITY_INFO, INFO_SERVICE_DELETED,
                selectedService.getServiceId());
        sessionBean.setSelectedServiceKeyForSupplier(null);
        selectedService = null;
        services = null;
    } catch (ServiceStateException sse) {
        Object[] params = null;
        String localizedStatus = JSFUtils.getText(
                "ServiceStatus." + sse.getMessageParams()[1], params);
        addMessage(null, FacesMessage.SEVERITY_ERROR,
                CANNOT_DELETE_ACTIVE_SERVICE, localizedStatus);
        return OUTCOME_ERROR;
    }

    if (logger.isDebugLoggingEnabled()) {

    }
    return OUTCOME_SUCCESS;
}
 
Example 31
Project: ProjetoFinalInitium   File: CriterioBean.java   Source Code and License 5 votes vote down vote up
public void adicionarMensagem(String mensagem, Severity tipoMensagem) {
	FacesContext fc = FacesContext.getCurrentInstance();
	FacesMessage fm = new FacesMessage(mensagem);
	fm.setSeverity(tipoMensagem);
	fc.addMessage(null, fm);

}
 
Example 32
Project: ProjetoFinalInitium   File: UfBean.java   Source Code and License 5 votes vote down vote up
public void adicionarMensagem(String mensagem, Severity tipoMensagem) {
	FacesContext fc = FacesContext.getCurrentInstance();
	FacesMessage fm = new FacesMessage(mensagem);
	fm.setSeverity(tipoMensagem);
	fc.addMessage(null, fm);

}
 
Example 33
Project: oscm   File: ApplicationBean.java   Source Code and License 5 votes vote down vote up
public boolean checkLocaleValidation(String locale) {
    List<String> locales = getActiveLocales();
    boolean isValid = true;
    if (locales != null && locale != null) {
        if (!locales.contains(locale)) {
            isValid = false;
            addMessage(null, FacesMessage.SEVERITY_WARN,
                    BaseBean.WARNING_SUPPORTEDLANGUAGE_LOCALE_INVALID,
                    new Locale(locale).getDisplayLanguage(ui
                            .getViewLocale()));
        }
    }

    return isValid;
}
 
Example 34
Project: ProjetoFinalInitium   File: AvaliadorBean.java   Source Code and License 5 votes vote down vote up
public String remover(Usuario usuario) {
	if (!dao.delete(usuario.getId())) {
		adicionarMensagem("Erro ao remover a Usuario.", FacesMessage.SEVERITY_ERROR);
	} else {
		adicionarMensagem("Usuario removida com sucesso.", FacesMessage.SEVERITY_INFO);
		listarUsuario();
	}
	return "avaliador";
}
 
Example 35
Project: ProjetoFinalInitium   File: AvaliadorBean.java   Source Code and License 5 votes vote down vote up
public void adicionarMensagem(String mensagem, Severity tipoMensagem) {
	FacesContext fc = FacesContext.getCurrentInstance();
	FacesMessage fm = new FacesMessage(mensagem);
	fm.setSeverity(tipoMensagem);
	fc.addMessage(null, fm);

}
 
Example 36
Project: oscm   File: ExportBillingDataCtrlTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setupClass() {
    new FacesContextStub(Locale.ENGLISH) {
        public void addMessage(String arg0, FacesMessage arg1) {
            // the implementation of the stub throws an
            // OperationNotSupportedException
        }
    };
}
 
Example 37
Project: oscm   File: IndexesBean.java   Source Code and License 5 votes vote down vote up
public String recreate() {

        try {
            search.initIndexForFulltextSearch(true);

            JSFUtils.addMessage(null, FacesMessage.SEVERITY_INFO,
                    BaseBean.INFO_RECREATE_INDEXES, null);

        } catch (Exception e) {
            logger.logError(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.ERROR_INVALID_JSON);
        }

        return BaseBean.OUTCOME_SUCCESS;
    }
 
Example 38
Project: NICON   File: Mensagem.java   Source Code and License 5 votes vote down vote up
public static void addWarningMsg(String mensagem)
{
    FacesContext facesContext = FacesContext.getCurrentInstance();
    FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, mensagem, mensagem);
    FacesContext  context = FacesContext.getCurrentInstance();
    context.addMessage(null, fm);  
}
 
Example 39
Project: oscm   File: ManageUdaDefinitionBeanTest.java   Source Code and License 5 votes vote down vote up
@Test
public void delete_Ok() throws Exception {
    // given
    doNothing().when(controller).deleteUdaDefinition();
    // when
    String result = bean.delete();
    // then
    verify(controller, times(1)).deleteUdaDefinition();
    assertEquals(BaseBean.OUTCOME_SUCCESS, result);
    verifyAddedMessage(FacesMessage.SEVERITY_INFO,
            BaseBean.INFO_UDADEFINITIONS_DELETED);
}
 
Example 40
Project: microservices-tcc-alfa   File: ClienteController.java   Source Code and License 5 votes vote down vote up
public void excluirCliente() {
	try {
		clienteService.excluirCliente(clienteEdicao);
		pesquisarClientes();
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Cliente excluído com sucesso!"));
	} catch (Exception e) {
		FacesContext.getCurrentInstance().addMessage(null, 
				new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao excluir cliente!\n" + e.getMessage(), null));
	}
}
 
Example 41
Project: oscm   File: ManageLanguageCtrlTest.java   Source Code and License 5 votes vote down vote up
private boolean containsMessageInList(FacesContext fc, String msg) {
    for (Iterator<FacesMessage> i = fc.getMessages(); i.hasNext();) {
        if (i.next().getDetail().contains(msg)) {
            return true;
        }
    }
    return false;
}
 
Example 42
Project: admin-persistence   File: Messages.java   Source Code and License 5 votes vote down vote up
public static void addDetailMessage(String message, FacesMessage.Severity severity) {

        FacesMessage facesMessage = new FacesMessage("", message);
        if (severity != null && severity != FacesMessage.SEVERITY_INFO) {
            facesMessage.setSeverity(severity);
        }

        FacesContext.getCurrentInstance().addMessage(null, facesMessage);
    }
 
Example 43
Project: ProjetoFinalInitium   File: CriterioBean.java   Source Code and License 5 votes vote down vote up
public String remover(Criterio criterio) {
	if (!dao.delete(criterio.getId())) {
		adicionarMensagem("Erro ao remover o criterio .", FacesMessage.SEVERITY_ERROR);
	} else {
		adicionarMensagem("Criterio removido com sucesso.", FacesMessage.SEVERITY_INFO);
		listarCriterio();
	}
	return "criterio";
}
 
Example 44
Project: myfaces-trinidad   File: NewMessageBackingBean.java   Source Code and License 5 votes vote down vote up
private void _showSendException(Exception e)
{
  FacesContext context = FacesContext.getCurrentInstance();
  context.addMessage(null,
                     new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                      e.getMessage(), null));
  _LOG.log(Level.WARNING, "Couldn't send message", e);
}
 
Example 45
Project: oscm-app   File: ManageServiceInstanceCtrlTest.java   Source Code and License 5 votes vote down vote up
@Test
public void executeService_AbortPending() throws Exception {
    // given
    model.setToken(model.getToken());
    model.setInitialized(true);
    model.setServiceInstanceRows(givenServiceInstanceRowsWithAbortPending());
    model.setSelectedInstanceId("instanceId1");
    doReturn(session).when(request).getSession();
    doReturn("1").when(session).getAttribute(
            SessionConstants.SESSION_CTRL_ID);
    doNothing().when(ctrl.serviceInstanceService).executeOperation(
            any(ServiceInstance.class), any(ServiceUser.class),
            any(InstanceOperation.class));
    doReturn("uid").when(session).getAttribute(
            SessionConstants.SESSION_USER_ID);
    doReturn("en").when(session).getAttribute(
            SessionConstants.SESSION_USER_LOCALE);
    ServiceInstance dbInstance = new ServiceInstance();
    dbInstance.setRunWithTimer(false);
    dbInstance.setControllerReady(false);
    doReturn(dbInstance).when(serviceInstanceService).find(
            any(ServiceInstance.class), anyString());

    // when
    String result = ctrl.executeService();

    // then
    assertEquals(OUTCOME_SUCCESS, result);
    assertEquals(Boolean.TRUE, model.isInitialized());
    verify(facesContext, times(2)).addMessage(anyString(),
            any(FacesMessage.class));
}
 
Example 46
Project: Multicentro_Mascotas   File: ThemeConverter.java   Source Code and License 5 votes vote down vote up
public Object getAsObject(FacesContext fc, UIComponent uic, String value)
/*    */   {
/* 30 */     if ((value != null) && (value.trim().length() > 0)) {
/*    */       try {
/* 32 */         ThemeService service = (ThemeService)fc.getExternalContext().getApplicationMap().get("themeService");
/* 33 */         return service.getThemes().get(Integer.parseInt(value));
/*    */       } catch (NumberFormatException e) {
/* 35 */         throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
/*    */       }
/*    */     }
/*    */ 
/* 39 */     return null;
/*    */   }
 
Example 47
Project: oscm   File: BrandBeanTest.java   Source Code and License 5 votes vote down vote up
@Test
public void validateCurrentUrl_InvalidUrl() {
    // given
    brandBean.setBrandingUrl(INVALID_URL);

    // when
    brandBean.validateCurrentUrl();

    // then
    assertEquals(1, facesMessages.size());
    assertEquals(FacesMessage.SEVERITY_ERROR, facesMessages.get(0)
            .getSeverity());
}
 
Example 48
Project: atbash-octopus   File: FacesMessages.java   Source Code and License 5 votes vote down vote up
private FacesMessage.Severity determineSeverity(String key) {
    FacesMessage.Severity result = FacesMessage.SEVERITY_INFO;
    String[] parts = key.substring(1).split("\\.");
    result = checkSeverity(result, parts[0], "error", FacesMessage.SEVERITY_ERROR);
    result = checkSeverity(result, parts[0], "warn", FacesMessage.SEVERITY_WARN);
    result = checkSeverity(result, parts[0], "fatal", FacesMessage.SEVERITY_FATAL);
    return result;
}
 
Example 49
Project: ProjetoFinalInitium   File: ProvaBean.java   Source Code and License 5 votes vote down vote up
public void adicionarMensagem(String mensagem, Severity tipoMensagem) {
	FacesContext fc = FacesContext.getCurrentInstance();
	FacesMessage fm = new FacesMessage(mensagem);
	fm.setSeverity(tipoMensagem);
	fc.addMessage(null, fm);

}
 
Example 50
Project: ctsms   File: InquiryBean.java   Source Code and License 5 votes vote down vote up
private void initSets() {
	initInquiryModel();
	trial = WebUtil.getTrial(this.in.getTrialId());
	if (WebUtil.isTrialLocked(trial)) {
		Messages.addLocalizedMessage(FacesMessage.SEVERITY_WARN, MessageCodes.TRIAL_LOCKED);
	}
	if (out != null && out.isDeferredDelete()) { // && Settings.getBoolean(SettingCodes.INQUIRY_DEFERRED_DELETE, Bundle.SETTINGS, DefaultSettings.INQUIRY_DEFERRED_DELETE)) {
		Messages.addLocalizedMessage(FacesMessage.SEVERITY_WARN, MessageCodes.MARKED_FOR_DELETION);
	}
}
 
Example 51
Project: oscm   File: AppConfigurationCtrlTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getInitialize_Success() throws Exception {
    // given
    doReturn(items).when(appConfigService).getControllerOrganizations();

    // when
    ctrl.getInitialize();

    // then
    verify(facesContext, times(0)).addMessage(anyString(),
            any(FacesMessage.class));

}
 
Example 52
Project: oscm   File: ManageLanguageCtrlTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("boxing")
@Test
public void importTranslations_translationMissingAndDuplicatKeys()
        throws Exception {
    // given
    ManageLanguageCtrl mlSpy = spy(ctrl);
    final List<FacesMessage> facesMessages = new ArrayList<FacesMessage>();
    final String firstValue = "{0} UI texts for {1} languages have been imported, but translations are multiple.";
    final String finalValue = "0 UI texts for 1 languages have been imported, but translations are multiple.";
    final String key = BaseBean.ERROR_FILE_IMPORT_TRANSLATIONS_MULTIPLEKEY_EXISTING;
    final String messageFortranslationMissing = "languages have been imported, but translations are missing.";

    context = givenContextStub(facesMessages);
    // given
    givenJSFUtilsMessage(context, key, firstValue, null);
    assertEquals(JSFUtils.existMessageInList(context, firstValue), true);
    prepareForImportWithException(mlSpy,
            "ex.PropertiesImportException.TRANSLATIONS_MISSING");

    // when
    String returnValue = mlSpy.importTranslations();

    // then
    verify(mlSpy.ui).resetDirty();
    verify(mlSpy, never()).addMissingTranslationWarning(anyString());

    assertEquals(BaseBean.OUTCOME_ERROR, returnValue);
    assertEquals(true, JSFUtils.existMessageInList(context, finalValue));
    assertFalse(containsMessageInList(context, messageFortranslationMissing));

}
 
Example 53
Project: oscm   File: PaymentInfoBean.java   Source Code and License 5 votes vote down vote up
public String handlePspResult() {

        String outcome = OUTCOME_PSP_SUCCESS;
        pspResult = getPSPResult();
        if (pspResult == null || pspResult.trim().length() == 0) {
            pspResult = FAILURE;
        }
        if (SUCCESS.equals(pspResult)) {
            addMessage(null, FacesMessage.SEVERITY_INFO,
                    INFO_PAYMENT_INFO_SAVED);
        } else if (CANCELED.equals(pspResult)) {
            addMessage(null, FacesMessage.SEVERITY_ERROR,
                    "info.pspregistrationresult.cancel");
            outcome = OUTCOME_PSP_ERROR;
        } else if (FAILURE.equals(pspResult)) {
            addMessage(null, FacesMessage.SEVERITY_ERROR,
                    "error.pspregistrationresult.failure");
            outcome = OUTCOME_PSP_ERROR;
        } else if (WINDOW_CLOSED.equals(pspResult)) {
            outcome = WINDOW_CLOSED;
        }
        paymentRegistrationLink = null;
        pspResult = null;

        if (OUTCOME_PSP_SUCCESS.equals(outcome)) {
            // find the newly created payment info and select it.
            selectedPaymentInfoForSubscription = findCreatedPaymentInfoById(paymentInfo
                    .getId());
        } else {
            resetCachedPaymentInfo();
        }
        // reset page to edit
        paymentInfo = null;
        currentServiceKeyForPayment = null;

        return outcome;
    }
 
Example 54
Project: myfaces-trinidad   File: RegExpValidator.java   Source Code and License 5 votes vote down vote up
/**
 * @todo custom message should be evaluated lazily and then be used for
 * displaying message.
 */
private FacesMessage _getNoMatchFoundMessage(
  FacesContext context,
  UIComponent component,
  String value)
{
  Object noMatchMsgDet = _getRawNoMatchMessageDetail();
  Object label = ValidatorUtils.getComponentLabel(component);
  Object[] params = {label, value, getPattern()};

  FacesMessage msg =
      MessageFactory.getMessage(context, NO_MATCH_MESSAGE_ID,
                                noMatchMsgDet, params, label);
    return msg;
}
 
Example 55
Project: oscm   File: BillingBean.java   Source Code and License 5 votes vote down vote up
public void validateFromAndToDate(final FacesContext context,
        final UIComponent toValidate, final Object value) {
    validator.setToDate(toDate);
    validator.setFromDate(fromDate);
    try {
        validator.validate(context, toValidate, value);
    } catch (ValidatorException ex) {
        context.addMessage(
                toValidate.getClientId(context),
                new FacesMessage(FacesMessage.SEVERITY_ERROR, ex
                        .getLocalizedMessage(), null));
    }
}
 
Example 56
Project: NICON   File: Message.java   Source Code and License 5 votes vote down vote up
public static void addWarningMsg(String mensagem,String idFormulario, String idComponente)
{
    FacesContext facesContext = FacesContext.getCurrentInstance();
    FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, mensagem, mensagem);
    FacesContext  context = FacesContext.getCurrentInstance();
    context.addMessage(null, fm);  
    RequestContext.getCurrentInstance().update(idFormulario+":"+idComponente);
}
 
Example 57
Project: myfaces-trinidad   File: FacesMessageWrapper.java   Source Code and License 5 votes vote down vote up
/**
 * Reads this object from the serialized stream.
 * 
 * @param objectInput
 * @throws IOException
 * @throws ClassNotFoundException
 */
public void readExternal(ObjectInput objectInput)
  throws IOException, ClassNotFoundException
{
  Long version = objectInput.readLong();
  
  if(version != serialVersionUID)
  {
    throw new InvalidClassException("Classes are not compatible.  Received serialVersionUID = " + version + ", local serialVersionUID = "+ serialVersionUID);
  }

  _wrapped = (FacesMessage)objectInput.readObject();
  _label = objectInput.readObject();
}
 
Example 58
Project: myfaces-trinidad   File: MessageFactory.java   Source Code and License 5 votes vote down vote up
public BindingFacesMessage(FacesMessage.Severity severity,
                           ErrorMessages messageStrings,
                           Object label)
{
  super(severity, null, null, label);
  _messageStrings = messageStrings;
}
 
Example 59
Project: myfaces-trinidad   File: UIXEditableValueTemplate.java   Source Code and License 5 votes vote down vote up
private FacesMessage _getRequiredFacesMessage(FacesContext context)
{
  Object customMessageDetail = _getRequiredMessageDetail();
  FacesMessage message;
  Object label = _getLabel();

  // if message is null then a custom message was not set.
  message = MessageFactory.getMessage(context,
                                      getRequiredMessageKey(),
                                      customMessageDetail,
                                      new Object[]{label},
                                      label);
  return message;
}
 
Example 60
Project: oscm   File: SubscriptionWizardConversationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void selectService() {
    // given
    initDataForSelectService();
    doNothing().when(bean).addMessage(any(FacesMessage.Severity.class),
            anyString());
    // when
    String result = bean.selectService();
    // then
    assertEquals("", result);
}