// TODO extract configured Mapping to FacesServlet
  @Override
  public String getRequestPath() {
    final FacesContext facesContext = FacesContext.getCurrentInstance();

    List<String> optionalParameters = new ArrayList<>(5);
    if (getLibraryName() != null) {
      optionalParameters.add("ln=" + getLibraryName());
    }
    if (!facesContext.isProjectStage(ProjectStage.Production)) {
      // append stage for all ProjectStages except Production
      optionalParameters.add("stage=" + facesContext.getApplication().getProjectStage().toString());
    }

    StringBuilder sb =
        new StringBuilder(30)
            .append(ResourceHandler.RESOURCE_IDENTIFIER)
            .append('/')
            .append(getResourceName())
            // the mapping has to be added, otherwise resources are not dispatched by the
            // FacesServlet
            .append(".xhtml");

    String parameterString = optionalParameters.stream().collect(Collectors.joining("&"));
    if (StringUtils.isNotBlank(parameterString)) {
      sb.append("?").append(parameterString);
    }

    return facesContext
        .getApplication()
        .getViewHandler()
        .getResourceURL(facesContext, sb.toString());
  }
 @Override
 public boolean userAgentNeedsUpdate(FacesContext fc) {
   // RFC2616 says related to If-Modified-Since header the following:
   //
   // "... The If-Modified-Since request-header field is used with a method
   // to make it conditional: if the requested variant has not been
   // modified since the time specified in this field, an entity will not
   // be returned from the server; instead, a 304 (not modified) response
   // will be returned without any message-body..."
   //
   // This method is called from ResourceHandlerImpl.handleResourceRequest
   // and if returns false send a 304 Not Modified response.
   if (!fc.isProjectStage(ProjectStage.Development)) {
     final Optional<String> ifModSinceHeader =
         Optional.ofNullable(
             fc.getExternalContext().getRequestHeaderMap().get("If-Modified-Since"));
     if (ifModSinceHeader.isPresent()) {
       LocalDateTime ifModifiedSince = convertIfModifiedSinceToDate(ifModSinceHeader.get());
       if (ifModifiedSince != null) return lastModified.isAfter(ifModifiedSince);
     }
   }
   // when in Development, or no if-modified-since header was found
   // (or couldn't be parsed),request a fresh resource
   return true;
 }
    public void processEvent(SystemEvent event) throws AbortProcessingException {
      FacesContext context = FacesContext.getCurrentInstance();
      ExternalContext externalContext = context.getExternalContext();
      Theme theme = (Theme) externalContext.getSessionMap().get(MOBI_THEME_KEY);

      boolean prod = context.isProjectStage(ProjectStage.Production);
      String name = CSSUtils.getThemeCSSFileName(theme, prod);

      String library = deriveLibrary(context.getAttributes());

      UIComponent resource = createThemeResource(context, library, name);
      context.getViewRoot().addComponentResource(context, resource);
    }
  @Override
  public void encodeJavaScriptCustom(FacesContext facesContext, UIComponent uiComponent)
      throws IOException {

    ResponseWriter responseWriter = facesContext.getResponseWriter();

    Popover popover = (Popover) uiComponent;
    ClientComponent clientComponent = (ClientComponent) uiComponent;
    String clientVarName = getClientVarName(facesContext, clientComponent);
    String clientKey = clientComponent.getClientKey();

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

    if (popover.isHideIconRendered()) {

      // Add an "x" toolbar icon so that the popover can be hidden just like alloy:dialog can.
      responseWriter.write(LIFERAY_COMPONENT);
      responseWriter.write("('");
      responseWriter.write(clientKey);
      responseWriter.write(
          "').addToolbar([{cssClass:'close',label:'\u00D7',on:{click:function(event){Liferay.component('");
      responseWriter.write(clientKey);
      responseWriter.write("').hide();}},render:true}],'header');");
    }

    // Move the overlayBody div into the popover-content div.
    String clientId = popover.getClientId(facesContext);
    String overlayBodyClientId = clientId.concat(OVERLAY_BODY_SUFFIX);
    String escapedOverlayBodyClientId = escapeClientId(overlayBodyClientId);

    String contentBoxClientId = clientId.concat(CONTENT_BOX_SUFFIX);
    String escapedContentBoxClientId = escapeClientId(contentBoxClientId);

    responseWriter.write("A.one('#");
    responseWriter.write(escapedOverlayBodyClientId);
    responseWriter.write("').appendTo(A.one('div#");
    responseWriter.write(escapedContentBoxClientId);
    responseWriter.write(">div.popover-content'));");

    if (popover.isDismissible()) {
      encodeOverlayDismissible(responseWriter, popover, clientKey);
    }

    encodeOverlayJavaScriptCustom(responseWriter, facesContext, popover);

    if ((popover.getFor() == null) && facesContext.isProjectStage(ProjectStage.Development)) {
      logger.error("The 'for' attribute is required for alloy:popover");
    }
  }
  public AjaxRequestBuilder delay(String delay) {
    if (!ComponentUtils.isValueBlank(delay) && !delay.equals("none")) {
      buffer.append(",d:").append(delay);

      if (context.isProjectStage(ProjectStage.Development)) {
        try {
          Integer.parseInt(delay);
        } catch (NumberFormatException e) {
          throw new FaceletException("Delay attribute should only take numbers or \"none\"");
        }
      }
    }

    return this;
  }
  @Override
  public void processEvent(SystemEvent postConstructApplicationEvent)
      throws AbortProcessingException {

    // Due to ClassLoader problems during static initialization, it is necessary to delay creation
    // of singleton
    // instances of template classes until the PostConstructApplicationEvent is sent.
    try {
      FacesContext startupFacesContext = FacesContext.getCurrentInstance();
      boolean minified = startupFacesContext.isProjectStage(ProjectStage.Production);
      wysiwygTemplate = new WYSIWYGTemplate(minified);
    } catch (Exception e) {
      logger.error(e);
    }
  }
Example #7
0
  private void throwIt(FacesContext ctx, FacesException fe) {

    boolean isDevelopment = ctx.isProjectStage(ProjectStage.Development);
    if (isDevelopment && !errorPagePresent) {
      // RELEASE_PENDING_2_1
      // thThe error page here will be text/html which means not all device
      // types are going to render this properly.  This should be addressed
      // in 2.1
      RenderKitUtils.renderHtmlErrorPage(ctx, fe);
    } else {
      if (isDevelopment) {
        // store the view root where the exception occurred into the
        // request scope so that the error page can display that component
        // tree and not the one rendering the errorpage
        ctx.getExternalContext().getRequestMap().put("com.sun.faces.error.view", ctx.getViewRoot());
      }
      throw fe;
    }
  }
  private void writeOutDeviceStyleSheets(
      FacesContext facesContext, DeviceResource comp, Theme theme) throws IOException {

    /**
     * The component has three modes in which it executes. 1.) no attributes - then component tries
     * to detect a mobile device in from the user-agent. If a mobile device is discovered, then it
     * will fall into three possible matches, iphone, ipad, android and blackberry. If the mobile
     * device is not not know then ipad is loaded. Library is always assumed to be DEFAULT_LIBRARY.
     *
     * <p>2.) name attribute - component will default to using a library name of DEFAULT_LIBRARY.
     * The name attribute specifies one of the possible device themes; iphone.css, android.css or
     * bberry.css. Error will result if named resource could not be resolved.
     *
     * <p>3.) name and libraries attributes. - component will use the library and name specified by
     * the user. Component is fully manual in this mode. Error will result if name and library can
     * not generate a value resource.
     */
    boolean prod = facesContext.isProjectStage(ProjectStage.Production);
    String cssFile = CSSUtils.getThemeCSSFileName(theme, prod);

    String library = deriveLibrary(facesContext.getAttributes());
    Resource resource =
        facesContext
            .getApplication()
            .getResourceHandler()
            .createResource(cssFile, library, "text/css");
    String resourceUrl = RESOURCE_URL_ERROR;
    if (resource != null) {
      resourceUrl = facesContext.getExternalContext().encodeResourceURL(resource.getRequestPath());
    } else if (log.isLoggable(Level.WARNING)) {
      log.warning("Warning could not load resource " + library + "/" + theme);
    }
    ResponseWriter writer = facesContext.getResponseWriter();
    writer.startElement(HTML.LINK_ELEM, comp);
    writer.writeAttribute(HTML.TYPE_ATTR, HTML.LINK_TYPE_TEXT_CSS, HTML.TYPE_ATTR);
    writer.writeAttribute(HTML.REL_ATTR, HTML.STYLE_REL_STYLESHEET, HTML.REL_ATTR);
    PassThruAttributeWriter.renderNonBooleanAttributes(
        writer, comp, new Attribute[] {new Attribute("media", null)});
    writer.writeURIAttribute(HTML.HREF_ATTR, resourceUrl, HTML.HREF_ATTR);
    writer.endElement(HTML.LINK_ELEM);
  }
  private void handlePartialResponseError(FacesContext context, Throwable t) {
    if (context.getResponseComplete()) {
      return; // don't write anything if the response is complete
    }
    try {

      ExternalContext extContext = context.getExternalContext();
      extContext.setResponseContentType("text/xml");
      extContext.addResponseHeader("Cache-Control", "no-cache");
      PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();

      writer.startDocument();
      writer.startError(t.getClass().toString());
      String msg;
      if (context.isProjectStage(ProjectStage.Production)) {
        msg = "See your server log for more information";
      } else {
        if (t.getCause() != null) {
          msg = t.getCause().getMessage();
        } else {
          msg = t.getMessage();
        }
      }
      writer.write(((msg != null) ? msg : ""));
      writer.endError();
      writer.endDocument();

      if (LOGGER.isLoggable(Level.SEVERE)) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        LOGGER.log(Level.SEVERE, sw.toString());
      }

      context.responseComplete();
    } catch (IOException ioe) {
      if (LOGGER.isLoggable(Level.SEVERE)) {
        LOGGER.log(Level.SEVERE, ioe.toString(), ioe);
      }
    }
  }
  @Override
  public void encodeMarkupBegin(FacesContext facesContext, UIComponent uiComponent)
      throws IOException {

    ResponseWriter responseWriter = facesContext.getResponseWriter();
    OutputTooltipResponseWriter outputTooltipResponseWriter =
        new OutputTooltipResponseWriter(responseWriter, uiComponent);

    OutputTooltip outputTooltip = (OutputTooltip) uiComponent;

    if (outputTooltip.getFor() == null) {

      if (facesContext.isProjectStage(ProjectStage.Development)) {
        logger.error(
            "The outputTooltip needs to point to something. Try using its 'for' attribute to point to an 'id' in the component tree.");
      }
    }

    // Mojarra's HTML Basic calls encodeEnd for fun
    super.encodeMarkupEnd(facesContext, uiComponent, outputTooltipResponseWriter);
  }
Example #11
0
  protected void renderAsDisabled(
      FacesContext context, UIComponent component, boolean failedToResolveNavigationCase)
      throws IOException {

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

    writer.startElement("span", component);
    writeIdAndNameAttributes(context, writer, component);
    renderLinkCommonAttributes(writer, component);
    renderPassThruAttributes(context, writer, component, ATTRIBUTES);
    writeValue(writer, component);

    // shame that we can't put this in encodeEnd, but then we have to attempt to resolve the
    // navigation case again
    if (failedToResolveNavigationCase) {
      if (!context.isProjectStage(ProjectStage.Production)) {
        writer.write(
            MessageUtils.getExceptionMessageString(MessageUtils.OUTCOME_TARGET_LINK_NO_MATCH));
      }
    }
  }
  /**
   * @see
   *     ResourceHelper#getNonCompressedInputStream(com.sun.faces.application.resource.ResourceInfo,
   *     javax.faces.context.FacesContext)
   */
  protected InputStream getNonCompressedInputStream(ResourceInfo resource, FacesContext ctx)
      throws IOException {

    InputStream in = null;

    if (ctx.isProjectStage(ProjectStage.Development)) {
      ClassLoader loader = Util.getCurrentLoader(getClass());
      String path = resource.getPath();
      if (loader.getResource(path) != null) {
        in = loader.getResource(path).openStream();
      }
      if (in == null && getClass().getClassLoader().getResource(path) != null) {
        in = getClass().getClassLoader().getResource(path).openStream();
      }
    } else {
      ClassLoader loader = Util.getCurrentLoader(getClass());
      String path = resource.getPath();
      in = loader.getResourceAsStream(path);
      if (in == null) {
        in = getClass().getClassLoader().getResourceAsStream(path);
      }
    }
    return in;
  }
  /**
   * @see ResourceHelper#findResource(LibraryInfo, String, String, boolean,
   *     javax.faces.context.FacesContext)
   */
  public ResourceInfo findResource(
      LibraryInfo library,
      String resourceName,
      String localePrefix,
      boolean compressable,
      FacesContext ctx) {

    resourceName = trimLeadingSlash(resourceName);
    ContractInfo[] outContract = new ContractInfo[1];
    outContract[0] = null;

    ClassLoader loader = Util.getCurrentLoader(this);
    String basePath;
    if (library != null) {
      basePath = library.getPath(localePrefix) + '/' + resourceName;
    } else {
      if (localePrefix == null) {
        basePath = getBaseResourcePath() + '/' + resourceName;
      } else {
        basePath = getBaseResourcePath() + '/' + localePrefix + '/' + resourceName;
      }
    }

    URL basePathURL = loader.getResource(basePath);
    if (basePathURL == null) {
      // try using this class' loader (necessary when running in OSGi)
      basePathURL = this.getClass().getClassLoader().getResource(basePath);
      if (basePathURL == null) {
        // Try it without the localePrefix
        if (library != null) {
          basePath = library.getPath(null) + '/' + resourceName;
        } else {
          basePath = getBaseResourcePath() + '/' + resourceName;
        }
        basePathURL = loader.getResource(basePath);
        if (basePathURL == null) {
          // try using this class' loader (necessary when running in OSGi)
          basePathURL = this.getClass().getClassLoader().getResource(basePath);
          if (basePathURL == null) {
            return null;
          }
        }

        localePrefix = null;
      }
    }

    ClientResourceInfo value;

    if (library != null) {
      value =
          new ClientResourceInfo(
              library,
              outContract[0],
              resourceName,
              null,
              compressable,
              resourceSupportsEL(resourceName, library.getName(), ctx),
              ctx.isProjectStage(ProjectStage.Development),
              cacheTimestamp);
    } else {
      value =
          new ClientResourceInfo(
              outContract[0],
              resourceName,
              null,
              localePrefix,
              this,
              compressable,
              resourceSupportsEL(resourceName, null, ctx),
              ctx.isProjectStage(ProjectStage.Development),
              cacheTimestamp);
    }

    if (value.isCompressable()) {
      value = handleCompression(value);
    }
    return value;
  }
  protected String resolveResourceUrl(
      FacesContext context, UIComponent component, String library, String name) {
    Map<Object, Object> contextMap = context.getAttributes();

    String key = name + library;

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

    // Ensure this import is not rendered more than once per request
    if (contextMap.containsKey(key)) {
      return null;
    }
    contextMap.put(key, Boolean.TRUE);

    // Special case of scripts that have query strings
    // These scripts actually use their query strings internally, not externally
    // so we don't need the resource to know about them
    int queryPos = name.indexOf("?");
    String query = null;
    if (queryPos > -1 && name.length() > queryPos) {
      query = name.substring(queryPos + 1);
      name = name.substring(0, queryPos);
    }

    Resource resource = context.getApplication().getResourceHandler().createResource(name, library);

    String resourceSrc = "RES_NOT_FOUND";

    WebConfiguration webConfig = WebConfiguration.getInstance();

    if (library == null
        && name != null
        && name.startsWith(
            webConfig.getOptionValue(
                WebConfiguration.WebContextInitParameter.WebAppContractsDirectory))) {

      if (context.isProjectStage(ProjectStage.Development)) {

        String msg = "Illegal path, direct contract references are not allowed: " + name;
        context.addMessage(
            component.getClientId(context),
            new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));
      }
      resource = null;
    }

    if (resource == null) {

      if (context.isProjectStage(ProjectStage.Development)) {
        String msg = "Unable to find resource " + (library == null ? "" : library + ", ") + name;
        context.addMessage(
            component.getClientId(context),
            new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));
      }

    } else {
      resourceSrc = resource.getRequestPath();
      if (query != null) {
        resourceSrc = resourceSrc + ((resourceSrc.indexOf("?") > -1) ? "&amp;" : "?") + query;
      }
      resourceSrc = context.getExternalContext().encodeResourceURL(resourceSrc);
    }

    return resourceSrc;
  }