Exemple #1
2
  protected void assignUniqueId(FaceletContext ctx, UIComponent parent, String id, UIComponent c) {

    // If the id is specified as a literal, and the component is being
    // repeated (by c:forEach, for example), use generated unique ids
    // after the first instance
    if (this.id != null && !(this.id.isLiteral() && ComponentSupport.getNeedUniqueIds(ctx))) {
      c.setId(this.id.getValue(ctx));
    } else {
      UIViewRoot root = ComponentSupport.getViewRoot(ctx, parent);
      if (root != null) {
        String uid;
        IdMapper mapper = IdMapper.getMapper(ctx.getFacesContext());
        String mid = ((mapper != null) ? mapper.getAliasedId(id) : id);
        UIComponent ancestorNamingContainer = parent.getNamingContainer();
        if (null != ancestorNamingContainer && ancestorNamingContainer instanceof UniqueIdVendor) {
          uid =
              ((UniqueIdVendor) ancestorNamingContainer).createUniqueId(ctx.getFacesContext(), mid);
        } else {
          uid = root.createUniqueId(ctx.getFacesContext(), mid);
        }
        c.setId(uid);
      }
    }

    if (this.rendererType != null) {
      c.setRendererType(this.rendererType);
    }
  }
Exemple #2
0
 public void applyMetadata(FaceletContext ctx, Object instance) {
   UIComponent c = (UIComponent) instance;
   c.setValueExpression(
       "value",
       attr.getValueExpression(
           ctx, ((c instanceof UISelectBoolean) ? Boolean.class : Object.class)));
 }
  /**
   * Collect all messages associated with components identified by <code>for</code> attribute and
   * return it. An empty list will be returned when there are no messages.
   *
   * @param context The involved faces context.
   * @param component The messages component.
   * @return All messages associated with components identified by <code>for</code> attribute.
   */
  protected List<FacesMessage> getMessages(FacesContext context, OmniMessages component) {
    String forClientIds = component.getFor();

    if (forClientIds == null) {
      return component.isGlobalOnly() ? context.getMessageList(null) : context.getMessageList();
    }

    List<FacesMessage> messages = new ArrayList<>();

    for (String forClientId : forClientIds.split("\\s+")) {
      UIComponent forComponent = component.findComponent(forClientId);

      if (forComponent == null) {
        continue;
      }

      messages.addAll(context.getMessageList(forComponent.getClientId(context)));

      if (!(forComponent instanceof UIInput)) {
        for (UIInput child : findComponentsInChildren(forComponent, UIInput.class)) {
          messages.addAll(context.getMessageList(child.getClientId(context)));
        }
      }
    }

    return messages;
  }
  /** If page >= 1 then it's a page number to show */
  @Attribute
  public int getPage() {

    UIComponent dataTable = getDataTable();
    Map<String, Object> attributes = dataTable.getAttributes();

    FacesContext facesContext = getFacesContext();
    Integer state =
        (Integer) attributes.get(dataTable.getClientId(facesContext) + SCROLLER_STATE_ATTRIBUTE);

    if (state != null) {
      return state;
    }

    if (this.page != null) {
      return page;
    }

    ValueExpression ve = getValueExpression("page");
    if (ve != null) {
      try {
        Integer pageObject = (Integer) ve.getValue(getFacesContext().getELContext());

        if (pageObject != null) {
          return pageObject;
        }
      } catch (ELException e) {
        throw new FacesException(e);
      }
    }

    return 1;
  }
  @Override
  protected void doDecode(FacesContext context, UIComponent component) {

    Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();

    AbstractPanelMenuItem menuItem = (AbstractPanelMenuItem) component;
    String compClientId = component.getClientId(context);
    if (requestMap.get(compClientId) != null) {
      AbstractPanelMenu pm = getParentPanelMenu(menuItem);

      if (pm.isImmediate()) {
        menuItem.setImmediate(true);
      }
      new ActionEvent(menuItem).queue();

      if (context.getPartialViewContext().isPartialRequest()) {

        // TODO nick - why render item by default?
        context.getPartialViewContext().getRenderIds().add(component.getClientId(context));

        // TODO nick - this should be done on encode, not on decode
        addOnCompleteParam(context, component.getClientId(context));
      }
    }
  }
  protected Iterator<MessageForRender> getMessages(
      FacesContext context, String forClientId, UIComponent component) {

    Iterator<MessageForRender> msgIter;

    if (forClientId != null) {

      if (forClientId.length() != 0) {

        UIComponent result = RendererUtils.getInstance().findComponentFor(component, forClientId);
        if (result == null) {
          msgIter = Iterators.emptyIterator();
        } else {
          String clientId = result.getClientId(context);
          msgIter = getMessagesForId(context, clientId);
        }
      } else {
        msgIter = getMessagesForId(context, null);
      }
    } else {
      msgIter = Iterators.emptyIterator();
      Iterator<String> clientIdsWithMessages = context.getClientIdsWithMessages();
      while (clientIdsWithMessages.hasNext()) {
        String clientId = (String) clientIdsWithMessages.next();
        msgIter = Iterators.concat(msgIter, getMessagesForId(context, clientId));
      }
    }

    return msgIter;
  }
  public void encodeBegin(FacesContext context, UIComponent component) throws IOException {

    if (!component.isRendered()) {
      return;
    }

    ResponseWriter writer = context.getResponseWriter();
    String jsfId = (String) RendererUtil.getAttribute(context, component, "id");
    String id = jsfId;

    if (component.getId() != null && !component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
      id = component.getClientId(context);
    }

    String title = (String) RendererUtil.getAttribute(context, component, "title");
    Object tmpFoldStr = RendererUtil.getAttribute(context, component, "hideByDefault");
    String key = (String) RendererUtil.getAttribute(context, component, "key");

    writer.write("<fieldset>");
    writer.write("<legend>");
    writer.write(
        "<a role='button' data-toggle='collapse' aria-expanded='true' aria-target='"
            + id
            + "' href='#"
            + id
            + "' data-target=\"[id='"
            + id
            + "']\">"
            + title
            + "</a>");
    writer.write("</legend>");

    writer.write("<div class='collapse in' " + " id=\"" + id + "\">");
  }
  @Override
  protected void doEncodeBegin(ResponseWriter writer, FacesContext context, UIComponent component)
      throws IOException {
    AbstractTooltip tooltip = (AbstractTooltip) component;

    writer.startElement(getMarkupElement(tooltip), component);
    writer.writeAttribute(ID_ATTRIBUTE, component.getClientId(context), "clientId");

    writer.writeAttribute(HtmlConstants.STYLE_ATTRIBUTE, "display: none;", null);
    writer.startElement(getMarkupElement(tooltip), component);
    writer.writeAttribute(ID_ATTRIBUTE, component.getClientId(context) + ":wrp", null);
    writer.writeAttribute(CLASS_ATTRIBUTE, getStyleClass(component), null);

    int zindex = tooltip.getZindex();
    if (zindex == Integer.MIN_VALUE) {
      zindex = DEFAULT_ZINDEX_VALUE;
    }

    String style = concatStyles("z-index:" + zindex, getStyle(component));
    if (style != null && style.trim().length() > 0) {
      writer.writeAttribute(HtmlConstants.STYLE_ATTRIBUTE, style, null);
    }

    renderPassThroughAttributes(context, component, getPassThroughAttributes());

    writer.startElement(getMarkupElement(tooltip), component);
    writer.writeAttribute(ID_ATTRIBUTE, component.getClientId(context) + ":cntr", null);
    writer.writeAttribute(CLASS_ATTRIBUTE, "rf-tt-cntr", null);

    if (tooltip.getMode() == TooltipMode.ajax) {
      encodeLoading(writer, context, tooltip);
    }

    encodeContentBegin(writer, context, tooltip);
  }
Exemple #9
0
  /**
   * This handler is used for the navigation nodes that request content from an external URL. This
   * handler pulls the "real url" from from the component specified by the <code>compId</code>
   * parameter (this necessarily depends on the presence of the navigation container in the view for
   * the component look up to work). Once the component has been found, the url is retrieved from
   * the attribute map, and its contents retrieved. If <code>processPage</code> is true, the URL
   * contents are interpretted and the resulting component(s) are added to the component tree (This
   * feature is not currently supported).. Otherwise, the contents are returned in the output
   * parameter <code>pluginPage</code> to be output as-is on the page.
   *
   * @param handlerCtx The <code>HandlerContext</code>.
   */
  @Handler(
      id = "retrievePluginPageContents",
      input = {@HandlerInput(name = "compId", type = String.class, required = true)},
      output = {@HandlerOutput(name = "pluginPage", type = String.class)})
  public static void retrievePluginPageContents(HandlerContext handlerCtx) {
    String id = (String) handlerCtx.getInputValue("compId");
    UIComponent comp = handlerCtx.getFacesContext().getViewRoot().findComponent(id);
    String urlContents = "";
    if (comp != null) {
      String url = (String) comp.getAttributes().get(NavigationNodeFactory.REAL_URL);
      try {
        // Read from the URL...
        URL contentUrl = FileUtil.searchForFile(url, null);
        if (contentUrl == null) {
          throw new IOException("Unable to locate file: " + url);
        }
        urlContents = new String(FileUtil.readFromURL(contentUrl));

        // FIXME: Implement processPage support
        /*
        if (processPage) {
            // probably do something like what includeIntegrations does
            ...
        }
        */
      } catch (IOException ex) {
        Logger.getLogger(PluginHandlers.class.getName())
            .log(Level.SEVERE, "Unable to read url: " + url, ex);
      }
    }

    // Set the content to output...
    handlerCtx.setOutputValue("pluginPage", urlContents);
  }
  @SuppressWarnings("unchecked")
  public UIComponent generate(FacesContext context, String id) {
    UIComponent component = this.createOutputTextComponent(context, id);
    component.getAttributes().put("escape", Boolean.FALSE);

    return component;
  }
  public void encodeClientScript(
      ResponseWriter writer, FacesContext facesContext, UIDataTableBase component)
      throws IOException {
    AbstractCollapsibleSubTable subTable = (AbstractCollapsibleSubTable) component;

    String id = subTable.getClientId(facesContext);

    UIComponent nestingForm = getUtils().getNestingForm(subTable);
    String formId = nestingForm != null ? nestingForm.getClientId(facesContext) : "";

    Map<String, Object> options = new HashMap<String, Object>();
    options.put("stateInput", subTable.getClientId(facesContext) + STATE);
    options.put("optionsInput", subTable.getClientId(facesContext) + OPTIONS);
    options.put("expandMode", subTable.getExpandMode());
    options.put("eventOptions", AjaxRendererUtils.buildEventOptions(facesContext, subTable));

    JSFunction jsFunction = new JSFunction("new RichFaces.ui.CollapsibleSubTable");
    jsFunction.addParameter(id);
    jsFunction.addParameter(formId);
    jsFunction.addParameter(options);

    writer.startElement(HtmlConstants.SCRIPT_ELEM, subTable);
    writer.writeAttribute(HtmlConstants.TYPE_ATTR, HtmlConstants.JAVASCRIPT_TYPE, null);
    writer.writeText(jsFunction.toScript(), null);
    writer.endElement(HtmlConstants.SCRIPT_ELEM);
  }
 public void encodeChildren(FacesContext facesContext, UIComponent uiComponent)
     throws IOException {
   validateParameters(facesContext, uiComponent, null);
   DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent);
   Element root = (Element) domContext.getRootNode();
   DOMContext.removeChildren(root);
   PanelSeries list = (PanelSeries) uiComponent;
   UISeries uiList = (UISeries) uiComponent;
   int rowIndex = uiList.getFirst();
   uiList.setRowIndex(rowIndex);
   int numberOfRowsToDisplay = uiList.getRows();
   int countOfRowsDisplayed = 0;
   while (uiList.isRowAvailable()) {
     if ((numberOfRowsToDisplay > 0) && (countOfRowsDisplayed >= numberOfRowsToDisplay)) {
       break;
     }
     Iterator childs;
     childs = list.getChildren().iterator();
     while (childs.hasNext()) {
       UIComponent nextChild = (UIComponent) childs.next();
       if (nextChild.isRendered()) {
         domContext.setCursorParent(root);
         domContext.streamWrite(facesContext, uiComponent, domContext.getRootNode(), root);
         encodeParentAndChildren(facesContext, nextChild);
       }
     }
     rowIndex++;
     countOfRowsDisplayed++;
     uiList.setRowIndex(rowIndex);
   }
   uiList.setRowIndex(-1);
 }
  /**
   * Recursively searches for {@link NamingContainer}s from the given start point looking for the
   * component with the <code>id</code> specified by <code>forComponent</code>.
   *
   * @param startPoint - the starting point in which to begin the search
   * @param forComponent - the component to search for
   * @return the component with the the <code>id</code that matches
   *         <code>
   *     forComponent</code> otheriwse null if no match is found.
   */
  private static UIComponent findUIComponentBelow(UIComponent startPoint, String forComponent) {

    UIComponent retComp = null;
    if (startPoint.getChildCount() > 0) {
      List<UIComponent> children = startPoint.getChildren();
      for (int i = 0, size = children.size(); i < size; i++) {
        UIComponent comp = children.get(i);

        if (comp instanceof NamingContainer) {
          try {
            retComp = comp.findComponent(forComponent);
          } catch (IllegalArgumentException iae) {
            continue;
          }
        }

        if (retComp == null) {
          if (comp.getChildCount() > 0) {
            retComp = findUIComponentBelow(comp, forComponent);
          }
        }

        if (retComp != null) {
          break;
        }
      }
    }
    return retComp;
  }
  /**
   * Collections parameters for use with Behavior script rendering. Similar to getParamList(), but
   * returns a collection of ClientBehaviorContext.Parameter instances.
   *
   * @param command the command which may have parameters
   * @return a collection of ClientBehaviorContext.Parameter instances.
   */
  protected Collection<ClientBehaviorContext.Parameter> getBehaviorParameters(UIComponent command) {

    ArrayList<ClientBehaviorContext.Parameter> params = null;
    int childCount = command.getChildCount();

    if (childCount > 0) {

      for (UIComponent kid : command.getChildren()) {
        if (kid instanceof UIParameter) {
          UIParameter uiParam = (UIParameter) kid;
          String name = uiParam.getName();
          Object value = uiParam.getValue();

          if ((name != null) && (name.length() > 0)) {

            if (params == null) {
              params = new ArrayList<>(childCount);
            }

            params.add(new ClientBehaviorContext.Parameter(name, value));
          }
        }
      }
    }

    return (params == null) ? Collections.<ClientBehaviorContext.Parameter>emptyList() : params;
  }
  protected Iterator getMessageIter(
      FacesContext context, String forComponent, UIComponent component) {

    Iterator messageIter;
    // Attempt to use the "for" attribute to locate
    // messages.  Three possible scenarios here:
    // 1. valid "for" attribute - messages returned
    //    for valid component identified by "for" expression.
    // 2. zero length "for" expression - global errors
    //    not associated with any component returned
    // 3. no "for" expression - all messages returned.
    if (null != forComponent) {
      if (forComponent.length() == 0) {
        messageIter = context.getMessages(null);
      } else {
        UIComponent result = getForComponent(context, forComponent, component);
        if (result == null) {
          messageIter = Collections.EMPTY_LIST.iterator();
        } else {
          messageIter = context.getMessages(result.getClientId(context));
        }
      }
    } else {
      messageIter = context.getMessages();
    }
    return messageIter;
  }
 @Override
 public Object getAsObject(FacesContext context, UIComponent component, String value) {
   Messages.addInfo(component.getClientId(context), "Converter currently used: {0}", this);
   Messages.addInfo(component.getClientId(context), "EJB injected in converter: {0}", ejb);
   Messages.addInfo(component.getClientId(context), "CDI injected in converter: {0}", cdi);
   return value;
 }
  protected void encodeProgressStateProlog(
      FacesContext context, UIComponent component, ProgressBarState currentState)
      throws IOException {

    ResponseWriter responseWriter = context.getResponseWriter();
    responseWriter.startElement(HtmlConstants.DIV_ELEM, component);
    responseWriter.writeAttribute(
        HtmlConstants.ID_ATTRIBUTE, component.getClientId(context) + ".rmng", null);
    responseWriter.writeAttribute(
        HtmlConstants.CLASS_ATTRIBUTE,
        HtmlUtil.concatClasses("rf-pb-rmng", component.getAttributes().get("remainingClass")),
        null);

    responseWriter.writeAttribute(
        HtmlConstants.STYLE_ATTRIBUTE,
        getContentStyle(currentState == ProgressBarState.progressState),
        null);

    responseWriter.startElement(HtmlConstants.DIV_ELEM, component);
    responseWriter.writeAttribute(
        HtmlConstants.CLASS_ATTRIBUTE,
        HtmlUtil.concatClasses("rf-pb-prgs", component.getAttributes().get("progressClass")),
        null);
    responseWriter.writeAttribute(
        HtmlConstants.ID_ATTRIBUTE, component.getClientId(context) + ".prgs", null);
    responseWriter.writeAttribute(
        HtmlConstants.STYLE_ATTRIBUTE, "width: " + getWidth(component) + "%", null);
    responseWriter.endElement(HtmlConstants.DIV_ELEM);
  }
  public void encodeEnd(FacesContext context, UIComponent component) throws IOException {

    if ((context == null) || (component == null)) {
      throw new NullPointerException(
          Util.getExceptionMessageString(Util.NULL_PARAMETERS_ERROR_MESSAGE_ID));
    }
    if (!component.isRendered()) {
      if (log.isTraceEnabled()) {
        log.trace(
            "No encoding necessary "
                + component.getId()
                + " since "
                + "rendered attribute is set to false ");
      }
      return;
    }
    UIData data = (UIData) component;
    data.setRowIndex(-1);
    ResponseWriter writer = context.getResponseWriter();

    // Render the ending of this table
    writer.endElement("table");
    writer.writeText("\n", null);
    if (log.isTraceEnabled()) {
      log.trace("End encoding component " + component.getId());
    }
  }
 protected void resetComponent(UIComponent comp, boolean recursive) {
   if (comp == null) {
     return;
   }
   if (comp instanceof ResettableComponent) {
     ((ResettableComponent) comp).resetCachedModel();
   } else {
     if (comp instanceof EditableValueHolder) {
       // reset submitted value
       ((EditableValueHolder) comp).setSubmittedValue(null);
     }
     if (comp instanceof ValueHolder) {
       // reset local value, only if there's a value expression
       // binding
       ValueExpression ve = comp.getValueExpression("value");
       if (ve != null) {
         ValueHolder vo = (ValueHolder) comp;
         vo.setValue(null);
         if (comp instanceof EditableValueHolder) {
           ((EditableValueHolder) comp).setLocalValueSet(false);
         }
       }
     }
   }
   if (recursive) {
     List<UIComponent> children = comp.getChildren();
     if (children != null && !children.isEmpty()) {
       for (UIComponent child : children) {
         resetComponent(child, recursive);
       }
     }
   }
 }
  protected void encodeToolbarGroups(FacesContext context, Toolbar toolbar) throws IOException {
    ResponseWriter writer = context.getResponseWriter();

    for (UIComponent child : toolbar.getChildren()) {
      if (child.isRendered() && child instanceof ToolbarGroup) {
        ToolbarGroup group = (ToolbarGroup) child;

        String defaultGroupClass = "ui-toolbar-group-" + group.getAlign();
        String groupClass = group.getStyleClass();
        String groupStyle = group.getStyle();
        groupClass = groupClass == null ? defaultGroupClass : defaultGroupClass + " " + groupClass;

        writer.startElement("div", null);
        writer.writeAttribute("class", groupClass, null);
        if (groupStyle != null) {
          writer.writeAttribute("style", groupStyle, null);
        }

        for (UIComponent groupChild : group.getChildren()) {
          if (groupChild instanceof UISeparator && groupChild.isRendered())
            encodeSeparator(context, (UISeparator) groupChild);
          else groupChild.encodeAll(context);
        }

        writer.endElement("div");
      }
    }
  }
 protected void encodeScript(FacesContext facesContext, UIComponent component) throws IOException {
   JavaScriptService javaScriptService = ServiceTracker.getService(JavaScriptService.class);
   JSFunction messageObject = new JSObject(getJSClassName(), component.getClientId(facesContext));
   Map<String, Object> attributes = component.getAttributes();
   Builder<String, Object> parametersBuilder = ImmutableMap.builder();
   String forId = (String) attributes.get("for");
   RendererUtils rendererUtils = RendererUtils.getInstance();
   if (!Strings.isNullOrEmpty(forId)) {
     UIComponent target = rendererUtils.findComponentFor(component, forId);
     if (null != target) {
       parametersBuilder.put("forComponentId", target.getClientId(facesContext));
     }
   }
   Severity level = getLevel(component);
   if (FacesMessage.SEVERITY_INFO != level) {
     parametersBuilder.put("level", level.getOrdinal());
   }
   if (!rendererUtils.isBooleanAttribute(component, "showSummary")) {
     parametersBuilder.put("showSummary", false);
   }
   if (rendererUtils.isBooleanAttribute(component, "showDetail")) {
     parametersBuilder.put("showDetail", true);
   }
   if (rendererUtils.isBooleanAttribute(component, "tooltip")) {
     parametersBuilder.put("tooltip", true);
   }
   if (isComponentMessages(component)) {
     parametersBuilder.put("isMessages", true);
   }
   messageObject.addParameter(parametersBuilder.build());
   // RendererUtils.getInstance().writeScript(facesContext, component, messageObject);
   javaScriptService.addPageReadyScript(facesContext, messageObject);
 }
 /**
  * finds the component with the given id that is located in the same NamingContainer as a given
  * component
  *
  * @param fc the FacesContext
  * @param componentId the component id
  * @param nearComponent a component within the same naming container from which to start the
  *     search (optional)
  * @return the component or null if no component was found
  */
 public UIComponent findComponent(FacesContext fc, String componentId, UIComponent nearComponent) {
   if (StringUtils.isEmpty(componentId))
     throw new InvalidArgumentException("componentId", componentId);
   // Begin search near given component (if any)
   UIComponent component = null;
   if (nearComponent != null) { // Search below the nearest naming container
     component = nearComponent.findComponent(componentId);
     if (component == null) { // Recurse upwards
       UIComponent nextParent = nearComponent;
       while (true) {
         nextParent = nextParent.getParent();
         // search NamingContainers only
         while (nextParent != null && !(nextParent instanceof NamingContainer)) {
           nextParent = nextParent.getParent();
         }
         if (nextParent == null) {
           break;
         } else {
           component = nextParent.findComponent(componentId);
         }
         if (component != null) {
           break;
         }
       }
     }
   }
   // Not found. Search the entire tree
   if (component == null) component = findChildComponent(fc.getViewRoot(), componentId);
   // done
   return component;
 }
  /**
   * This method returns any facets that should be applied to the <code>TreeNode (comp)</code>.
   * Useful facets for the sun <code>TreeNode</code> component are: "content" and "image".
   *
   * <p>Facets that already exist on <code>comp</code>, or facets that are directly added to <code>
   * comp</code> do not need to be returned from this method.
   *
   * <p>This implementation directly adds a "content" facet and returns <code>null</code> from this
   * method.
   *
   * @param comp The tree node <code>UIComponent</code>.
   * @param nodeObject The (model) object representing the tree node.
   */
  public Map<String, UIComponent> getFacets(UIComponent comp, Object nodeObject) {
    if (nodeObject == null) {
      return null;
    }
    if (nodeObject.toString().equals(_objectName)) {
      return null;
    }
    Properties props = new Properties();
    LayoutComponent desc = this.getLayoutComponent();

    // Check to see if a childActionListener was added
    // NOTE: This is not needed when a "command" event is used.  In the
    //	 case of a CommandEvent an ActionListener will be
    //	 automatically registered by the ComponentFactoryBase class
    //	 during "setOptions()".  Also, setting a childActionListener
    //	 here should not stop "command" handlers from being invoked.
    setProperty(props, "actionListener", desc.getOption("childActionListener"));

    // Also se the target and text...
    setProperty(props, "target", desc.getOption("childTarget"));
    setProperty(props, "text", comp.getAttributes().get("text"));
    // FIXME: Add support for other hyperlink properties??

    // Create Hyperlink
    // NOTE: Last attribute "content" will be the facet named used.
    UIComponent link =
        ComponentUtil.getChild(
            comp,
            "link",
            "com.sun.jsftemplating.component.factory.sun.HyperlinkFactory",
            props,
            "content");

    // Check to see if we have a childURL, evalute it here (after component
    // is created, before rendered) so we can use the link itself to define
    // the URL.  This has proven to be useful...
    Object val = desc.getOption("childURL");
    if (val != null) {
      link.getAttributes()
          .put("url", desc.resolveValue(FacesContext.getCurrentInstance(), link, val));
    }

    // Set href's handlers...
    // We do it this way rather than earlier b/c the factory will not
    // recognize this as a property, it requires it to be defined in the
    // LayoutComponent as a handler.  So we must do this manually like
    // this.
    List handlers = desc.getHandlers("childCommand");
    if (handlers != null) {
      link.getAttributes().put("command", handlers);
      // This adds the required action listener to proces the commands
      // This is needed here b/c the factory has already executed -- the
      // factory is normally the place where this is added (iff there is
      // at least one command handler).
      ((ActionSource) link).addActionListener(CommandActionListener.getInstance());
    }

    // We already added the facet, return null...
    return null;
  }
Exemple #24
0
  public void validateCaptcha(FacesContext context, UIComponent toValidate, Object value) {

    if (c != null) {
      Map map = context.getExternalContext().getRequestParameterMap();
      String challenge = map.get("recaptcha_challenge_field").toString();
      String response = map.get("recaptcha_response_field").toString();
      HttpServletRequest req =
          (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
      ReCaptchaResponse resp = r.checkAnswer(req.getRemoteAddr(), challenge, response);
      if (!resp.isValid() || hasValidationErrors) {
        Logger.getLogger(ContactUsPage.class.getName())
            .info("INVALID RESPONSE: " + resp.getErrorMessage());
        ((UIInput) toValidate).setValid(false);
        if (hasValidationErrors) {
          context.addMessage(
              toValidate.getClientId(context),
              new FacesMessage(
                  "Some required information was entered incorrectly. Please press refresh below to get a new challenge, then correct the issue."));
          hasValidationErrors = false;
        } else {
          context.addMessage(
              toValidate.getClientId(context),
              new FacesMessage("Press refresh below to get a new challenge."));
          hasValidationErrors = false;
        }
      }
    }
  }
  protected void encodeColumnFooter(FacesContext context, DataTable table, UIColumn column)
      throws IOException {
    if (!column.isRendered()) {
      return;
    }

    ResponseWriter writer = context.getResponseWriter();

    String style = column.getStyle();
    String styleClass = column.getStyleClass();
    styleClass =
        styleClass == null
            ? DataTable.COLUMN_FOOTER_CLASS
            : DataTable.COLUMN_FOOTER_CLASS + " " + styleClass;

    writer.startElement("td", null);
    writer.writeAttribute("class", styleClass, null);

    if (style != null) writer.writeAttribute("style", style, null);
    if (column.getRowspan() != 1) writer.writeAttribute("rowspan", column.getRowspan(), null);
    if (column.getColspan() != 1) writer.writeAttribute("colspan", column.getColspan(), null);

    // Footer content
    UIComponent facet = column.getFacet("footer");
    String text = column.getFooterText();
    if (facet != null) {
      facet.encodeAll(context);
    } else if (text != null) {
      writer.write(text);
    }

    writer.endElement("td");
  }
  /**
   * Render any "passthru" attributes, where we simply just output the raw name and value of the
   * attribute. This method is aware of the set of HTML4 attributes that fall into this bucket.
   * Examples are all the javascript attributes, alt, rows, cols, etc.
   *
   * @param writer writer the {@link javax.faces.context.ResponseWriter} to be used when writing the
   *     attributes
   * @param component the component
   * @param attributes an array off attributes to be processed
   * @throws IOException if an error occurs writing the attributes
   */
  public static void renderPassThruAttributes(
      ResponseWriter writer, UIComponent component, String[] attributes) throws IOException {

    assert (null != writer);
    assert (null != component);

    Map<String, Object> attrMap = component.getAttributes();

    // PENDING - think anyone would run the RI using another implementation
    // of the jsf-api?  If they did, then this would fall apart.  That
    // scenario seems extremely unlikely.
    if (canBeOptimized(component)) {
      //noinspection unchecked
      List<String> setAttributes =
          (List<String>) component.getAttributes().get(ATTRIBUTES_THAT_ARE_SET_KEY);
      if (setAttributes != null) {
        renderPassThruAttributesOptimized(writer, component, attributes, setAttributes);
      }
    } else {
      // this block should only be hit by custom components leveraging
      // the RI's rendering code.  We make no assumptions and loop through
      // all known attributes.
      boolean isXhtml = RIConstants.XHTML_CONTENT_TYPE.equals(writer.getContentType());
      for (String attrName : attributes) {

        Object value = attrMap.get(attrName);
        if (value != null && shouldRenderAttribute(value)) {
          writer.writeAttribute(prefixAttribute(attrName, isXhtml), value, attrName);
        }
      }
    }
  }
  public void testWidgetProcessor() throws Exception {

    CssStyleProcessor processor = new CssStyleProcessor();

    // Pass through

    HtmlMetawidget metawidget = new HtmlMetawidget();
    UIComponent component = new HtmlInputText();
    assertEquals(component, processor.processWidget(component, PROPERTY, null, metawidget));
    assertEquals(null, component.getAttributes().get("style"));
    assertEquals(null, component.getAttributes().get("styleClass"));

    // Simple styles and styleClasses

    metawidget.setStyle("foo1");
    metawidget.setStyleClass("bar1");
    assertEquals(component, processor.processWidget(component, PROPERTY, null, metawidget));
    assertEquals("foo1", component.getAttributes().get("style"));
    assertEquals("bar1", component.getAttributes().get("styleClass"));

    // Compound styles and styleClasses

    metawidget.setStyle("foo2");
    metawidget.setStyleClass("bar2");
    assertEquals(component, processor.processWidget(component, PROPERTY, null, metawidget));
    assertEquals("foo1 foo2", component.getAttributes().get("style"));
    assertEquals("bar1 bar2", component.getAttributes().get("styleClass"));
  }
 protected ToolComponent findParentTool(ComponentWrapper parent) {
   UIComponent parentComponent = parent.getComponent();
   while (!(parentComponent instanceof ToolComponent) && parentComponent != null) {
     parentComponent = parentComponent.getParent();
   }
   return (ToolComponent) parentComponent;
 }
  /**
   * 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);
      }
    }
  }
  /** Find all parameters to include by looking at nested uiparams and params of navigation case */
  protected static Map<String, List<String>> getParams(NavigationCase navCase, Button button) {
    Map<String, List<String>> params = new LinkedHashMap<String, List<String>>();

    // UIParams
    for (UIComponent child : button.getChildren()) {
      if (child.isRendered() && (child instanceof UIParameter)) {
        UIParameter uiParam = (UIParameter) child;

        if (!uiParam.isDisable()) {
          List<String> paramValues = params.get(uiParam.getName());
          if (paramValues == null) {
            paramValues = new ArrayList<String>();
            params.put(uiParam.getName(), paramValues);
          }

          paramValues.add(String.valueOf(uiParam.getValue()));
        }
      }
    }

    // NavCase Params
    Map<String, List<String>> navCaseParams = navCase.getParameters();
    if (navCaseParams != null && !navCaseParams.isEmpty()) {
      for (Map.Entry<String, List<String>> entry : navCaseParams.entrySet()) {
        String key = entry.getKey();

        // UIParams take precedence
        if (!params.containsKey(key)) {
          params.put(key, entry.getValue());
        }
      }
    }

    return params;
  }