@Override
  public VisitContext getVisitContext(
      FacesContext facesContext, Collection<String> ids, Set<VisitHint> hints) {

    // Prepend the ids with the portlet namespace unless they already start with the namespace, or
    // if the id starts with the SeparatorChar
    if (ids != null) {

      UIViewRoot viewRoot = facesContext.getViewRoot();
      String separator = String.valueOf(UINamingContainer.getSeparatorChar(facesContext));
      String containerClientIdAndSeparator =
          viewRoot.getContainerClientId(facesContext) + separator;

      List<String> newIds = new ArrayList<String>();

      for (String id : ids) {

        if (!id.startsWith(separator) && !id.startsWith(containerClientIdAndSeparator)) {
          id = containerClientIdAndSeparator + id;
        }

        newIds.add(id);
      }

      ids = newIds;
    }

    return wrappedVisitContextFactory.getVisitContext(facesContext, ids, hints);
  }
Exemplo n.º 2
0
  /**
   * <p>
   * Stores the provided state within the session obtained from the provided
   * <code>FacesContext</code>
   * </p>
   *
   * <p>If <code>stateCapture</code> is <code>null</code>, the composite
   * key used to look up the actual and logical views will be written to
   * the client as a hidden field using the <code>ResponseWriter</code>
   * from the provided <code>FacesContext</code>.</p>
   *
   * <p>If <code>stateCapture</code> is not <code>null</code>, the composite
   * key will be appended to the <code>StringBuilder<code> without any markup
   * included or any content written to the client.
   */
  public void writeState(FacesContext ctx, Object state, StringBuilder stateCapture)
      throws IOException {

    Util.notNull("context", ctx);

    String id;

    UIViewRoot viewRoot = ctx.getViewRoot();

    if (!viewRoot.isTransient()) {
      if (!ctx.getAttributes().containsKey("com.sun.faces.ViewStateValue")) {
        Util.notNull("state", state);
        Object[] stateToWrite = (Object[]) state;
        ExternalContext externalContext = ctx.getExternalContext();
        Object sessionObj = externalContext.getSession(true);
        Map<String, Object> sessionMap = externalContext.getSessionMap();

        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (sessionObj) {
          Map<String, Map> logicalMap =
              TypedCollections.dynamicallyCastMap(
                  (Map) sessionMap.get(LOGICAL_VIEW_MAP), String.class, Map.class);
          if (logicalMap == null) {
            logicalMap = Collections.synchronizedMap(new LRUMap<String, Map>(numberOfLogicalViews));
            sessionMap.put(LOGICAL_VIEW_MAP, logicalMap);
          }

          Object structure = stateToWrite[0];
          Object savedState = handleSaveState(stateToWrite[1]);

          String idInLogicalMap =
              (String) RequestStateManager.get(ctx, RequestStateManager.LOGICAL_VIEW_MAP);
          if (idInLogicalMap == null) {
            idInLogicalMap =
                ((generateUniqueStateIds) ? createRandomId() : createIncrementalRequestId(ctx));
          }
          String idInActualMap = null;
          if (ctx.getPartialViewContext().isPartialRequest()) {
            // If partial request, do not change actual view Id, because page not actually changed.
            // Otherwise partial requests will soon overflow cache with values that would be never
            // used.
            idInActualMap =
                (String) RequestStateManager.get(ctx, RequestStateManager.ACTUAL_VIEW_MAP);
          }
          if (null == idInActualMap) {
            idInActualMap =
                ((generateUniqueStateIds) ? createRandomId() : createIncrementalRequestId(ctx));
          }
          Map<String, Object[]> actualMap =
              TypedCollections.dynamicallyCastMap(
                  logicalMap.get(idInLogicalMap), String.class, Object[].class);
          if (actualMap == null) {
            actualMap = new LRUMap<String, Object[]>(numberOfViews);
            logicalMap.put(idInLogicalMap, actualMap);
          }

          id = idInLogicalMap + ':' + idInActualMap;

          Object[] stateArray = actualMap.get(idInActualMap);
          // reuse the array if possible
          if (stateArray != null) {
            stateArray[0] = structure;
            stateArray[1] = savedState;
          } else {
            actualMap.put(idInActualMap, new Object[] {structure, savedState});
          }

          // always call put/setAttribute as we may be in a clustered environment.
          sessionMap.put(LOGICAL_VIEW_MAP, logicalMap);
          ctx.getAttributes().put("com.sun.faces.ViewStateValue", id);
        }
      } else {
        id = (String) ctx.getAttributes().get("com.sun.faces.ViewStateValue");
      }
    } else {
      id = "stateless";
    }

    if (stateCapture != null) {
      stateCapture.append(id);
    } else {
      ResponseWriter writer = ctx.getResponseWriter();

      writer.startElement("input", null);
      writer.writeAttribute("type", "hidden", null);

      String viewStateParam = ResponseStateManager.VIEW_STATE_PARAM;

      if ((namespaceParameters) && (viewRoot instanceof NamingContainer)) {
        String namingContainerId = viewRoot.getContainerClientId(ctx);
        if (namingContainerId != null) {
          viewStateParam = namingContainerId + viewStateParam;
        }
      }
      writer.writeAttribute("name", viewStateParam, null);
      if (webConfig.isOptionEnabled(EnableViewStateIdRendering)) {
        String viewStateId = Util.getViewStateId(ctx);
        writer.writeAttribute("id", viewStateId, null);
      }
      writer.writeAttribute("value", id, null);
      if (webConfig.isOptionEnabled(AutoCompleteOffOnViewState)) {
        writer.writeAttribute("autocomplete", "off", null);
      }
      writer.endElement("input");

      writeClientWindowField(ctx, writer);
      writeRenderKitIdField(ctx, writer);
    }
  }
  @Override
  public void encodeJavaScriptCustom(FacesContext facesContext, UIComponent uiComponent)
      throws IOException {

    ResponseWriter responseWriter = facesContext.getResponseWriter();
    InputFile inputFile = (InputFile) uiComponent;
    JavaScriptFragment alloyNamespace = new JavaScriptFragment("A");

    // Determine the valid content-types and maximum file size from the validator (if specified).
    JavaScriptFragment contentTypes = new JavaScriptFragment("[]");
    String validContentTypes = inputFile.getContentTypes();

    if (validContentTypes != null) {
      contentTypes = toJavaScriptArray(validContentTypes.split(","));
    }

    String clientId = inputFile.getClientId(facesContext);
    Long maxFileSize = inputFile.getMaxFileSize();

    if (maxFileSize == null) {
      maxFileSize = Long.MAX_VALUE;
    }

    // If the component should render the upload progress table, then initialize the YUI progress
    // uploader widget.
    if (inputFile.isShowProgress()) {

      String clientVarName = getClientVarName(facesContext, inputFile);
      String clientKey = inputFile.getClientKey();

      if (clientKey == null) {
        clientKey = clientVarName;
      }

      UIViewRoot viewRoot = facesContext.getViewRoot();
      Locale locale = viewRoot.getLocale();
      String formClientId = getParentFormClientId(inputFile);
      Application application = facesContext.getApplication();
      ViewHandler viewHandler = application.getViewHandler();
      String actionURL = viewHandler.getActionURL(facesContext, viewRoot.getViewId());
      String partialActionURL = facesContext.getExternalContext().encodePartialActionURL(actionURL);
      String namingContainerId = "";

      if (viewRoot instanceof NamingContainer) {
        namingContainerId = viewRoot.getContainerClientId(facesContext);
      }

      AjaxParameters ajaxParameters = new AjaxParameters(inputFile, clientId, formClientId);
      String execute = ajaxParameters.getExecute();
      String render = ajaxParameters.getRender();

      String notStartedMessage = getMessageContext().getMessage(locale, "not-started");
      JavaScriptFragment clientComponent =
          new JavaScriptFragment("Liferay.component('" + clientKey + "')");
      encodeFunctionCall(
          responseWriter,
          "LFAI.initProgressUploader",
          alloyNamespace,
          clientComponent,
          contentTypes,
          clientId,
          formClientId,
          namingContainerId,
          inputFile.isAuto(),
          execute,
          render,
          partialActionURL,
          maxFileSize,
          notStartedMessage);
    }

    // Otherwise, if the component should render the upload preview table, then format the
    // preview-uploader.js
    // template and write it to the response.
    else if (inputFile.isShowPreview()) {

      encodeFunctionCall(
          responseWriter,
          "LFAI.initPreviewUploader",
          alloyNamespace,
          contentTypes,
          clientId,
          maxFileSize);
    }
  }
Exemplo n.º 4
0
  private static String buildAjaxCommand(
      ClientBehaviorContext behaviorContext,
      AjaxBehavior ajaxBehavior,
      boolean namespaceParameters) {

    // First things first - if AjaxBehavior is disabled, we are done.
    if (ajaxBehavior.isDisabled()) {
      return null;
    }

    UIComponent component = behaviorContext.getComponent();
    String eventName = behaviorContext.getEventName();

    StringBuilder ajaxCommand = new StringBuilder(256);
    Collection<String> execute = ajaxBehavior.getExecute();
    Collection<String> render = ajaxBehavior.getRender();
    String onevent = ajaxBehavior.getOnevent();
    String onerror = ajaxBehavior.getOnerror();
    String sourceId = behaviorContext.getSourceId();
    String delay = ajaxBehavior.getDelay();
    Boolean resetValues = null;
    if (ajaxBehavior.isResetValuesSet()) {
      resetValues = ajaxBehavior.isResetValues();
    }
    Collection<ClientBehaviorContext.Parameter> params = behaviorContext.getParameters();

    // Needed workaround for SelectManyCheckbox - if execute doesn't have sourceId,
    // we need to add it - otherwise, we use the default, which is sourceId:child, which
    // won't work.
    ClientBehaviorContext.Parameter foundparam = null;
    for (ClientBehaviorContext.Parameter param : params) {
      if (param.getName().equals("incExec") && (Boolean) param.getValue()) {
        foundparam = param;
      }
    }
    if (foundparam != null && !execute.contains(sourceId)) {
      execute = new LinkedList<>(execute);
      execute.add(component.getClientId());
    }
    if (foundparam != null) {
      try {
        // And since this is a hack, we now try to remove the param
        params.remove(foundparam);
      } catch (UnsupportedOperationException uoe) {
        if (logger.isLoggable(Level.FINEST)) {
          logger.log(Level.FINEST, "Unsupported operation", uoe);
        }
      }
    }

    ajaxCommand.append("mojarra.ab(");

    if (sourceId == null) {
      ajaxCommand.append("this");
    } else {
      ajaxCommand.append("'");
      ajaxCommand.append(sourceId);
      ajaxCommand.append("'");
    }

    ajaxCommand.append(",event,'");
    ajaxCommand.append(eventName);
    ajaxCommand.append("',");

    appendIds(component, ajaxCommand, execute);
    ajaxCommand.append(",");
    appendIds(component, ajaxCommand, render);

    String namingContainerId = null;
    if (namespaceParameters) {
      FacesContext context = behaviorContext.getFacesContext();
      UIViewRoot viewRoot = context.getViewRoot();
      if (viewRoot instanceof NamingContainer) {
        namingContainerId = viewRoot.getContainerClientId(context);
      }
    }

    if ((namingContainerId != null)
        || (onevent != null)
        || (onerror != null)
        || (delay != null)
        || (resetValues != null)
        || !params.isEmpty()) {

      ajaxCommand.append(",{");

      if (namingContainerId != null) {
        // the literal string must exactly match the corresponding value
        // in jsf.js.
        RenderKitUtils.appendProperty(
            ajaxCommand, "com.sun.faces.namingContainerId", namingContainerId, true);
      }

      if (onevent != null) {
        RenderKitUtils.appendProperty(ajaxCommand, "onevent", onevent, false);
      }

      if (onerror != null) {
        RenderKitUtils.appendProperty(ajaxCommand, "onerror", onerror, false);
      }

      if (delay != null) {
        RenderKitUtils.appendProperty(ajaxCommand, "delay", delay, true);
      }

      if (resetValues != null) {
        RenderKitUtils.appendProperty(ajaxCommand, "resetValues", resetValues, false);
      }

      if (!params.isEmpty()) {
        for (ClientBehaviorContext.Parameter param : params) {
          RenderKitUtils.appendProperty(ajaxCommand, param.getName(), param.getValue());
        }
      }

      ajaxCommand.append("}");
    }

    ajaxCommand.append(")");

    return ajaxCommand.toString();
  }