/** Load the whitelist from the properties file */
 static void loadWhitelist() {
   Properties whitelistProperties = new Properties();
   InputStream stream = null;
   try {
     stream =
         LookAheadObjectInputStream.class.getResourceAsStream(
             "/org/richfaces/resource/resource-serialization.properties");
     whitelistProperties.load(stream);
   } catch (IOException e) {
     throw new RuntimeException("Error loading the resource-serialization.properties file", e);
   } finally {
     if (stream != null) {
       try {
         stream.close();
       } catch (IOException e) {
         throw new RuntimeException("Error closing the resource-serialization.properties file", e);
       }
     }
   }
   for (String baseClassName : whitelistProperties.getProperty("whitelist").split(",")) {
     try {
       Class<?> baseClass = Class.forName(baseClassName);
       whitelistBaseClasses.add(baseClass);
     } catch (ClassNotFoundException e) {
       if (LOGGER.isInfoEnabled()) {
         LOGGER.debug(e);
       }
     }
   }
 }
  /**
   * Note: Filter does not delegate to chain, since it would lead into cycle by calling {@link
   * PushServlet#service(ServletRequest, ServletResponse)}.
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
      HttpServletRequest httpReq = (HttpServletRequest) request;
      HttpServletResponse httpResp = (HttpServletResponse) response;

      if ("GET".equals(httpReq.getMethod())) {
        String pushSessionId = httpReq.getParameter(PUSH_SESSION_ID_PARAM);

        Session session = null;

        if (pushSessionId != null) {
          ensureServletContextAvailable(request);
          PushContext pushContext =
              (PushContext) servletContext.getAttribute(PushContext.INSTANCE_KEY_NAME);
          session = pushContext.getSessionManager().getPushSession(pushSessionId);
        }

        if (session == null) {
          if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(MessageFormat.format("Session {0} was not found", pushSessionId));
          }
          httpResp.sendError(HttpServletResponse.SC_BAD_REQUEST);
          return;
        }

        httpResp.setContentType("text/plain");

        Meteor meteor =
            Meteor.build(httpReq, SCOPE.REQUEST, Collections.<BroadcastFilter>emptyList(), null);

        try {
          Request pushRequest = new RequestImpl(meteor, session);

          httpReq.setAttribute(SESSION_ATTRIBUTE_NAME, session);
          httpReq.setAttribute(REQUEST_ATTRIBUTE_NAME, pushRequest);

          pushRequest.suspend();
        } catch (Exception e) {
          LOGGER.error(e.getMessage(), e);
        }

        return;
      }
    }
  }
  @Override
  public boolean visitTree(VisitContext visitContext, VisitCallback callback) {

    // First check to see whether we are visitable. If not
    // short-circuit out of this subtree, though allow the
    // visit to proceed through to other subtrees.
    if (!isVisitable(visitContext)) {
      return false;
    }

    // Clear out the row index is one is set so that
    // we start from a clean slate.
    FacesContext facesContext = visitContext.getFacesContext();

    int oldRowIndex = getRowIndex();
    setRowIndex(-1);

    // Push ourselves to EL
    pushComponentToEL(facesContext, null);

    try {

      // Visit ourselves. Note that we delegate to the
      // VisitContext to actually perform the visit.
      VisitResult result = visitContext.invokeVisitCallback(this, callback);

      // If the visit is complete, short-circuit out and end the visit
      if (result == VisitResult.COMPLETE) {
        return true;
      }

      // Visit children, short-circuiting as necessary
      if ((result == VisitResult.ACCEPT) && doVisitChildren(visitContext)) {
        setRowIndex(-1);

        if (visitFixedChildren(visitContext, callback)) {
          return true;
        }

        if (visitDataChildren(visitContext, callback)) {
          return true;
        }
      }
    } finally {

      // Clean up - pop EL and restore old row index
      popComponentFromEL(facesContext);

      try {
        setRowIndex(oldRowIndex);
      } catch (Exception e) {
        LOG.error(e.getMessage(), e);
      }
    }

    // Return false to allow the visit to continue
    return false;
  }
  private ItemChangeEvent createItemChangeEvent(FacesContext facesContext) {
    if (facesContext == null) {
      throw new NullPointerException();
    }

    // Submitted value == null means "the component was not submitted at all".
    String activeItem = getSubmittedActiveItem();
    if (activeItem == null) {
      return null;
    }

    String previous = (String) getValue();
    if (previous == null || !previous.equalsIgnoreCase(activeItem)) {
      UIComponent prevComp = null;
      UIComponent actvComp = null;

      if (previous != null) {
        try {
          prevComp = (UIComponent) getItem(previous);
        } catch (TogglePanelVisitException e) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("Cannot include dynamic TogglePanelComponents in itemChangeEvents");
          }
          prevComp = null;
        }
      }
      if (activeItem != null) {
        try {
          if (LOG.isDebugEnabled()) {
            LOG.debug("Cannot include dynamic TogglePanelComponents in itemChangeEvents");
          }
          actvComp = (UIComponent) getItem(activeItem);
        } catch (TogglePanelVisitException e) {
          actvComp = null;
        }
      }

      return new ItemChangeEvent(this, previous, prevComp, activeItem, actvComp);
    }
    return null;
  }
Beispiel #5
0
  private void logPushFilterWarning(ServletContext servletContext) {
    String message;

    if (servletContext.getMajorVersion() >= 3) {
      message =
          "PushFilter has been deprecated, you can remove its declaration in Servlets 3 environment";
    } else {
      message = "PushFilter has been deprecated, you should use PushServlet instead";
    }

    LOGGER.warn(message);
  }
Beispiel #6
0
  public void afterPhase(PhaseEvent event) {
    Long phaseStartTime = phaseTimer.get();

    long measuredTime = 0;
    if (phaseStartTime != null) {
      measuredTime = System.currentTimeMillis() - phaseStartTime.longValue();
    }

    logger.debug(
        MessageFormat.format("Phase {0} completed by {1}ms", event.getPhaseId(), measuredTime));
    phaseTimer.set(null);
  }
  public void release() {
    super.release();

    if (uploadedFiles != null) {
      for (UploadedFile uploadedFile : uploadedFiles) {
        try {
          uploadedFile.delete();
        } catch (IOException e) {
          LOGGER.error(e.getMessage(), e);
        }
      }
    }
  }
  private void parseIfNecessary() {
    if (responseState != null) {
      return;
    }

    try {
      requestParser.parse();

      uploadedFiles = requestParser.getUploadedFiles();
      params = requestParser.getParameters();
      responseState = ResponseState.ok;
    } catch (FileUploadException e) {
      LOGGER.error(e.getMessage(), e);
      responseState = ResponseState.serverError;
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.richfaces.resource.external.ExternalStaticResourceFactory#getResourcesForLocation(java.lang.String)
   */
  @Override
  public Set<ResourceKey> getResourcesForLocation(String resourceLocation) {
    if (externalStaticResources == null) {
      LOGGER.error("factory hasn't been initialized yet");
      return Collections.emptySet();
    }

    Set<ResourceKey> result = Sets.newHashSet();
    for (Entry<ResourceKey, ExternalMapping> entry : externalStaticResources.entrySet()) {
      final ResourceKey resourceKey = entry.getKey();
      final ExternalMapping mapping = entry.getValue();

      if (mapping.getResourceLocation().equals(resourceLocation)) {
        result.add(resourceKey);
      }
    }

    return result;
  }
  public void broadcast(FacesContext context) throws AbortProcessingException {
    // Set up the correct context and fire our wrapped event
    UIDataAdaptor dataAdaptor = getComponent();
    initialRowKey = dataAdaptor.getRowKey();

    UIComponent compositeParent = null;

    UIComponent targetComponent = event.getComponent();

    try {
      if (!UIComponent.isCompositeComponent(targetComponent)) {
        compositeParent = UIComponent.getCompositeComponentParent(targetComponent);
      }

      if (compositeParent != null) {
        compositeParent.pushComponentToEL(context, null);
      }

      setupEventContext(context);

      targetComponent.pushComponentToEL(context, null);
      targetComponent.broadcast(event);
    } finally {
      try {
        dataAdaptor.setRowKey(context, initialRowKey);
      } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
      }

      initialRowKey = null;

      targetComponent.popComponentFromEL(context);

      if (compositeParent != null) {
        compositeParent.popComponentFromEL(context);
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.richfaces.application.Initializable#init()
   */
  @Override
  public void init() {
    final Map<ResourceKey, ExternalMapping> result = Maps.newHashMap();

    final List<String> mappingFiles = ResourceMappingFeature.getMappingFiles();
    for (String mappingFile : mappingFiles) {
      if (classpathResourceExistsForLocation(mappingFile)) {
        for (Entry<String, String> entry : PropertiesUtil.loadProperties(mappingFile).entrySet()) {
          final ResourceKey resourceKey = ResourceKey.create(entry.getKey());
          final String resourceLocation = entry.getValue();
          result.put(resourceKey, new ExternalMapping(resourceKey, resourceLocation));
        }
      } else {
        if (!isDefaultStaticResourceMappingLocation(mappingFile)) {
          LOGGER.warn(
              "Resource mapping is configured to load non-existent resource: '"
                  + mappingFile
                  + "'");
        }
      }
    }

    externalStaticResources = result;
  }
 private void logError(Exception e) {
   LOGGER.error(MessageFormat.format("Exception invoking listener: {0}", e.getMessage()), e);
 }
Beispiel #13
0
 public static Object getConvertedValue(
     FacesContext facesContext, UIComponent component, Object val) throws ConverterException {
   String[] values = (val == null) ? new String[0] : (String[]) val;
   Converter converter = SelectManyHelper.getItemConverter(facesContext, component);
   ValueExpression ve = component.getValueExpression("value");
   Object targetForConvertedValues = null;
   if (ve != null) {
     // If the component has a ValueExpression for value, let modelType be the type of the value
     // expression
     Class<?> modelType = ve.getType(facesContext.getELContext());
     if (modelType.isArray()) {
       // If the component has a ValueExpression for value and the type of the expression is an
       // array, let targetForConvertedValues be a new array of the expected type.
       Class<?> arrayComponentType = modelType.getComponentType();
       targetForConvertedValues = Array.newInstance(arrayComponentType, values.length);
     } else if (Collection.class.isAssignableFrom(modelType) || Object.class.equals(modelType)) {
       // If modelType is a Collection, do the following to arrive at targetForConvertedValues:
       // Ask the component for its attribute under the key "collectionType"
       String collectionType = (String) component.getAttributes().get("collectionType");
       if (collectionType != null) {
         // Let targetForConvertedValues be a new instance of Collection implemented by the
         // concrete class specified in collectionType
         Class<?> collectionClass = getCollectionClass(collectionType);
         try {
           targetForConvertedValues = collectionClass.newInstance();
         } catch (Exception e) {
           throw new FacesException(e);
         }
       } else {
         // If there is no "collectionType" attribute, call getValue() on the component
         // The result will implement Collection.
         Collection value = (Collection) ((EditableValueHolder) component).getValue();
         if (value instanceof Cloneable) {
           // If the result also implements Cloneable, let targetForConvertedValues be the result
           // of calling its clone() method,
           // then calling clear() on the cloned Collection.
           try {
             targetForConvertedValues =
                 (Collection) value.getClass().getMethod("clone").invoke(value);
             ((Collection) targetForConvertedValues).clear();
           } catch (Exception e) {
             // If unable to clone the value for any reason, log a message
             LOG.log(Logger.Level.WARNING, "Unable to clone collection");
           }
         }
         if (targetForConvertedValues == null) {
           // and proceed to the next step
           Class<?> collectionClass = value == null ? modelType : value.getClass();
           try {
             // If modelType is a concrete class, let targetForConvertedValues be a new instance of
             // that class.
             targetForConvertedValues = collectionClass.newInstance();
             ((Collection) targetForConvertedValues).clear();
           } catch (Exception e) {
             // Otherwise, the concrete type for targetForConvertedValues is taken from the
             // following table
             if (Collection.class.isAssignableFrom(modelType)) {
               if (SortedSet.class.isAssignableFrom(modelType)) {
                 targetForConvertedValues = new TreeSet();
               } else if (Queue.class.isAssignableFrom(modelType)) {
                 targetForConvertedValues = new LinkedList();
               } else if (Set.class.isAssignableFrom(modelType)) {
                 targetForConvertedValues = new HashSet(values.length);
               } else {
                 targetForConvertedValues = new ArrayList(values.length);
               }
             }
           }
         }
       }
     } else {
       throw new FacesException("ValueExpression must be either an Array, or a Collection");
     }
   } else {
     // If the component does not have a ValueExpression for value, let targetForConvertedValues be
     // an array of type Object.
     targetForConvertedValues = new Object[values.length];
   }
   for (int i = 0; i < values.length; i++) {
     Object value;
     if (converter == null) {
       value = values[i];
     } else {
       value = converter.getAsObject(facesContext, component, values[i]);
     }
     if (targetForConvertedValues.getClass().isArray()) {
       Array.set(targetForConvertedValues, i, value);
     } else {
       ((Collection) targetForConvertedValues).add(value);
     }
   }
   return targetForConvertedValues;
 }
Beispiel #14
0
 public void beforePhase(PhaseEvent event) {
   logger.debug(MessageFormat.format("Phase {0} started", event.getPhaseId()));
   phaseTimer.set(System.currentTimeMillis());
 }