@Override
  public Object getAsObject(FacesContext context, UIComponent component, String value) {

    if ((context == null) || (component == null)) {
      throw new NullPointerException();
    }

    if (value == null) {
      return null;
    }

    Integer obj = null;
    WidgetValues widgetValues = DojoServerFacesUtil.getWidgetValuesInstance(context, component);
    if (widgetValues != null) {
      obj = new Integer(widgetValues.getDisplayedValueIndex(value));
    }

    if ((Integer) obj == -1) {
      FacesMessage errMessage = new FacesMessage("Undefined value!");
      errMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ConverterException(errMessage);
    }

    return obj;
  }
  /*
   * (non-Javadoc)
   * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
   */
  @Override
  public void validate(FacesContext facesContext, UIComponent uiComponent, Object value)
      throws ValidatorException {
    UserList userList = (UserList) Component.getInstance("userList");
    String messageDetail = null;
    String messageSummary = null;

    String userName = value.toString();
    if (!isValid(userName)) {
      messageDetail = ResourceBundle.instance().getString("validator.email");
      messageSummary = ResourceBundle.instance().getString("validator.email");
    } else {
      Integer userId = userList.getUserIdForUsername(userName);
      if (userId != null) {
        messageDetail =
            ResourceBundle.instance()
                .getString("org.ideaproject.jsf.validator.USERNAME_TAKEN_detail");
        messageSummary =
            ResourceBundle.instance().getString("org.ideaproject.jsf.validator.USERNAME_TAKEN");
      }
    }

    if (messageDetail != null && messageSummary != null) {
      FacesMessage message = new FacesMessage();
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      message.setSummary(messageSummary);
      message.setDetail(messageDetail);
      throw new ValidatorException(message);
    }
  }
Example #3
0
  /**
   * Formats the value by inserting space after every four characters for better readability if they
   * don't already exist. In the process converts any <code>"-"</code> characters into blanks for
   * consistency.
   *
   * @param context the <code>FacesContext</code> of the current request
   * @param component the component associated with the value
   * @param value the value to convert
   * @return a formatted credit card number
   * @throws ConverterException if the value cannot be converted
   */
  public String getAsString(FacesContext context, UIComponent component, Object value)
      throws ConverterException {

    if (value == null) {
      return null;
    }
    // value must be of the type that can be cast to a String.
    String inputVal = null;
    try {
      inputVal = (String) value;
    } catch (ClassCastException ce) {
      FacesMessage errMsg = MessageFactory.getMessage(CONVERSION_ERROR_MESSAGE_ID, value, inputVal);
      throw new ConverterException(errMsg.getSummary());
    }

    // insert spaces after every four characters for better
    // readability if it doesn't already exist.
    char[] input = inputVal.toCharArray();
    StringBuilder buffer = new StringBuilder(50);
    for (int i = 0; i < input.length; ++i) {
      if ((i % 4) == 0 && i != 0) {
        if (input[i] != ' ' || input[i] != '-') {
          buffer.append(' ');
          // if there any "-"'s convert them to blanks.
        } else if (input[i] == '-') {
          buffer.append(' ');
        }
      }
      buffer.append(input[i]);
    }
    // System.out.println("Formatted value " + convertedValue);
    return buffer.toString();
  }
Example #4
0
 public boolean eliminar() {
   boolean ok = false;
   RequestContext context = RequestContext.getCurrentInstance();
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Aviso:", "eliminar: mbUpc");
   try {
     if (this.listaUpcs.size() > 2 && this.upc.isActual()) {
       fMsg.setSeverity(FacesMessage.SEVERITY_WARN);
       fMsg.setDetail("No se puede eliminar, cambie primero de actual");
     } else {
       this.dao = new DAOUpcs();
       this.dao.Eliminar(this.upc.getUpc());
       this.cargaListaUpcs();
       ok = true;
     }
   } catch (NamingException ex) {
     fMsg.setDetail(ex.getMessage());
   } catch (SQLException ex) {
     fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
   }
   if (!ok) {
     FacesContext.getCurrentInstance().addMessage(null, fMsg);
   }
   context.addCallbackParam("okUpc", ok);
   return ok;
 }
 /**
  * @param messageField
  * @param messageError
  */
 private void setErrorMessage(String messageField, String messageError) {
   FacesContext context = FacesContext.getCurrentInstance();
   FacesMessage message = new FacesMessage(messageError);
   message.setSeverity(FacesMessage.SEVERITY_ERROR);
   context.addMessage(messageField, message);
   setFormError(true);
 }
 @Override
 public void validate(FacesContext context, UIComponent component, Object value)
     throws ValidatorException {
   String email = value.toString();
   // Succeed early if the given email address is the same as the old one
   String old = (String) component.getAttributes().get("old");
   if (old != null && !old.isEmpty() && old.equals(email)) {
     return;
   }
   // Query database for an account with the given email address
   try {
     UserAccount account = UserAccountManager.findByEmail(email);
     if (account != null) {
       // Given email address is already in the database
       FacesMessage message =
           new FacesMessage(MessageProvider.getMessage("validatorEmailUniqueness"));
       message.setSeverity(FacesMessage.SEVERITY_ERROR);
       throw new ValidatorException(message);
     }
   } catch (UserAccountException e) {
     FacesMessage message = new FacesMessage(e.getMessage());
     message.setSeverity(FacesMessage.SEVERITY_ERROR);
     throw new ValidatorException(message);
   }
 }
Example #7
0
  public void validatePartialCredit(FacesContext context, UIComponent toValidate, Object value) {
    Integer pCredit = null;
    boolean isValid = true;
    if ("0.0".equals(value.toString())) {
      pCredit = 0;
    } else {
      try {
        pCredit = Integer.parseInt(value.toString());
      } catch (NumberFormatException e) {
        isValid = false;
      }
    }

    if (isValid && (pCredit == null || pCredit < 0 || pCredit > 99)) {
      isValid = false;
    }

    if (!isValid) {
      ((UIInput) toValidate).setValid(false);
      FacesMessage message = new FacesMessage();
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      String summary =
          ContextUtil.getLocalizedString(
              "org.sakaiproject.tool.assessment.bundle.AuthorMessages",
              "partial_credit_limit_summary");
      String detail =
          ContextUtil.getLocalizedString(
              "org.sakaiproject.tool.assessment.bundle.AuthorMessages",
              "partial_credit_limit_detail");
      message.setSummary(summary);
      message.setDetail(detail);
      context.addMessage(toValidate.getClientId(context), message);
    }
  }
  // Test validation of value against the valid list
  public void testValidation() throws Exception {

    // Put our component under test in a tree under a UIViewRoot
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    root.getChildren().add(component);

    // Add valid options to the component under test
    UISelectOne selectOne = (UISelectOne) component;
    selectOne.getChildren().add(new UISelectItemSub("foo", null, null));
    selectOne.getChildren().add(new UISelectItemSub("bar", null, null));
    selectOne.getChildren().add(new UISelectItemSub("baz", null, null));

    // Validate a value that is on the list
    selectOne.setValid(true);
    selectOne.setSubmittedValue("bar");
    selectOne.setRendererType(null); // We don't have any renderers
    selectOne.validate(facesContext);
    assertTrue(selectOne.isValid());

    // Validate a value that is not on the list
    selectOne.getAttributes().put("label", "mylabel");
    selectOne.setValid(true);
    selectOne.setSubmittedValue("bop");
    selectOne.validate(facesContext);
    assertTrue(!selectOne.isValid());
    Iterator messages = facesContext.getMessages();
    while (messages.hasNext()) {
      FacesMessage message = (FacesMessage) messages.next();
      assertTrue(message.getSummary().indexOf("mylabel") >= 0);
    }
  }
Example #9
0
 public void grabar() {
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso:", "");
   if (this.zona == null || this.zona.getIdZona() == 0) {
     fMsg.setDetail("Seleccione una zona !!");
   } else if (this.grupo == null || this.grupo.getIdGrupo() == 0) {
     fMsg.setDetail("Seleccione un grupo !!");
   } else if (this.detalle == null || this.detalle.getImpuesto().getIdImpuesto() == 0) {
     fMsg.setDetail("Seleccione un impuesto de la lista !!");
   } else {
     try {
       this.dao = new DAOImpuestosDetalle();
       this.detalles =
           this.dao.grabar(zona.getIdZona(), grupo.getIdGrupo(), this.detalle, this.periodo);
       fMsg.setSeverity(FacesMessage.SEVERITY_INFO);
       fMsg.setDetail("La operación se realizó con éxito !!");
     } catch (SQLException ex) {
       fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
       fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
     } catch (NamingException ex) {
       fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
       fMsg.setDetail(ex.getMessage());
     }
   }
   FacesContext.getCurrentInstance().addMessage(null, fMsg);
 }
Example #10
0
  /** @see FacesContext#addMessage(String, javax.faces.application.FacesMessage) */
  public void addMessage(String clientId, FacesMessage message) {
    assertNotReleased();
    // Validate our preconditions
    Util.notNull("message", message);

    if (maxSeverity == null) {
      maxSeverity = message.getSeverity();
    } else {
      Severity sev = message.getSeverity();
      if (sev.getOrdinal() > maxSeverity.getOrdinal()) {
        maxSeverity = sev;
      }
    }

    if (componentMessageLists == null) {
      componentMessageLists = new LinkedHashMap<String, List<FacesMessage>>();
    }

    // Add this message to our internal queue
    List<FacesMessage> list = componentMessageLists.get(clientId);
    if (list == null) {
      list = new ArrayList<FacesMessage>();
      componentMessageLists.put(clientId, list);
    }
    list.add(message);
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine(
          "Adding Message[sourceId="
              + (clientId != null ? clientId : "<<NONE>>")
              + ",summary="
              + message.getSummary()
              + ")");
    }
  }
 public String cadastrar() {
   produtoRep.cadastrar(produto);
   FacesMessage message = new FacesMessage("Produto cadastrado com sucesso!");
   message.setSeverity(FacesMessage.SEVERITY_INFO);
   FacesContext.getCurrentInstance().addMessage(null, message);
   return null;
 }
Example #12
0
  public void testTorrent(AjaxBehaviorEvent event) {
    // TODO Это точно такая же часть как и в testMessage
    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent component = UIComponent.getCurrentComponent(context);
    String url = (String) ((UIInput) component.findComponent("filmLinkRutracker")).getValue();

    WebBrowser webBrowser = new WebBrowser(LogEnum.WEB.getLog());
    //

    String regexp =
        (String) ((UIInput) component.findComponent("filmRegexpSerialNumber")).getValue();
    FacesMessage message = new FacesMessage();
    try {
      webBrowser.goToUrl(url);
      filmEdit.setTitle(webBrowser.getTitle());
      TorrentFile torrent = webBrowser.downloadTorrentFile(webBrowser.getTorrentUrl());
      ByteArrayInputStream bais = new ByteArrayInputStream(torrent.getContent());
      TorrentInfo info = new TorrentInfo(new BufferedInputStream(bais));
      StringBuilder builder = new StringBuilder();
      for (String fileName : info.getInfo()) {
        builder
            .append(fileName)
            .append(" № серии: \"")
            .append(MessageUtils.parseEpisode(fileName, regexp))
            .append("\"  ");
      }
      message.setSummary(builder.toString());
      message.setSeverity(FacesMessage.SEVERITY_INFO);
    } catch (CoreException e) {
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      message.setSummary(e.getMessage());
    }
    context.addMessage("otherMessageHidden", message);
    context.renderResponse();
  }
Example #13
0
  public void eliminarPeriodo() {
    FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso:", "");
    if (this.zona == null || this.zona.getIdZona() == 0) {
      fMsg.setDetail("Seleccione una zona !!");
    } else if (this.grupo == null || this.grupo.getIdGrupo() == 0) {
      fMsg.setDetail("Seleccione un grupo !!");
    } else if (this.periodo.equals("1")) {
      fMsg.setDetail("No se puede eliminar el período actual !!");
    } else {
      try {
        this.dao = new DAOImpuestosDetalle();
        this.dao.eliminarPeriodo(this.zona.getIdZona(), this.grupo.getIdGrupo());
        this.detalles = new ArrayList<ImpuestoDetalle>();
        this.detalle = null;

        fMsg.setSeverity(FacesMessage.SEVERITY_INFO);
        fMsg.setDetail("La operación se realizó con éxito !!");
      } catch (SQLException ex) {
        fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
        fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
      } catch (NamingException ex) {
        fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
        fMsg.setDetail(ex.getMessage());
      }
    }
    FacesContext.getCurrentInstance().addMessage(null, fMsg);
  }
Example #14
0
 public boolean agregar() {
   boolean ok = false;
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Aviso:", "agregar: mbUpc");
   //        RequestContext context = RequestContext.getCurrentInstance();
   try {
     if (this.upc.getUpc().equals("")) {
       fMsg.setSeverity(FacesMessage.SEVERITY_WARN);
       fMsg.setDetail("Se requiere un UPC !");
     } else {
       this.dao = new DAOUpcs();
       this.dao.agregar(this.upc);
       this.cargaListaUpcs();
       ok = true;
     }
   } catch (NamingException ex) {
     fMsg.setDetail(ex.getMessage());
   } catch (SQLException ex) {
     fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
   }
   if (!ok) {
     FacesContext.getCurrentInstance().addMessage(null, fMsg);
   }
   //        context.addCallbackParam("okUpc", ok);
   return ok;
 }
Example #15
0
 public void cargarDetalles(int idZona, int idGrupo) {
   boolean ok = false;
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso:", "");
   if (this.periodo == null) {
     this.periodo = "1";
   }
   try {
     if (idZona == 0 || idGrupo == 0) {
       this.detalles = new ArrayList<ImpuestoDetalle>();
     } else {
       this.dao = new DAOImpuestosDetalle();
       this.detalles = this.dao.obtenerDetalles(idZona, idGrupo, this.periodo);
     }
     ok = true;
   } catch (SQLException ex) {
     fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
     fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
   } catch (NamingException ex) {
     fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
     fMsg.setDetail(ex.getMessage());
   }
   if (!ok) {
     FacesContext.getCurrentInstance().addMessage(null, fMsg);
   }
 }
  /**
   * Encode the case when the <code>var</code> attribute is specified. This will render without any
   * HTML markup and put the current message in the request scope as identified by the <code>var
   * </code> attribute. Note: the iteration is by design completely stateless.
   *
   * @param context The involved faces context.
   * @param component The messages component.
   * @param messages The queued faces messages.
   * @throws IOException When an I/O error occurs.
   */
  protected void encodeMessagesRepeater(
      FacesContext context, OmniMessages component, List<FacesMessage> messages)
      throws IOException {
    String var = component.getVar();
    Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
    Object originalVar = requestMap.get(var);

    try {
      for (FacesMessage message : messages) {
        if (message.isRendered() && !component.isRedisplay()) {
          continue;
        }

        requestMap.put(var, message);

        for (UIComponent child : component.getChildren()) {
          child.encodeAll(context);
        }

        message.rendered();
      }
    } finally {
      if (originalVar != null) {
        requestMap.put(var, originalVar);
      } else {
        requestMap.remove(var);
      }
    }
  }
  public void warningValidator(FacesContext facesContext, UIComponent uiComponent, Object value)
      throws ValidatorException {

    FacesMessage facesMessage = new FacesMessage();
    facesMessage.setSeverity(FacesMessage.SEVERITY_WARN);
    facesMessage.setDetail("This is a warning message.");
    facesContext.addMessage(uiComponent.getClientId(), facesMessage);
  }
Example #18
0
 private void addMessage(String message, Severity severity, String componentId) {
   FacesMessage msg = new FacesMessage();
   msg.setDetail(message);
   msg.setSeverity(severity);
   UIComponent uic = getComponent(componentId, FacesContext.getCurrentInstance().getViewRoot());
   FacesContext.getCurrentInstance()
       .addMessage(uic.getClientId(FacesContext.getCurrentInstance()), msg);
 }
 /**
  * Add keyed error/message.
  *
  * @param level
  * @param key message key
  */
 private void addError(FacesContext context, String key) {
   FacesMessage fMessage = MessageFactory.getMessage(key);
   if (fMessage != null) {
     FacesContext facesContext = FacesContext.getCurrentInstance();
     fMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
     facesContext.addMessage(null, fMessage);
   }
 }
 private BridgeMessage convertToBridgeMsg(FacesMessage message) {
   BridgeMessage bridgeMsg = new BridgeMessage();
   bridgeMsg.detail = message.getDetail();
   bridgeMsg.summary = message.getSummary();
   bridgeMsg.rendered = message.isRendered();
   bridgeMsg.severityOrdinal = message.getSeverity().getOrdinal();
   return bridgeMsg;
 }
 public String showMessage(UIComponent component, String messageText) {
   FacesMessage fm = new FacesMessage(messageText);
   /** set the type of the message. Valid types: error, fatal,info,warning */
   fm.setSeverity(FacesMessage.SEVERITY_ERROR);
   FacesContext context = FacesContext.getCurrentInstance();
   // departmentName is the binding property for our field.
   context.addMessage(component.getClientId(context), fm);
   return null;
 }
  public void validateWidgetValidatorAttr(FacesContext context, UIComponent component, Object value)
      throws ValidatorException {

    if (ValidatorUtil.validateObjectHasOnlyValue(value, this.widgetValues.getFirst())) return;

    FacesMessage message = new FacesMessage("Value must have 'a'");
    message.setSeverity(FacesMessage.SEVERITY_ERROR);
    throw new ValidatorException(message);
  }
  /**
   * Throws messages in the context.
   *
   * @param key
   * @param severity
   */
  public static void setMessage(String clientID, String summary, String key, Severity severity) {

    FacesMessage message = new FacesMessage(summary, message(key));
    message.setSeverity(severity);

    FacesContext fc = FacesContext.getCurrentInstance();

    fc.addMessage(clientID, message);
  }
  @Override
  protected Object[] getJsValidatorParametersAsString(FacesContext context, UIComponent component) {
    Object[] args = {component.getId()};
    FacesMessage message =
        MessageUtil.getMessage(
            context, FacesMessage.SEVERITY_ERROR, UIInput.REQUIRED_MESSAGE_ID, args);

    return new String[] {message.getSummary(), message.getDetail()};
  }
Example #25
0
  @Override
  public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException {

    if (!validaCNPJ(String.valueOf(o))) {
      FacesMessage message = new FacesMessage();
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      message.setSummary("CNPJ inválido!");
      throw new ValidatorException(message);
    }
  }
Example #26
0
 public static void addErrorMessage(
     FacesContext context, UIComponent component, String message, Object[] params) {
   String bundleName = context.getApplication().getMessageBundle();
   Locale locale = context.getViewRoot().getLocale();
   message =
       I18NUtils.getMessageString(bundleName, message, evaluateParams(context, params), locale);
   FacesMessage msg = new FacesMessage(message);
   msg.setSeverity(FacesMessage.SEVERITY_ERROR);
   context.addMessage(component.getClientId(context), msg);
 }
 private static boolean isInvalid(FacesContext facesContext, String clientId) {
   Iterator<FacesMessage> messages = facesContext.getMessages(clientId);
   while (messages.hasNext()) {
     FacesMessage message = messages.next();
     if (message.getSeverity().getOrdinal() > FacesMessage.SEVERITY_INFO.getOrdinal()) {
       return true;
     }
   }
   return false;
 }
  @Observer("org.jboss.seam.validationFailed")
  public void observeFailedValidation() {
    log.info("validation of JSF component failed");
    Iterator<FacesMessage> it = FacesContext.getCurrentInstance().getMessages();

    while (it.hasNext()) {
      FacesMessage fm = it.next();
      log.info("Found FacesMessage: #0 #1 #2", fm.getSeverity(), fm.getSummary(), fm.getDetail());
    }
  }
 @Override
 public void validate(FacesContext ctx, UIComponent cmpt, Object valor) throws ValidatorException {
   if (!validaCPF(String.valueOf(valor))) {
     FacesMessage message = new FacesMessage();
     message.setDetail("Por favor digite um CPF válido!");
     message.setSummary("Por favor digite um CPF válido!");
     message.setSeverity(FacesMessage.SEVERITY_ERROR);
     throw new ValidatorException(message);
   }
 }
Example #30
0
 public String isKundeValid() { // TODO Methodenname??
   kunde = dao.findKunde(tempUsername, tempPassword);
   if (kunde.getKundenNummer() != -1) {
     return "showKunde"; // TODO Navigationrules
   }
   FacesMessage msg = new FacesMessage("Username und/oder Passort falsch!");
   msg.setSeverity(FacesMessage.SEVERITY_INFO);
   FacesContext.getCurrentInstance().addMessage("msgout", msg);
   return "noKunde";
 }