Example #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);
    }
  }
 // Populate a pristine component to be used in state holder tests
 protected void populateComponent(UIComponent component) {
   super.populateComponent(component);
   UIViewRoot vr = (UIViewRoot) component;
   vr.setRenderKitId("foo");
   vr.setViewId("bar");
   vr.setLocale(new Locale("fr", "FR"));
 }
  // 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);
    }
  }
  @Override
  public void setUp() throws Exception {
    FactoryFinder.releaseFactories();
    super.setUp();
    for (int i = 0, len = FACTORIES.length; i < len; i++) {
      System.getProperties().remove(FACTORIES[i][0]);
    }

    FactoryFinder.releaseFactories();
    int len, i = 0;

    // simulate the "faces implementation specific" part
    for (i = 0, len = FACTORIES.length; i < len; i++) {
      FactoryFinder.setFactory(FACTORIES[i][0], FACTORIES[i][1]);
    }

    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    root.setViewId("/viewId");
    facesContext.setViewRoot(root);
    RenderKitFactory renderKitFactory =
        (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
    RenderKit renderKit = new MockRenderKit();
    try {
      renderKitFactory.addRenderKit(RenderKitFactory.HTML_BASIC_RENDER_KIT, renderKit);
    } catch (IllegalArgumentException e) {;
    }
  }
  // Test validation of component with UISelectItems pointing to map
  public void testValidation2() 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
    Map map = new HashMap();
    map.put("key_foo", "foo");
    map.put("key_bar", "bar");
    map.put("key_baz", "baz");
    UISelectItems items = new UISelectItems();
    items.setValue(map);
    UISelectOne selectOne = (UISelectOne) component;
    selectOne.getChildren().add(items);

    selectOne.setValid(true);
    selectOne.setSubmittedValue("foo");
    selectOne.validate(facesContext);
    assertTrue(selectOne.isValid());

    // Validate one value on the list and one not on the list
    selectOne.setValid(true);
    selectOne.setSubmittedValue("car");
    selectOne.setRendererType(null); // We don't have any renderers
    selectOne.validate(facesContext);
    assertTrue(!selectOne.isValid());
  }
  // Test validation against a nested list of available options
  public void testValidateNested() throws Exception {

    // Set up UISelectOne with nested UISelectItems
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    root.getChildren().add(component);
    UISelectOne selectOne = (UISelectOne) component;
    UISelectItems selectItems = new UISelectItems();
    selectItems.setValue(setupOptions());
    selectOne.getChildren().add(selectItems);
    selectOne.setRequired(true);
    checkMessages(0);

    // Verify that all legal values will validate
    for (int i = 0; i < legalValues.length; i++) {
      selectOne.setValid(true);
      selectOne.setSubmittedValue(legalValues[i]);
      selectOne.validate(facesContext);
      assertTrue("Value '" + legalValues[i] + "' found", selectOne.isValid());
      checkMessages(0);
    }

    // Verify that illegal values will not validate
    for (int i = 0; i < illegalValues.length; i++) {
      selectOne.setValid(true);
      selectOne.setSubmittedValue(illegalValues[i]);
      selectOne.validate(facesContext);
      assertTrue("Value '" + illegalValues[i] + "' not found", !selectOne.isValid());
      checkMessages(i + 1);
    }
  }
  public void doTestPhaseMethodExpressionAndListenerWithPhaseId(UIViewRoot root, PhaseId phaseId)
      throws Exception {
    PhaseListenerBean phaseListener = new PhaseListenerBean(phaseId);
    PhaseListenerBean phaseListenerBean = new PhaseListenerBean(phaseId);
    facesContext.getExternalContext().getRequestMap().put("bean", phaseListenerBean);
    Class[] args = new Class[] {PhaseEvent.class};
    MethodExpression
        beforeExpression =
            facesContext
                .getApplication()
                .getExpressionFactory()
                .createMethodExpression(
                    facesContext.getELContext(), "#{bean.beforePhase}", null, args),
        afterExpression =
            facesContext
                .getApplication()
                .getExpressionFactory()
                .createMethodExpression(
                    facesContext.getELContext(), "#{bean.afterPhase}", null, args);
    root.setBeforePhaseListener(beforeExpression);
    root.setAfterPhaseListener(afterExpression);
    root.addPhaseListener(phaseListener);

    callRightLifecycleMethodGivenPhaseId(root, phaseId);

    assertTrue(phaseListenerBean.isBeforePhaseCalled());
    assertTrue(phaseListenerBean.isAfterPhaseCalled());
    assertTrue(phaseListener.isBeforePhaseCalled());
    assertTrue(phaseListener.isAfterPhaseCalled());
  }
  // Test validation of a required field
  public void testValidateRequired() throws Exception {

    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    root.getChildren().add(component);
    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));
    selectOne.setRequired(true);
    checkMessages(0);

    selectOne.setValid(true);
    selectOne.setSubmittedValue("foo");
    selectOne.validate(facesContext);
    checkMessages(0);
    assertTrue(selectOne.isValid());

    selectOne.setValid(true);
    selectOne.setSubmittedValue("");
    selectOne.validate(facesContext);
    checkMessages(1);
    assertTrue(!selectOne.isValid());

    selectOne.setValid(true);
    selectOne.setSubmittedValue(null);
    // awiner: see UIInputTestCase
    selectOne.validate(facesContext);
    checkMessages(1);
    assertTrue(selectOne.isValid());
  }
Example #9
0
  private void restoreView(FacesContext context) throws FacesException {
    Application app = context.getApplication();

    if (app instanceof ApplicationImpl) ((ApplicationImpl) app).initRequest();

    ViewHandler view = app.getViewHandler();

    view.initView(context);

    UIViewRoot viewRoot = context.getViewRoot();

    if (viewRoot != null) {
      ExternalContext extContext = context.getExternalContext();

      viewRoot.setLocale(extContext.getRequestLocale());

      doSetBindings(context.getELContext(), viewRoot);

      return;
    }

    String viewId = calculateViewId(context);

    String renderKitId = view.calculateRenderKitId(context);

    RenderKitFactory renderKitFactory =
        (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);

    RenderKit renderKit = renderKitFactory.getRenderKit(context, renderKitId);

    ResponseStateManager stateManager = renderKit.getResponseStateManager();

    if (stateManager.isPostback(context)) {
      viewRoot = view.restoreView(context, viewId);

      if (viewRoot != null) {
        doSetBindings(context.getELContext(), viewRoot);
      } else {
        // XXX: backward compat issues with ViewHandler and StateManager

        // throw new ViewExpiredException(L.l("{0} is an expired view", viewId));

        context.renderResponse();

        viewRoot = view.createView(context, viewId);

        context.setViewRoot(viewRoot);
      }

      context.setViewRoot(viewRoot);
    } else {
      context.renderResponse();

      viewRoot = view.createView(context, viewId);

      context.setViewRoot(viewRoot);
    }
  }
  public void testPhaseMethodExpressionAndListenerState() throws Exception {
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    facesContext.setViewRoot(root);
    Object state = root.saveState(facesContext);
    root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    facesContext.setViewRoot(root);
    root.restoreState(facesContext, state);

    doTestPhaseMethodExpressionAndListener(root, false);
  }
Example #11
0
  protected void addViewParameters(
      FacesContext ctx, String viewId, Map<String, List<String>> existingParameters) {

    UIViewRoot currentRoot = ctx.getViewRoot();
    String currentViewId = currentRoot.getViewId();
    Collection<UIViewParameter> toViewParams;
    Collection<UIViewParameter> currentViewParams;
    boolean currentIsSameAsNew = false;
    currentViewParams = ViewMetadata.getViewParameters(currentRoot);

    if (currentViewId.equals(viewId)) {
      currentIsSameAsNew = true;
      toViewParams = currentViewParams;
    } else {
      ViewDeclarationLanguage pdl = getViewDeclarationLanguage(ctx, viewId);
      ViewMetadata viewMetadata = pdl.getViewMetadata(ctx, viewId);
      UIViewRoot root = viewMetadata.createMetadataView(ctx);
      toViewParams = ViewMetadata.getViewParameters(root);
    }

    if (toViewParams.isEmpty()) {
      return;
    }

    for (UIViewParameter viewParam : toViewParams) {
      String value;
      // don't bother looking at view parameter if it's been overridden
      if (existingParameters.containsKey(viewParam.getName())) {
        continue;
      } else if (paramHasValueExpression(viewParam)) {
        value = viewParam.getStringValueFromModel(ctx);
      } else {
        // Anonymous view parameter:
        // Get string value from UIViewParameter instance stored in current view
        if (currentIsSameAsNew) {
          value = viewParam.getStringValue(ctx);
        }
        // ...or transfer string value from matching UIViewParameter instance stored in current view
        else {
          value = getStringValueToTransfer(ctx, viewParam, currentViewParams);
        }
      }
      if (value != null) {
        List<String> existing = existingParameters.get(viewParam.getName());
        if (existing == null) {
          existing = new ArrayList<String>(4);
          existingParameters.put(viewParam.getName(), existing);
        }
        existing.add(value);
      }
    }
  }
 public void doTestPhaseMethodExpressionAndListener(UIViewRoot root, boolean skipping)
     throws Exception {
   PhaseSkipTestComponent comp = null;
   if (skipping) {
     comp = new PhaseSkipTestComponent();
     root.getChildren().add(comp);
     facesContext.responseComplete();
   }
   doTestPhaseMethodExpressionAndListenerWithPhaseId(root, PhaseId.APPLY_REQUEST_VALUES);
   if (skipping) {
     assertTrue(!comp.isDecodeCalled());
   }
   doTestPhaseMethodExpressionAndListenerWithPhaseId(root, PhaseId.PROCESS_VALIDATIONS);
   if (skipping) {
     assertTrue(!comp.isProcessValidatorsCalled());
   }
   doTestPhaseMethodExpressionAndListenerWithPhaseId(root, PhaseId.UPDATE_MODEL_VALUES);
   if (skipping) {
     assertTrue(!comp.isProcessUpdatesCalled());
   }
   doTestPhaseMethodExpressionAndListenerWithPhaseId(root, PhaseId.INVOKE_APPLICATION);
   doTestPhaseMethodExpressionAndListenerWithPhaseId(root, PhaseId.RENDER_RESPONSE);
   if (skipping) {
     assertTrue(!comp.isEncodeBeginCalled());
   }
 }
  // Check that the properties on the specified components are equal
  protected void checkProperties(UIComponent comp1, UIComponent comp2) {

    super.checkProperties(comp1, comp2);
    UIViewRoot vr1 = (UIViewRoot) comp1;
    UIViewRoot vr2 = (UIViewRoot) comp2;
    assertEquals(vr2.getRenderKitId(), vr2.getRenderKitId());
    assertEquals(vr1.getViewId(), vr2.getViewId());
    assertEquals(vr1.getLocale(), vr2.getLocale());
  }
  private void checkEventQueueing(PhaseId phaseId) {

    // NOTE:  Current semantics for ANY_PHASE listeners is that
    // the event should be delivered exactly once, so the existence
    // of such a listener does not cause the event to remain queued.
    // Therefore, the expected string is the same as for any
    // phase-specific listener, and it should get matched after
    // Apply Request Values processing since that is first phase
    // for which events are fired

    // Register an event listener for the specified phase id
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    facesContext.setViewRoot(root);
    TestEvent event = null;
    TestListener listener = new TestListener("t");
    root.addFacesListener(listener);

    // Queue some events to be processed
    event = new TestEvent(root, "1");
    event.setPhaseId(phaseId);
    root.queueEvent(event);
    event = new TestEvent(root, "2");
    event.setPhaseId(phaseId);
    root.queueEvent(event);
    String expected = "/t/1/t/2";

    // Fire off the relevant lifecycle methods and check expected results
    TestListener.trace(null);
    assertEquals("", TestListener.trace());
    root.processDecodes(facesContext);
    if (PhaseId.APPLY_REQUEST_VALUES.equals(phaseId) || PhaseId.ANY_PHASE.equals(phaseId)) {
      assertEquals(expected, TestListener.trace());
    } else {
      assertEquals("", TestListener.trace());
    }
    root.processValidators(facesContext);
    if (PhaseId.PROCESS_VALIDATIONS.equals(phaseId)
        || PhaseId.APPLY_REQUEST_VALUES.equals(phaseId)
        || PhaseId.APPLY_REQUEST_VALUES.equals(phaseId)
        || PhaseId.ANY_PHASE.equals(phaseId)) {
      assertEquals(expected, TestListener.trace());
    } else {
      assertEquals("", TestListener.trace());
    }
    root.processUpdates(facesContext);
    if (PhaseId.UPDATE_MODEL_VALUES.equals(phaseId)
        || PhaseId.PROCESS_VALIDATIONS.equals(phaseId)
        || PhaseId.APPLY_REQUEST_VALUES.equals(phaseId)
        || PhaseId.ANY_PHASE.equals(phaseId)) {
      assertEquals(expected, TestListener.trace());
    } else {
      assertEquals("", TestListener.trace());
    }
    root.processApplication(facesContext);
    assertEquals(expected, TestListener.trace());
  }
Example #15
0
 // 编写处理Action事件的方法
 public void processAction(ActionEvent event) {
   // 获取当前的FacesContext对象
   FacesContext context = FacesContext.getCurrentInstance();
   // 获取JSF页面中<f:view.../>元素
   UIViewRoot viewRoot = context.getViewRoot();
   // 通过ID获取<f:view.../>内的<h:form.../>子元素。
   UIComponent comp = viewRoot.findComponent("addForm");
   // 通过ID获取<h:form.../>内的第一个<h:inputText.../>子元素。
   UIInput input = (UIInput) comp.findComponent("name");
   // 通过ID获取<h:form.../>内的第二个<h:inputText.../>子元素。
   HtmlInputText price = (HtmlInputText) comp.findComponent("price");
   if (input.getValue().equals("疯狂Java讲义")) {
     price.setSize(60);
     price.setValue("99.0元");
     price.setStyle("background-color:#9999ff;" + "font-weight:bold");
   }
 }
  public void doTestPhaseListenerWithPhaseId(UIViewRoot root, PhaseId phaseId) throws Exception {
    PhaseListenerBean phaseListener = new PhaseListenerBean(phaseId);
    root.addPhaseListener(phaseListener);

    callRightLifecycleMethodGivenPhaseId(root, phaseId);

    assertTrue(phaseListener.isBeforePhaseCalled());
    assertTrue(phaseListener.isAfterPhaseCalled());
  }
Example #17
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());
      }
    }
  }
Example #18
0
  /**
   * Call {@link ViewDeclarationLanguage#renderView(javax.faces.context.FacesContext,
   * javax.faces.component.UIViewRoot)} if the view can be rendered.
   *
   * @see ViewHandler#renderView(javax.faces.context.FacesContext, javax.faces.component.UIViewRoot)
   */
  public void renderView(FacesContext context, UIViewRoot viewToRender)
      throws IOException, FacesException {

    Util.notNull("context", context);
    Util.notNull("viewToRender", viewToRender);

    vdlFactory
        .getViewDeclarationLanguage(viewToRender.getViewId())
        .renderView(context, viewToRender);
  }
  // Test event queuing and dequeuing during broadcasting
  public void testEventBroadcasting() {

    // Register a listener that will conditionally queue a new event
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    facesContext.setViewRoot(root);

    root.addFacesListener(new TestListener("t", "2", "4"));
    TestListener.trace(null);

    // Queue some events, including the trigger one
    TestEvent event = new TestEvent(root, "1");
    event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
    root.queueEvent(event);
    event = new TestEvent(root, "2");
    event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
    root.queueEvent(event);
    event = new TestEvent(root, "3");
    event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
    root.queueEvent(event);

    // Simulate the Apply Request Values phase
    root.processDecodes(facesContext);

    // Validate the results (expect 4th event to also be queued)
    String expected = "/t/1/t/2/t/3/t/4";
    assertEquals(expected, TestListener.trace());
  }
  public static UIViewRoot findRoot(FacesContext context, ServletRequest req, Object etag)
      throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    UIViewRoot root = context.getViewRoot();

    if (root == null)
      throw new NullPointerException(L.l("f:view can't find current in FacesContext"));

    Object oldETag = root.getAttributes().get("caucho.etag");

    if (oldETag != null && !oldETag.equals(etag)) {
      // clear view on JSP change

      root.getChildren().clear();
      root.getFacets().clear();
    }

    root.getAttributes().put("caucho.etag", etag);

    return root;
  }
  public void testLocaleFromVB() throws Exception {
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    facesContext.setViewRoot(root);
    ValueExpression expression =
        application
            .getExpressionFactory()
            .createValueExpression(facesContext.getELContext(), "#{locale}", Object.class);
    request.setAttribute("locale", Locale.CHINESE);
    assertEquals(Locale.getDefault(), root.getLocale());
    root.setValueExpression("locale", expression);
    assertEquals(Locale.CHINESE, root.getLocale());

    // test locale from String
    request.setAttribute("locale", "en");
    assertEquals(new Locale("en"), root.getLocale());
    request.setAttribute("locale", "en_IE");
    assertEquals(new Locale("en", "IE"), root.getLocale());
    request.setAttribute("locale", "en_IE_EURO");
    assertEquals(new Locale("en", "IE", "EURO"), root.getLocale());

    root.setLocale(Locale.CANADA_FRENCH);
    assertEquals(Locale.CANADA_FRENCH, root.getLocale());
  }
 private void callRightLifecycleMethodGivenPhaseId(UIViewRoot root, PhaseId phaseId)
     throws Exception {
   if (phaseId.getOrdinal() == PhaseId.APPLY_REQUEST_VALUES.getOrdinal()) {
     root.processDecodes(facesContext);
   } else if (phaseId.getOrdinal() == PhaseId.PROCESS_VALIDATIONS.getOrdinal()) {
     root.processValidators(facesContext);
   } else if (phaseId.getOrdinal() == PhaseId.UPDATE_MODEL_VALUES.getOrdinal()) {
     root.processUpdates(facesContext);
   } else if (phaseId.getOrdinal() == PhaseId.INVOKE_APPLICATION.getOrdinal()) {
     root.processApplication(facesContext);
   } else if (phaseId.getOrdinal() == PhaseId.RENDER_RESPONSE.getOrdinal()) {
     root.encodeBegin(facesContext);
     root.encodeEnd(facesContext);
   }
 }
  // Test AbortProcessingException support
  public void testAbortProcessingException() {

    // Register three listeners, with the second one set to abort
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    facesContext.setViewRoot(root);
    root.addFacesListener(new TestListener("a", false));
    root.addFacesListener(new TestListener("b", true));
    root.addFacesListener(new TestListener("c", false));

    // Queue two event and check the results
    TestListener.trace(null);
    TestEvent event1 = new TestEvent(root, "1");
    event1.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
    root.queueEvent(event1);
    TestEvent event2 = new TestEvent(root, "2");
    event2.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
    root.queueEvent(event2);
    root.processDecodes(facesContext);
    assertEquals("/a/1/b/1/a/2/b/2", TestListener.trace());
  }
  // Test Events List Clearing
  public void testEventsListClear() {
    UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
    facesContext.setViewRoot(root);
    TestEvent event1, event2, event3, event4 = null;
    event1 = new TestEvent(root, "1");
    event1.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
    root.queueEvent(event1);
    event2 = new TestEvent(root, "2");
    event2.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
    root.queueEvent(event2);
    event3 = new TestEvent(root, "3");
    event3.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
    root.queueEvent(event3);
    event4 = new TestEvent(root, "4");
    event4.setPhaseId(PhaseId.INVOKE_APPLICATION);
    root.queueEvent(event4);
    final Field fields[] = UIViewRoot.class.getDeclaredFields();
    Field field = null;
    List<List> events = null;
    for (int i = 0; i < fields.length; ++i) {
      if ("events".equals(fields[i].getName())) {
        field = fields[i];
        field.setAccessible(true);
        try {
          events = TypedCollections.dynamicallyCastList((List) field.get(root), List.class);
        } catch (Exception e) {
          assertTrue(false);
        }
        break;
      }
    }
    // CASE: renderReponse not set; responseComplete not set;
    // check for existence of events before processDecodes
    checkEventQueuesSizes(events, 1, 1, 1, 1);
    root.processDecodes(facesContext);
    // there should be no events
    checkEventQueuesSizes(events, 0, 1, 1, 1);

    // requeue apply request event
    root.queueEvent(event1);
    // CASE: renderReponse set;
    // check for existence of events before processValidators
    checkEventQueuesSizes(events, 1, 1, 1, 1);
    facesContext.renderResponse();
    root.processValidators(facesContext);
    // there should be no events
    checkEventQueuesSizes(events, 0, 0, 0, 0);

    // reset FacesContext
    facesContext.setRenderResponse(false);
    facesContext.setResponseComplete(false);
    // requeue all events
    root.queueEvent(event1);
    root.queueEvent(event2);
    root.queueEvent(event3);
    root.queueEvent(event4);
    try {
      events = TypedCollections.dynamicallyCastList((List) field.get(root), List.class);
    } catch (Exception e) {
      assertTrue(false);
    }
    // CASE: response set;
    // check for existence of events before processValidators
    checkEventQueuesSizes(events, 1, 1, 1, 1);
    facesContext.renderResponse();
    root.processValidators(facesContext);
    // there should be no events
    checkEventQueuesSizes(events, 0, 0, 0, 0);

    // reset FacesContext
    facesContext.setRenderResponse(false);
    facesContext.setResponseComplete(false);
    // requeue all events
    root.queueEvent(event1);
    root.queueEvent(event2);
    root.queueEvent(event3);
    root.queueEvent(event4);
    try {
      events = TypedCollections.dynamicallyCastList((List) field.get(root), List.class);
    } catch (Exception e) {
      assertTrue(false);
    }
    // CASE: response complete;
    // check for existence of events before processUpdates
    checkEventQueuesSizes(events, 1, 1, 1, 1);
    facesContext.responseComplete();
    root.processUpdates(facesContext);
    // there should be no events
    checkEventQueuesSizes(events, 0, 0, 0, 0);

    // reset FacesContext
    facesContext.setRenderResponse(false);
    facesContext.setResponseComplete(false);
    // requeue all events
    root.queueEvent(event1);
    root.queueEvent(event2);
    root.queueEvent(event3);
    root.queueEvent(event4);
    try {
      events = TypedCollections.dynamicallyCastList((List) field.get(root), List.class);
    } catch (Exception e) {
      assertTrue(false);
    }
    // CASE: response complete;
    // check for existence of events before processApplication
    checkEventQueuesSizes(events, 1, 1, 1, 1);
    facesContext.responseComplete();
    root.processApplication(facesContext);
    // there should be no events
    checkEventQueuesSizes(events, 0, 0, 0, 0);

    // finally, get the internal events list one more time
    // to make sure it is null
    try {
      events = TypedCollections.dynamicallyCastList((List) field.get(root), List.class);
    } catch (Exception e) {
      assertTrue(false);
    }
    assertNull("events", events);
  }
 public void testUninitializedInstance() throws Exception {
   UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
   facesContext.setViewRoot(root);
   assertEquals(javax.faces.render.RenderKitFactory.HTML_BASIC_RENDER_KIT, root.getRenderKitId());
   assertEquals(Locale.getDefault(), root.getLocale());
 }
  public void testPhaseListenerExceptions() throws Exception {
    PhaseId[] ids = {
      PhaseId.APPLY_REQUEST_VALUES,
      PhaseId.PROCESS_VALIDATIONS,
      PhaseId.UPDATE_MODEL_VALUES,
      PhaseId.INVOKE_APPLICATION,
      PhaseId.RENDER_RESPONSE
    };
    Class[] args = new Class[] {PhaseEvent.class};
    MethodExpression beforeExpression =
        facesContext
            .getApplication()
            .getExpressionFactory()
            .createMethodExpression(facesContext.getELContext(), "#{bean.beforePhase}", null, args);
    MethodExpression afterExpression =
        facesContext
            .getApplication()
            .getExpressionFactory()
            .createMethodExpression(facesContext.getELContext(), "#{bean.afterPhase}", null, args);
    for (PhaseId id : ids) {
      UIViewRoot root =
          facesContext.getApplication().getViewHandler().createView(facesContext, null);
      PhaseListenerBean bean = new PhaseListenerBean(id, true, false);
      PhaseListenerBean pl1 = new PhaseListenerBean(id);
      PhaseListenerBean pl2 = new PhaseListenerBean(id);
      facesContext.getExternalContext().getRequestMap().put("bean", bean);
      root.setBeforePhaseListener(beforeExpression);
      root.setAfterPhaseListener(afterExpression);
      root.addPhaseListener(pl1);
      root.addPhaseListener(pl2);

      // validate behavior
      callRightLifecycleMethodGivenPhaseId(root, id);
      assertTrue(bean.isBeforePhaseCalled());
      assertTrue(!bean.isAfterPhaseCalled());
      assertTrue(!pl1.isBeforePhaseCalled());
      assertTrue(!pl1.isAfterPhaseCalled());
      assertTrue(!pl2.isBeforePhaseCalled());
      assertTrue(!pl2.isAfterPhaseCalled());

      // ensure PLs are invoked properly in the case of exceptions
      root = facesContext.getApplication().getViewHandler().createView(facesContext, null);
      bean = new PhaseListenerBean(id);
      pl1 = new PhaseListenerBean(id, true, false);
      pl2 = new PhaseListenerBean(id);
      facesContext.getExternalContext().getRequestMap().put("bean", bean);
      root.setBeforePhaseListener(beforeExpression);
      root.setAfterPhaseListener(afterExpression);
      root.addPhaseListener(pl1);
      root.addPhaseListener(pl2);

      // validate behavior
      callRightLifecycleMethodGivenPhaseId(root, id);
      assertTrue(bean.isBeforePhaseCalled());
      assertTrue(bean.isAfterPhaseCalled());
      assertTrue(pl1.isBeforePhaseCalled());
      assertTrue(!pl1.isAfterPhaseCalled());
      assertTrue(!pl2.isBeforePhaseCalled());
      assertTrue(!pl2.isAfterPhaseCalled());
    }
  }
  public void testAddGetComponentResources() {

    application.addComponent("javax.faces.ComponentResourceContainer", Container.class.getName());
    UIViewRoot root = new UIViewRoot();
    UIOutput resource = new UIOutput();

    // no target argument should result in target being head
    root.addComponentResource(facesContext, resource);
    List<UIComponent> components = root.getComponentResources(facesContext, "head");
    assertNotNull(components);
    assertTrue(components.size() == 1);
    assertTrue(components.get(0) == resource);
    UIOutput resource2 = new UIOutput();
    root.addComponentResource(facesContext, resource2);
    assertTrue(components.size() == 2);
    assertTrue(components.get(1) == resource2);
    root.addComponentResource(facesContext, resource2, "form");
    components = root.getComponentResources(facesContext, "form");
    assertTrue(components.size() == 1);
    root.addComponentResource(facesContext, resource2, "body");
    components = root.getComponentResources(facesContext, "body");
    assertTrue(components.size() == 1);

    // the default implementation masks the facet name values
    // of head and form to ensure there are no collisions with valid
    // facets by the name.  Calling UIViewRoot.getFacet("head") or
    // get("form") will return null.
    assertNull(root.getFacet("head"));
    assertNull(root.getFacet("form"));
    assertNull(root.getFacet("body"));
    assertNotNull(root.getFacet("javax_faces_location_HEAD"));
    assertNotNull(root.getFacet("javax_faces_location_FORM"));
    assertNotNull(root.getFacet("javax_faces_location_BODY"));

    // custom locations will also be masked
    root.addComponentResource(facesContext, resource2, "gt");
    assertNotNull(root.getFacet("javax_faces_location_gt"));
    components = root.getComponentResources(facesContext, "gt");
    assertTrue(components.size() == 1);
  }
Example #28
0
  private boolean sendError(FacesContext context, String lifecycle, Exception e) {
    for (Throwable cause = e; cause != null; cause = cause.getCause()) {
      if (cause instanceof DisplayableException) {
        if (e instanceof RuntimeException) throw (RuntimeException) e;
        else throw new FacesException(e);
      } else if (cause instanceof ServletException) throw new FacesException(e);
      else if (cause instanceof JspException) throw new FacesException(e);
    }

    ExternalContext extContext = context.getExternalContext();
    Object response = extContext.getResponse();

    if (!(response instanceof HttpServletResponse)) {
      context.renderResponse();

      if (e instanceof RuntimeException) throw (RuntimeException) e;
      else throw new RuntimeException(e);
    }

    log.log(Level.WARNING, e.toString(), e);

    HttpServletResponse res = (HttpServletResponse) response;

    try {
      context.renderResponse();
      context.responseComplete();

      res.setStatus(500, "JSF Exception");
      res.setContentType("text/html");

      PrintWriter out = res.getWriter();

      out.println("<body>");

      out.println("<h3>JSF exception detected in " + lifecycle + " phase</h3>");

      String msg = e.getMessage();
      out.println("<span style='color:red;font:bold'>" + Html.escapeHtml(msg) + "</span><br/>");

      out.println("<h3>Context: " + context.getViewRoot() + "</h3>");
      out.println("<code><pre>");

      String errorId = null;

      if (e instanceof FacesException && msg.startsWith("id=")) {
        int p = msg.indexOf(' ');
        errorId = msg.substring(3, p);
      }

      printComponentTree(out, errorId, context, context.getViewRoot(), 0);

      out.println("</pre></code>");

      if (!Alarm.isTest()) {
        out.println("<h3>Stack Trace</h3>");
        out.println("<pre>");
        if (e.getCause() != null) e.getCause().printStackTrace(out);
        else e.printStackTrace(out);
        out.println("</pre>");
      }

      out.println("</body>");

      // clear, so we don't just loop
      Application app = context.getApplication();

      ViewHandler view = app.getViewHandler();

      UIViewRoot viewRoot = context.getViewRoot();

      viewRoot = view.createView(context, viewRoot.getViewId());

      context.setViewRoot(viewRoot);

      // view.writeState(context); // XXX: no need to output state, but review.

      return true;
    } catch (IOException e1) {
      throw new RuntimeException(e);
    }
  }
Example #29
0
  public void execute(FacesContext context) throws FacesException {
    boolean isFiner = log.isLoggable(Level.FINER);

    if (context.getResponseComplete() || context.getRenderResponse()) return;

    beforePhase(context, PhaseId.RESTORE_VIEW);

    try {
      if (isFiner) log.finer("JSF[] before restore view");

      restoreView(context);
    } finally {
      afterPhase(context, PhaseId.RESTORE_VIEW);
    }

    if (context.getResponseComplete() || context.getRenderResponse()) return;

    UIViewRoot viewRoot = context.getViewRoot();

    beforePhase(context, PhaseId.APPLY_REQUEST_VALUES);

    try {
      if (isFiner) log.finer(context.getViewRoot() + " before process decodes");

      viewRoot.processDecodes(context);
    } catch (RuntimeException e) {
      log.log(Level.WARNING, e.toString(), e);
    } finally {
      afterPhase(context, PhaseId.APPLY_REQUEST_VALUES);
    }

    //
    // Process Validations (processValidators)
    //

    if (context.getResponseComplete() || context.getRenderResponse()) return;

    beforePhase(context, PhaseId.PROCESS_VALIDATIONS);

    try {
      if (isFiner) log.finer(context.getViewRoot() + " before process validators");

      viewRoot.processValidators(context);
    } finally {
      afterPhase(context, PhaseId.PROCESS_VALIDATIONS);
    }

    //
    // Update Model Values (processUpdates)
    //

    if (context.getResponseComplete() || context.getRenderResponse()) return;

    beforePhase(context, PhaseId.UPDATE_MODEL_VALUES);

    try {
      if (isFiner) log.finer(context.getViewRoot() + " before process updates");

      viewRoot.processUpdates(context);
    } catch (RuntimeException e) {
      if (sendError(context, "processUpdates", e)) return;
    } finally {
      afterPhase(context, PhaseId.UPDATE_MODEL_VALUES);
    }

    //
    // Invoke Application (processApplication)
    //

    if (context.getResponseComplete() || context.getRenderResponse()) return;

    beforePhase(context, PhaseId.INVOKE_APPLICATION);

    try {
      if (isFiner) log.finer(context.getViewRoot() + " before process application");

      viewRoot.processApplication(context);
    } finally {
      afterPhase(context, PhaseId.INVOKE_APPLICATION);
    }
  }