Exemplo n.º 1
0
  private void encodeSeverityMessages(
      FacesContext facesContext,
      UIComponent component,
      UIMessages uiMessages,
      Severity severity,
      List<FacesMessage> messages)
      throws IOException {
    ResponseWriter writer = facesContext.getResponseWriter();

    String alertSeverityClass = "";

    if (FacesMessage.SEVERITY_INFO.equals(severity)) {
      alertSeverityClass = "alert-info";
    } else if (FacesMessage.SEVERITY_WARN.equals(severity)) {
      alertSeverityClass = ""; // Default alert is a warning
    } else if (FacesMessage.SEVERITY_ERROR.equals(severity)) {
      alertSeverityClass = "alert-error";
    } else if (FacesMessage.SEVERITY_FATAL.equals(severity)) {
      alertSeverityClass = "alert-error";
    }

    writer.startElement("div", null);
    writer.writeAttribute("class", "alert " + alertSeverityClass, "alert " + alertSeverityClass);
    writer.startElement("a", component);
    writer.writeAttribute("class", "close", "class");
    writer.writeAttribute("data-dismiss", "alert", "data-dismiss");
    writer.writeAttribute("href", "#", "href");
    writer.write("&times;");
    writer.endElement("a");

    writer.startElement("ul", null);

    for (FacesMessage msg : messages) {
      String summary = msg.getSummary() != null ? msg.getSummary() : "";
      String detail = msg.getDetail() != null ? msg.getDetail() : summary;

      writer.startElement("li", component);

      if (uiMessages.isShowSummary()) {
        writer.startElement("strong", component);
        writer.writeText(summary, component, null);
        writer.endElement("strong");
      }

      if (uiMessages.isShowDetail()) {
        writer.writeText(" " + detail, null);
      }

      writer.endElement("li");
      msg.rendered();
    }
    writer.endElement("ul");
    writer.endElement("div");
  }
Exemplo n.º 2
0
  // 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);
    }
  }
Exemplo n.º 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();
  }
Exemplo n.º 4
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()
              + ")");
    }
  }
 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;
 }
Exemplo n.º 6
0
  private void logMessage(FacesMessage message) {

    final StringBuilder msgBuilder = new StringBuilder("Message='");
    msgBuilder.append(message.getSummary());
    msgBuilder.append("'");

    log4j(message, msgBuilder);
  }
  @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()};
  }
  @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());
    }
  }
Exemplo n.º 9
0
  private void logMessages(FacesContext context) {
    UIViewRoot root = context.getViewRoot();
    String viewId = "";

    if (root != null) viewId = root.getViewId();

    Iterator<FacesMessage> iter = context.getMessages();

    while (iter != null && iter.hasNext()) {
      FacesMessage msg = iter.next();

      if (log.isLoggable(Level.FINE)) {
        if (msg.getDetail() != null)
          log.fine(
              viewId + " [ " + msg.getSeverity() + "] " + msg.getSummary() + " " + msg.getDetail());
        else log.fine(viewId + " [ " + msg.getSeverity() + "] " + msg.getSummary());
      }
    }
  }
Exemplo n.º 10
0
  private void logMessage(String clientId, FacesMessage message) {

    final StringBuilder msgBuilder = new StringBuilder("Message for component '");
    msgBuilder.append(clientId);
    msgBuilder.append("' = '");
    msgBuilder.append(message.getSummary());
    msgBuilder.append("'");

    log4j(message, msgBuilder);
  }
Exemplo n.º 11
0
 public AppFacesException(String messageCode, Object[] args, Throwable cause) {
   super(cause);
   final FacesContext context = FacesContext.getCurrentInstance();
   final FacesMessage facesMessage = FacesMessageUtil.getMessage(context, messageCode, args);
   String message = facesMessage.getDetail();
   if (message == null) {
     message = facesMessage.getSummary();
   }
   this.messageCode = messageCode;
   this.args = args;
   this.message = message;
   this.facesMessage = facesMessage;
 }
Exemplo n.º 12
0
  /**
   * Tratamento para verificar se a mensagem já foi inserida no contexto do JSF
   *
   * @param msg
   * @param facesMessage
   */
  @SuppressWarnings("rawtypes")
  private void addMensagemDistinct(String msg, FacesMessage facesMessage) {
    boolean mensagemNova = true;
    for (Iterator iterator = facesContext.getMessages(); iterator.hasNext(); ) {
      FacesMessage message = (FacesMessage) iterator.next();

      if (message.getSummary().equals(msg)) {
        mensagemNova = false;
        break;
      }
    }

    // Só permite a inclusão da mensagem no contexto do JSF uma vez.
    if (mensagemNova) {
      facesContext.addMessage(null, facesMessage);
    }
  }
Exemplo n.º 13
0
  private void printMessagesAssociatedWithComponents(FacesContext context) {

    final Iterator<String> clientsWithMessages = context.getClientIdsWithMessages();
    while (clientsWithMessages.hasNext()) {

      String clientId = clientsWithMessages.next();

      final Iterator<FacesMessage> messages = context.getMessages(clientId);
      while (messages.hasNext()) {
        final FacesMessage facesMessage = messages.next();
        logMessage(clientId, facesMessage);

        facesMessage.setSummary(
            facesMessage.getSummary() + "  -- tagged by " + this.getClass().getSimpleName());
      }
    }
  }
Exemplo n.º 14
0
  /**
   * Encode a single faces message.
   *
   * @param context The involved faces context.
   * @param component The messages component.
   * @param message The queued faces message.
   * @param table Whether to render the messages as a HTML table or a HTML list.
   * @param showSummary Whether to show summary.
   * @param showDetail Whether to show detail.
   * @param escape Whether to HTML-escape message.
   * @param tooltip Whether to show tooltip.
   * @throws IOException When an I/O error occurs.
   */
  protected void encodeMessage(
      FacesContext context,
      OmniMessages component,
      FacesMessage message,
      boolean table,
      boolean showSummary,
      boolean showDetail,
      boolean escape,
      boolean tooltip)
      throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    writer.startElement(table ? "tr" : "li", component);
    String severityName = SEVERITY_NAMES.get(message.getSeverity());
    writeAttribute(writer, component, severityName + "Style", "style");
    writeAttribute(writer, component, severityName + "Class", "class", "styleClass");

    if (table) {
      writer.startElement("td", component);
    }

    String summary = coalesce(message.getSummary(), "");
    String detail = coalesce(message.getDetail(), summary);

    if (tooltip) {
      writeAttribute(writer, "title", detail);
    }

    if (showSummary) {
      writeText(writer, component, summary, escape);

      if (showDetail) {
        writer.write(" ");
      }
    }

    if (showDetail) {
      writeText(writer, component, detail, escape);
    }

    if (table) {
      writer.endElement("td");
    }

    writer.endElement(table ? "tr" : "li");
  }
 private static void replaceIdWithLabel(
     String clientId, FacesMessage message, FacesContext facesContext) {
   UIComponent label = findLabelFor(facesContext.getViewRoot(), clientId);
   if (label != null) {
     int idx = clientId.lastIndexOf(':');
     if (idx >= 0) {
       clientId = clientId.substring(idx + 1);
     }
     log.debug("Replacing ID with Label for: " + clientId);
     String text = (String) label.getAttributes().get("value");
     String detail = message.getDetail();
     String summary = message.getSummary();
     message.setSummary(summary.replaceAll(clientId, text));
     message.setDetail(detail.replaceAll(clientId, text));
   } else {
     log.debug("Unabled to find a label for ID: " + clientId);
   }
 }
 @Override
 protected void writeErrorSummaryRow(
     FacesContext context, ResponseWriter w, FormLayout c, FacesMessage m) throws IOException {
   w.startElement("h2", c); // $NON-NLS-1$
   String style = (String) getProperty(PROP_ERRORSUMMARYITEMSTYLE);
   if (StringUtil.isNotEmpty(style)) {
     w.writeAttribute("style", style, null); // $NON-NLS-1$
   }
   String cls = (String) getProperty(PROP_ERRORSUMMARYITEMCLASS);
   if (StringUtil.isNotEmpty(cls)) {
     w.writeAttribute("class", cls, null); // $NON-NLS-1$
   }
   String title = null;
   if (StringUtil.isNotEmpty(title)) {
     w.startElement("strong", c); // $NON-NLS-1$
     w.writeText(title, null);
     w.endElement("strong"); // $NON-NLS-1$
   }
   String text = m.getSummary();
   w.writeText(text, null);
   w.endElement("h2"); // $NON-NLS-1$
 }
Exemplo n.º 17
0
  /**
   * populate the argument component with values, being sensitive to the possible multi-nature of
   * the values, and to the type of the values.
   *
   * @param context the <code>FacesContext</code> for the current request
   * @param component the <code>UIComponent</code> to populate
   * @param componentType the component type
   * @param value the value
   * @param valueType the value type
   */
  private void populateComponentWithValue(
      FacesContext context,
      UIComponent component,
      String componentType,
      String value,
      String valueType) {
    Application application = context.getApplication();
    Converter converter = null;

    // if we need a converter, and can have a converter
    if (!"java.lang.String".equals(valueType) && component instanceof ValueHolder) {
      // if so create it,
      try {
        converter = application.createConverter(CarStore.loadClass(valueType, this));
        // add it to our component,
        ((ValueHolder) component).setConverter(converter);
      } catch (ClassNotFoundException cne) {
        FacesMessage errMsg = MessageFactory.getMessage(CONVERTER_ERROR_MESSAGE_ID, valueType);
        throw new IllegalStateException(errMsg.getSummary());
      }
    }

    // if this component is a SelectOne or SelectMany, take special action
    if (isMultiValue(componentType)) {
      // create a UISelectItems instance
      UISelectItems items = new UISelectItems();
      items.setValue(parseStringIntoArrayList(value, converter));
      // add it to the component
      component.getChildren().add(items);
    } else {
      // we have a single value
      if (null != converter) {
        component.getAttributes().put("value", converter.getAsObject(context, component, value));
      } else {
        component.getAttributes().put("value", value);
      }
    }
  }
 private static void appendMessagesForClientId(
     FacesContext facesContext, String clientId, StringBuffer jsTxt) {
   Iterator<FacesMessage> messages = facesContext.getMessages(clientId);
   boolean replaceIds = isReplaceId(facesContext);
   while (messages.hasNext()) {
     FacesMessage message = messages.next();
     if (clientId == null) {
       jsTxt.append("\n{severity:'");
     } else {
       if (replaceIds) {
         replaceIdWithLabel(clientId, message, facesContext);
       }
       jsTxt.append("\n{clientId:'");
       jsTxt.append(clientId);
       jsTxt.append("', severity:'");
     }
     jsTxt.append(message.getSeverity());
     jsTxt.append("', summary:'");
     jsTxt.append(message.getSummary());
     jsTxt.append("', detail:'");
     jsTxt.append(message.getDetail());
     jsTxt.append("'},");
   }
 }
Exemplo n.º 19
0
 public String getSummary() {
   return message.getSummary();
 }
Exemplo n.º 20
0
  public void execute(FacesContext facesContext) throws FacesException {

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Entering RenderResponsePhase");
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("About to render view " + facesContext.getViewRoot().getViewId());
    }
    // For requests intended to produce a partial response, we need prohibit
    // writing any content outside of the view itself (f:view).
    if (facesContext.isAjaxRequest()) {
      facesContext.enableResponseWriting(false);
    }

    try {
      // Setup message display LOGGER.
      if (LOGGER.isLoggable(Level.INFO)) {
        Iterator<String> clientIdIter = facesContext.getClientIdsWithMessages();

        // If Messages are queued
        if (clientIdIter.hasNext()) {
          Set<String> clientIds = new HashSet<String>();

          // Copy client ids to set of clientIds pending display.
          while (clientIdIter.hasNext()) {
            clientIds.add(clientIdIter.next());
          }
          RequestStateManager.set(
              facesContext, RequestStateManager.CLIENT_ID_MESSAGES_NOT_DISPLAYED, clientIds);
        }
      }

      // render the view
      facesContext
          .getApplication()
          .getViewHandler()
          .renderView(facesContext, facesContext.getViewRoot());

      // display results of message display LOGGER
      if (LOGGER.isLoggable(Level.INFO)
          && RequestStateManager.containsKey(
              facesContext, RequestStateManager.CLIENT_ID_MESSAGES_NOT_DISPLAYED)) {

        // remove so Set does not get modified when displaying messages.
        Set<String> clientIds =
            TypedCollections.dynamicallyCastSet(
                (Set)
                    RequestStateManager.remove(
                        facesContext, RequestStateManager.CLIENT_ID_MESSAGES_NOT_DISPLAYED),
                String.class);
        if (!clientIds.isEmpty()) {

          // Display each message possibly not displayed.
          StringBuilder builder = new StringBuilder();
          for (String clientId : clientIds) {
            Iterator<FacesMessage> messages = facesContext.getMessages(clientId);
            while (messages.hasNext()) {
              FacesMessage message = messages.next();
              builder.append("\n");
              builder.append("sourceId=").append(clientId);
              builder.append("[severity=(").append(message.getSeverity());
              builder.append("), summary=(").append(message.getSummary());
              builder.append("), detail=(").append(message.getDetail()).append(")]");
            }
          }
          LOGGER.log(Level.INFO, "jsf.non_displayed_message", builder.toString());
        }
      }
    } catch (IOException e) {
      throw new FacesException(e.getMessage(), e);
    }

    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.log(
          Level.FINEST,
          "+=+=+=+=+=+= View structure printout for " + facesContext.getViewRoot().getViewId());
      DebugUtil.printTree(facesContext.getViewRoot(), LOGGER, Level.FINEST);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Exiting RenderResponsePhase");
    }
  }
  @SuppressWarnings("unchecked")
  public void restoreState(FacesContext facesContext) {

    logger.debug("restoreState(facesContext)");

    boolean restoreNonExcludedRequestAttributes =
        ((beganInPhase == Bridge.PortletPhase.ACTION_PHASE)
            || (beganInPhase == Bridge.PortletPhase.EVENT_PHASE)
            || (beganInPhase == Bridge.PortletPhase.RESOURCE_PHASE));

    BridgeContext bridgeContext = BridgeContext.getCurrentInstance();

    PortletPhase portletRequestPhase = bridgeContext.getPortletRequestPhase();

    if (portletRequestPhase == Bridge.PortletPhase.RENDER_PHASE) {

      if (!portletMode.equals(bridgeContext.getPortletRequest().getPortletMode())) {
        setPortletModeChanged(true);
        restoreNonExcludedRequestAttributes = false;
      }
    }

    if ((beganInPhase == Bridge.PortletPhase.ACTION_PHASE)
        || (beganInPhase == Bridge.PortletPhase.EVENT_PHASE)
        || (beganInPhase == Bridge.PortletPhase.RESOURCE_PHASE)) {

      // Restore the view root that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      UIViewRoot uiViewRoot = (UIViewRoot) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_VIEW_ROOT);

      if (uiViewRoot != null) {
        facesContext.setViewRoot(uiViewRoot);
        logger.debug("Restored viewId=[{0}] uiViewRoot=[{1}]", uiViewRoot.getViewId(), uiViewRoot);
      } else {
        logger.debug("Did not restore uiViewRoot");
      }

      // Restore the faces messages that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      List<FacesMessageWrapper> facesMessages =
          (List<FacesMessageWrapper>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_MESSAGES);

      boolean restoredFacesMessages = false;

      if (facesMessages != null) {

        for (FacesMessageWrapper facesMessageWrapper : facesMessages) {
          String clientId = facesMessageWrapper.getClientId();
          FacesMessage facesMessage = facesMessageWrapper.getFacesMessage();
          facesContext.addMessage(clientId, facesMessage);
          logger.trace("Restored facesMessage=[{0}]", facesMessage.getSummary());
          restoredFacesMessages = true;
        }
      }

      if (restoredFacesMessages) {
        logger.debug("Restored facesMessages");
      } else {
        logger.debug("Did not restore any facesMessages");
      }

      // NOTE: PROPOSE-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-203
      // Restore the
      // FacesContext attributes that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      restoreJSF2FacesContextAttributes(facesContext);
    }

    if (restoreNonExcludedRequestAttributes) {

      // Restore the non-excluded request attributes.
      List<RequestAttribute> savedRequestAttributes =
          (List<RequestAttribute>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_REQUEST_ATTRIBUTES);

      boolean restoredNonExcludedRequestAttributes = false;

      if (savedRequestAttributes != null) {
        Map<String, Object> currentRequestAttributes =
            facesContext.getExternalContext().getRequestMap();

        // If a redirect did not occur, then restore the non-excluded request attributes.
        if (!isRedirectOccurred()) {

          for (RequestAttribute requestAttribute : savedRequestAttributes) {
            String name = requestAttribute.getName();
            Object value = requestAttribute.getValue();
            logger.trace(
                "Restoring non-excluded request attribute name=[{0}] value=[{1}]", name, value);
            currentRequestAttributes.put(name, value);
            restoredNonExcludedRequestAttributes = true;
          }
        }
      }

      if (restoredNonExcludedRequestAttributes) {
        logger.debug("Restored non-excluded request attributes");
      } else {
        logger.debug("Did not restore any non-excluded request attributes");
      }
    }

    // If running in the RENDER_PHASE, then the Flash scope must be restored.
    if (portletRequestPhase == Bridge.PortletPhase.RENDER_PHASE) {

      // NOTE: PROPOSED-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-201
      // Restore the flash scope.
      restoreFlashState(facesContext);
    }

    // If running in the RENDER_PHASE, then the incongruity context must be restored.
    if (((beganInPhase == Bridge.PortletPhase.ACTION_PHASE)
            || (beganInPhase == Bridge.PortletPhase.EVENT_PHASE))
        && (portletRequestPhase == Bridge.PortletPhase.RENDER_PHASE)) {

      List<IncongruityAttribute> savedIncongruityAttributes =
          (List<IncongruityAttribute>)
              getAttribute(BRIDGE_REQ_SCOPE_ATTR_INCONGRUITY_CONTEXT_ATTRIBUTES);

      if (savedIncongruityAttributes != null) {

        IncongruityContext incongruityContext = bridgeContext.getIncongruityContext();
        Map<String, Object> incongruityContextAttributes = incongruityContext.getAttributes();

        for (IncongruityAttribute incongruityAttribute : savedIncongruityAttributes) {
          String key = incongruityAttribute.getName();
          Object value = incongruityAttribute.getValue();
          incongruityContextAttributes.put(key, value);
        }
      }
    }
  }
Exemplo n.º 22
0
  private void updateModel(int newPage) {

    FacesContext facesContext = getFacesContext();
    UIComponent dataTable = getDataTable();

    if (isRendered(dataTable)) {
      dataTable.getAttributes().put("first", (newPage - 1) * getRows(dataTable));
    }

    Map<String, Object> attributes = dataTable.getAttributes();
    attributes.put(dataTable.getClientId(facesContext) + SCROLLER_STATE_ATTRIBUTE, newPage);

    ValueExpression ve = getValueExpression("page");
    if (ve != null) {
      try {
        ve.setValue(facesContext.getELContext(), newPage);
        attributes.remove(dataTable.getClientId(facesContext) + SCROLLER_STATE_ATTRIBUTE);
      } catch (ELException e) {
        String messageStr = e.getMessage();
        Throwable result = e.getCause();
        while (null != result && result.getClass().isAssignableFrom(ELException.class)) {
          messageStr = result.getMessage();
          result = result.getCause();
        }
        FacesMessage message;
        if (null == messageStr) {
          message =
              ServiceTracker.getService(MessageFactory.class)
                  .createMessage(
                      facesContext,
                      FacesMessages.UIINPUT_UPDATE,
                      MessageUtil.getLabel(facesContext, this));
        } else {
          message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageStr, messageStr);
        }
        facesContext.getExternalContext().log(message.getSummary(), result);
        facesContext.addMessage(getClientId(facesContext), message);
        facesContext.renderResponse();
      } catch (IllegalArgumentException e) {
        FacesMessage message =
            ServiceTracker.getService(MessageFactory.class)
                .createMessage(
                    facesContext,
                    FacesMessages.UIINPUT_UPDATE,
                    MessageUtil.getLabel(facesContext, this));
        facesContext.getExternalContext().log(message.getSummary(), e);
        facesContext.addMessage(getClientId(facesContext), message);
        facesContext.renderResponse();
      } catch (Exception e) {
        FacesMessage message =
            ServiceTracker.getService(MessageFactory.class)
                .createMessage(
                    facesContext,
                    FacesMessages.UIINPUT_UPDATE,
                    MessageUtil.getLabel(facesContext, this));
        facesContext.getExternalContext().log(message.getSummary(), e);
        facesContext.addMessage(getClientId(facesContext), message);
        facesContext.renderResponse();
      }
    }
  }
Exemplo n.º 23
0
  private void encodeSeverityMessages(
      FacesContext facesContext, Growl uiGrowl, String severity, List<FacesMessage> messages)
      throws IOException {
    ResponseWriter writer = facesContext.getResponseWriter();

    for (FacesMessage msg : messages) {
      String summary = msg.getSummary() != null ? msg.getSummary() : "";
      String detail = msg.getDetail() != null ? msg.getDetail() : summary;
      if (uiGrowl.isEscape()) {
        summary = BsfUtils.escapeHtml(summary);
        detail = BsfUtils.escapeHtml(detail);
      }
      summary = summary.replace("'", "\\\'");
      detail = detail.replace("'", "\\\'");
      // Decode messageType to map bootstrap alert styles
      String messageType = "success";
      if ("info".equals(severity)) {
        messageType = "info";
      } else if ("warn".equals(severity)) {
        messageType = "warning";
      } else if ("error".equals(severity)) {
        messageType = "danger";
      } else if ("fatal".equals(severity)) {
        messageType = "danger";
      }

      String icon =
          uiGrowl.getIcon() != null
              ? "glyphicon glyphicon-" + uiGrowl.getIcon()
              : "glyphicon glyphicon-warning-sign";

      String from = BsfUtils.StringOrDefault(uiGrowl.getPlacementFrom(), "top");
      String align = BsfUtils.StringOrDefault(uiGrowl.getPlacementAlign(), "right");

      writer.writeText(
          ""
              + " 	$.notify({"
              + " 		title: '"
              + (uiGrowl.isShowSummary() ? summary : "")
              + "', "
              + " 		message: '"
              + (uiGrowl.isShowDetail() ? detail : "")
              + "', "
              + " 		icon: '"
              + icon
              + "'"
              + " 	}, {"
              + " 		position: null, "
              + " 		type: '"
              + messageType
              + "', "
              + "		allow_dismiss: "
              + uiGrowl.isAllowDismiss()
              + ", "
              + "		newest_on_top: "
              + uiGrowl.isNewestOnTop()
              + ", "
              + "       delay: "
              + uiGrowl.getDelay()
              + ", "
              + "       timer: "
              + uiGrowl.getTimer()
              + ", "
              + " 		placement: { "
              + "			from: '"
              + from
              + "',"
              + "			align: '"
              + align
              + "'"
              + " 		}, "
              + "		animate: { "
              + "			enter: 'animated fadeInDown', "
              + "			exit: 'animated fadeOutUp' "
              + "		} "
              + "   }); "
              + "",
          null);
    }
  }
Exemplo n.º 24
0
  @Override
  public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
    rendererParamsNotNull(context, component);

    if (!shouldEncode(component)) {
      return;
    }

    UIMessages messages = (UIMessages) component;
    ResponseWriter writer = context.getResponseWriter();
    assert (writer != null);

    // String clientId = ((UIMessages) component).getFor();
    String clientId = null; // PENDING - "for" is actually gone now
    // if no clientId was included
    if (clientId == null) {
      // and the author explicitly only wants global messages
      if (messages.isGlobalOnly()) {
        // make it so only global messages get displayed.
        clientId = "";
      }
    }

    // "for" attribute optional for Messages
    Iterator messageIter = getMessageIter(context, clientId, component);

    assert (messageIter != null);

    if (!messageIter.hasNext()) {
      return;
    }

    boolean showSummary = messages.isShowSummary();
    boolean showDetail = messages.isShowDetail();

    while (messageIter.hasNext()) {
      FacesMessage curMessage = (FacesMessage) messageIter.next();

      // make sure we have a non-null value for summary and
      // detail.
      String summary = (null != (summary = curMessage.getSummary())) ? summary : "";
      // Default to summary if we have no detail
      String detail = (null != (detail = curMessage.getDetail())) ? detail : summary;

      String severityStyleClass = null;
      String errorType = "default";
      long timeout = 5;
      if (curMessage.getSeverity() == FacesMessage.SEVERITY_INFO) {
        severityStyleClass = (String) component.getAttributes().get("infoClass");
        errorType = "info";
      } else if (curMessage.getSeverity() == FacesMessage.SEVERITY_WARN) {
        severityStyleClass = (String) component.getAttributes().get("warnClass");
        errorType = "warn";
      } else if (curMessage.getSeverity() == FacesMessage.SEVERITY_ERROR) {
        severityStyleClass = (String) component.getAttributes().get("errorClass");
        errorType = "error";
        timeout = 0;
      } else if (curMessage.getSeverity() == FacesMessage.SEVERITY_FATAL) {
        severityStyleClass = (String) component.getAttributes().get("fatalClass");
        errorType = "fatal";
        timeout = 0;
      }

      if (Framework.getProperty("org.nuxeo.ecm.tester.name") != null) {
        timeout = 0;
      }

      writer.startElement("script", messages);
      writer.writeAttribute("type", "text/javascript", null);

      String scriptContent =
          "jQuery(document).ready(function() {\n"
              + "  jQuery.ambiance({\n"
              + "    "
              + "message: \"%s\",\n"
              + "    title: \"%s\",\n"
              + "    type: \"%s\",\n"
              + "    className: \"%s\",\n"
              + "    timeout: \"%d\""
              + "  })\n"
              + "});\n";
      String formattedScriptContent;
      if (showDetail) {
        formattedScriptContent =
            String.format(scriptContent, detail, summary, errorType, severityStyleClass, timeout);
      } else {
        formattedScriptContent =
            String.format(scriptContent, "", summary, errorType, severityStyleClass, timeout);
      }
      writer.writeText(formattedScriptContent, null);
      writer.endElement("script");
    }
  }
  /**
   * Restores the state of the FacesContext as required by section 5.1.2 of the JSR 329 spec. This
   * method is designed to be called during the RENDER_PHASE of the portlet lifecycle.
   *
   * @param facesContext The current faces context.
   * @return Flag indicating whether or not a restoration took place.
   */
  @SuppressWarnings("unchecked")
  public boolean restoreScopedData(FacesContext facesContext) {

    if (beganInActionOrEventRequest) {

      // Restore the view root that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      UIViewRoot uiViewRoot = (UIViewRoot) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_VIEW_ROOT);

      if (uiViewRoot != null) {
        facesContext.setViewRoot(uiViewRoot);
        logger.debug("Restored viewId=[{0}] uiViewRoot=[{1}]", uiViewRoot.getViewId(), uiViewRoot);
      } else {
        logger.debug("Did not restore uiViewRoot");
      }

      // Restore the faces messages that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      List<FacesMessageWrapper> facesMessages =
          (List<FacesMessageWrapper>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_MESSAGES);

      boolean restoredFacesMessages = false;

      if (facesMessages != null) {

        for (FacesMessageWrapper facesMessageWrapper : facesMessages) {
          String clientId = facesMessageWrapper.getClientId();
          FacesMessage facesMessage = facesMessageWrapper.getFacesMessage();
          facesContext.addMessage(clientId, facesMessage);
          logger.trace("Restored facesMessage=[{0}]", facesMessage.getSummary());
          restoredFacesMessages = true;
        }
      }

      if (restoredFacesMessages) {
        logger.debug("Restored facesMessages");
      } else {
        logger.debug("Did not restore any facesMessages");
      }

      // Restore the non-excluded request attributes.
      List<RequestAttribute> savedRequestAttributes =
          (List<RequestAttribute>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_REQUEST_ATTRIBUTES);

      boolean restoredNonExcludedRequestAttributes = false;

      if (savedRequestAttributes != null) {
        Map<String, Object> currentRequestAttributes =
            facesContext.getExternalContext().getRequestMap();

        for (RequestAttribute requestAttribute : savedRequestAttributes) {
          String name = requestAttribute.getName();
          Object value = requestAttribute.getValue();
          logger.trace(
              "Restoring non-excluded request attribute name=[{0}] value=[{1}]", name, value);
          currentRequestAttributes.put(name, value);
          restoredNonExcludedRequestAttributes = true;
        }
      }

      if (restoredNonExcludedRequestAttributes) {
        logger.debug("Restored non-excluded request attributes");
      } else {
        logger.debug("Did not restore any non-excluded request attributes");
      }

      // NOTE: PROPOSE-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-203
      // Restore the
      // FacesContext attributes that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      List<FacesContextAttribute> savedFacesContextAttributes =
          (List<FacesContextAttribute>)
              getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_CONTEXT_ATTRIBUTES);

      boolean restoredFacesContextAttibutes = false;

      if (savedFacesContextAttributes != null) {
        Map<Object, Object> currentFacesContextAttributes = facesContext.getAttributes();

        for (FacesContextAttribute facesContextAttribute : savedFacesContextAttributes) {
          Object name = facesContextAttribute.getName();

          // Note: Don't want to restore the BridgeContext because that would be invalid data -- it
          // would
          // contain the ActionRequest/ActionResponse or EventRequest/EventResponse and would
          // overwrite the
          // current RenderRequest/RenderResponse.
          if (!BridgeExt.BRIDGE_CONTEXT_ATTRIBUTE.equals(name)) {
            Object value = facesContextAttribute.getValue();
            logger.trace("Restoring FacesContext attribute name=[{0}] value=[{1}]", name, value);
            currentFacesContextAttributes.put(name, value);
            restoredFacesContextAttibutes = true;
          }
        }
      }

      if (restoredFacesContextAttibutes) {
        logger.debug("Restored FacesContext attributes");
      } else {
        logger.debug("Did not restore any FacesContext attributes");
      }

      return true;
    } else {
      return false;
    }
  }
Exemplo n.º 26
0
 public Object getValue() {
   Object value = super.getValue();
   if (value instanceof SelectItem[] || value instanceof SelectItem) {
     return value;
   }
   List list = new ArrayList();
   boolean nullLabelSet = false;
   if (nullLabelRequired) {
     SelectItem si = new SelectItem();
     si.setValue("");
     final FacesContext context = getFacesContext();
     FacesMessage mes = FacesMessageUtil.getMessage(context, NULL_LABEL_MESSAGE_CODE, null);
     si.setLabel(mes.getSummary());
     list.add(si);
     nullLabelSet = true;
   }
   if (value != null && value.getClass().isArray()) {
     value = Arrays.asList((Object[]) value);
   }
   if (value instanceof Collection) {
     final Collection valueCollection = (Collection) value;
     if (!nullLabelSet && valueCollection.size() == 0) {
       list.add(BLANK_SELECT_ITEM);
     } else {
       for (Iterator it = valueCollection.iterator(); it.hasNext(); ) {
         Object item = it.next();
         if (item instanceof SelectItem) {
           list.add(item);
         } else if (item instanceof Map) {
           Map map = (Map) item;
           SelectItem si = new SelectItem();
           Object itemValueValue = map.get(itemValue);
           if (itemValueValue != null) {
             si.setValue(itemValueValue);
           }
           Object itemLabelValue = map.get(itemLabel);
           if (itemLabelValue == null) {
             itemLabelValue = itemValueValue;
           }
           if (itemLabelValue != null) {
             si.setLabel(itemLabelValue.toString());
           }
           list.add(si);
         } else {
           SelectItem si = new SelectItem();
           BeanDesc bd = BeanDescFactory.getBeanDesc(item.getClass());
           PropertyDesc pd = bd.getPropertyDesc(itemValue);
           Object itemValueValue = (pd.isReadable()) ? pd.getValue(item) : null;
           if (itemValueValue != null) {
             si.setValue(itemValueValue);
           }
           Object itemLabelValue = null;
           if (bd.hasPropertyDesc(itemLabel)) {
             pd = bd.getPropertyDesc(itemLabel);
             itemLabelValue = (pd.isReadable()) ? pd.getValue(item) : null;
           }
           if (itemLabelValue == null) {
             itemLabelValue = itemValueValue;
           }
           if (itemLabelValue != null) {
             si.setLabel(itemLabelValue.toString());
           }
           list.add(si);
         }
       }
     }
   } else if (value instanceof Map) {
     final Map map = (Map) value;
     if (!nullLabelSet && map.size() == 0) {
       list.add(BLANK_SELECT_ITEM);
     } else {
       for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
         Object key = it.next();
         Object val = map.get(key);
         SelectItem si = new SelectItem();
         if (key != null) {
           si.setLabel(key.toString());
         }
         if (val != null) {
           si.setValue(val);
         }
         list.add(si);
       }
     }
   } else {
     if (!nullLabelSet && value == null) {
       list.add(BLANK_SELECT_ITEM);
     }
   }
   return list;
 }
Exemplo n.º 27
0
 public Message(FacesMessage msg) {
   this.severity = msg.getSeverity().getOrdinal();
   this.summary = msg.getSummary();
   this.detail = msg.getDetail();
 }