Java Code Examples for javax.faces.context.FacesContext#setViewRoot()

The following examples show how to use javax.faces.context.FacesContext#setViewRoot() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Test
public void validateSubscriptionId_ShowExternalConfiguratorIsFalse()
        throws Exception {
    // given

    model.setShowExternalConfigurator(false);

    UIViewRoot viewRoot = mock(UIViewRoot.class);
    viewRoot.setViewId(SUBSCRIPTIONADD_VIEWID);

    FacesContext context = mock(FacesContext.class);
    context.setViewRoot(viewRoot);

    // when
    UIComponent toValidate = mock(UIComponent.class);
    doReturn("").when(toValidate).getClientId();
    bean.validateSubscriptionId(context, toValidate,
            new String());

    // then
    assertEquals(Boolean.FALSE,
            Boolean.valueOf(model.isShowExternalConfigurator()));
}
 
Example 2
Source Project: development   File: UiDelegateTest.java    License: Apache License 2.0 6 votes vote down vote up
private void prepareFacesContextforNullUser() {
    final HttpSession session = new HttpSessionStub(Locale.ENGLISH) {
        @Override
        public Object getAttribute(String arg0) {
            return null;
        }
    };
    new HttpServletRequestStub(Locale.ENGLISH) {
        @Override
        public HttpSession getSession() {
            return session;
        }
    };

    FacesContext facesContext = new FacesContextStub(Locale.ENGLISH);
    UIViewRootStub vrStub = new UIViewRootStub() {
        @Override
        public Locale getLocale() {
            return Locale.ENGLISH;
        };
    };
    facesContext.setViewRoot(vrStub);
}
 
Example 3
@Override
public UIViewRoot restoreView(FacesContext context, String viewId, String renderKitId) {
	SerializedView serView = restore();
	
	Node node = (Node) serView.getStructure();
	try {
		UIViewRoot root = (UIViewRoot) node.restore(ClassLoaderUtil.getContextClassLoader(StateManagerTestImpl.class));
		FacesUtil.setRestoreRoot(context, root);
		UIViewRoot old = context.getViewRoot();
		try {
			context.setViewRoot(root);
			root.processRestoreState(context, serView.getState());
		} finally {
			context.setViewRoot(old);
		}
           FacesUtil.setRestoreRoot(context, null);
		return root;
	} catch(Exception e) {
		throw new FacesExceptionEx(e);
	}
}
 
Example 4
@Override
public void handle() throws FacesException {
    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
    while (i.hasNext()) {
        ExceptionQueuedEvent event = i.next();
        ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

        // get the exception from context
        Throwable t = context.getException();

        FacesContext facesContext = FacesContext.getCurrentInstance();

        if (t instanceof ViewExpiredException) {
            try {

                String homeLocation = "/index.xhtml";
                facesContext.setViewRoot(facesContext.getApplication().getViewHandler().createView(facesContext, homeLocation));
                facesContext.getPartialViewContext().setRenderAll(true);
                String messageText = "Your session is expired and data is resetted.";
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageText, messageText);
                facesContext.addMessage(null, message);
                facesContext.renderResponse();

            } finally {
                //remove it from queue
                i.remove();
            }
        }
    }
    //parent handle
    getWrapped().handle();
}
 
Example 5
public void refresh() {
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    ViewHandler viewHandler = application.getViewHandler();
    UIViewRoot viewRoot = viewHandler.createView(context, context
            .getViewRoot().getViewId());
    context.setViewRoot(viewRoot);
    context.renderResponse(); //Optional
}
 
Example 6
public void refresh() {
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    ViewHandler viewHandler = application.getViewHandler();
    UIViewRoot viewRoot = viewHandler.createView(context, context
            .getViewRoot().getViewId());
    context.setViewRoot(viewRoot);
}
 
Example 7
public void refresh() {
      FacesContext context = FacesContext.getCurrentInstance();
      Application application = context.getApplication();
      ViewHandler viewHandler = application.getViewHandler();
      UIViewRoot viewRoot = viewHandler.createView(context, context
           .getViewRoot().getViewId());
      context.setViewRoot(viewRoot);
    //  context.renderResponse(); //Optional
}
 
Example 8
/**
 * @param pageName
 * @param root
 * @param extraParams
 * @return
 * @throws Exception
 */
private FacesContext createContextForPost(String pageName, UIViewRoot root, Map<String, String> extraParams) throws Exception {
    FacesContext contextForPost;
    extraParams.put("view:_id1", ""); // the <form element itself
    //String submittedValue = InputSaveValueTest.getSubmittedValue(instance, "");
    //extraParams.put("view:_id1:input1", submittedValue);
    HttpServletRequest request = TestProject.createRequest(this, pageName, extraParams);
    contextForPost = TestProject.createFacesContext(this,request);
    ResponseBuffer.initContext(contextForPost);
    contextForPost.setViewRoot(root);
    return contextForPost;
}
 
Example 9
public static UIViewRoot loadEmptyPage(AbstractXspTest test, FacesContext context) throws Exception{
    String pageName = "/pages/pregenerated/empty.xsp";
    Application application = lazyApplication(test);
    ViewHandler viewHandler = application.getViewHandler();
    UIViewRoot root = viewHandler.createView(context, pageName);
    if( null == root ){
        throw new RuntimeException("JUnit test could not load the empty page "+pageName);
    }
    context.setViewRoot(root);
    return root;
}
 
Example 10
public static UIViewRoot loadView(AbstractXspTest test,
        FacesContext context, String viewId) throws Exception{
    
    String pageName = toPageName(viewId);
    Application application = lazyApplication(test);
    ViewHandler viewHandler = application.getViewHandler();
    UIViewRoot root = viewHandler.createView(context, pageName);
    if( null != root ){
        context.setViewRoot(root);
    }
    return root;
}
 
Example 11
public void refresh() {
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    ViewHandler viewHandler = application.getViewHandler();
    UIViewRoot viewRoot = viewHandler.createView(context, context
            .getViewRoot().getViewId());
    context.setViewRoot(viewRoot);
    context.renderResponse(); //Optional
}
 
Example 12
public void testChangeDynamicContent() throws Exception {
	
       // first create the view using a regular get command
       Application app = TestProject.createApplication(this);
       FacesContext context = TestProject.createFacesContext(this); // [0]first get request
       String fullViewName = "/pages/testChangeDynamicContentAction.xsp";
       UIViewRoot root = TestProject.loadView(this, context, fullViewName);
       
       // verify the test has not been misconfigured
       AssertUtil.assertInstanceOf(DesignerApplicationEx.class, app);
       
       String fails = "";
       fails += checkComputedFieldPresence(root, 0);
       
       // the next request created is as explained in the method below
       for (int i = 1; i < expectedArr.length; i++) {
           int requestNum = i;
           
           Map<String, String> extraParams = new HashMap<String, String>();
           extraParams.put("view:_id1", "");
           extraParams.put("$$xspsubmitid", (String)expectedArr[requestNum][0]);
           HttpServletRequest request = TestProject.createRequest(this, fullViewName, extraParams);
           FacesContext contextForPost = TestProject.createFacesContext(this,request);
           ResponseBuffer.initContext(contextForPost);
           contextForPost.setViewRoot(root);
           
           // now fake the JSF lifecycle
           root.processDecodes(contextForPost);
           root.processValidators(contextForPost);
           if( contextForPost.getMessages().hasNext() ){
               fail("messages found after validate");
           }
           root.processUpdates(contextForPost);
           root.processApplication(contextForPost);
           
           if( contextForPost.getMessages().hasNext() ) fail("messages found");
           
           fails += checkComputedFieldPresence(root, requestNum);
           
           Boolean expectActionFoo = (Boolean) expectedArr[requestNum][4];
           if( null != expectActionFoo ){
               UIComponent actionDiv = findComponent(root, "actionDiv");
               if( null == actionDiv ){
                   fails += "[" +requestNum+"] unexpected absence of actionDiv in control tree.\n";
                   continue;
               }
               String pageSnippet = ResponseBuffer.encode(actionDiv, contextForPost);
               String actionValue = expectActionFoo?"foo":"";
               AssertUtil.assertContains(
                       pageSnippet,
                       "<span id=\"view:_id1:dynamicContent1:computedField4\">"
                               + actionValue + "</span>");
           }
       }
       if( fails.length() > 0 ){
           fail(XspTestUtil.getMultilineFailMessage(fails));
       }
}
 
Example 13
public static void tearDown(AbstractXspTest test){
    Map<String, Object> localVars = test.getTestLocalVars();
    FacesContext context = (FacesContext) localVars.remove("facesContext");
    if( null != context ){
        context.setViewRoot(null);
        new FacesContextImpl(){
            {
                setCurrentInstance(null);
            }
        }.getClass(); // call getClass to prevent Object is never used compile warning
    }
    FacesController controller = (FacesController) localVars.remove("controller");
    if( null != controller){
        controller.destroy();
    }
    BootStrap bootstrap = (BootStrap) localVars.remove("bootStrap");
    if( null != bootstrap ){
        ServletContext servletContext = (ServletContext) localVars.remove("servletContext");
        bootstrap.destroy(servletContext);
        // note, if you don't destroy the bootstrap then 
        // FactoryFinder.getFactory("javax.faces.application.ApplicationFactory");
        // hangs around, so the old application instance is used in the next
        // JUnit test and the managed beans don't resolve.
    }
    FacesSharableRegistry registry = (FacesSharableRegistry) localVars.remove("registry");
    if( null != registry ){
        // prevent unused local variable warning
        registry.getClass();
    }
    ApplicationEx app = (ApplicationEx) localVars.remove("application");
    if( null != app ){
        // prevent unused local variable warning
        app.getClass();
    }
    TestFrameworkPlatform platform = (TestFrameworkPlatform) localVars.remove("platform");
    if( null != platform ){
        // revert to the previous type of platform - stop using a TestFrameworkPlatform
        Class<?> defaultPlatformClass = (Class<?>) localVars.remove("platformShadowedClass");
        try{
            defaultPlatformClass.newInstance();
        }
        catch (Exception e) {
            throw new RuntimeException("Problem restoring the default platform.", e);
        }
    }
}
 
Example 14
@Override
public void handle() throws FacesException
{
    lazyInit();
    Iterator<ExceptionQueuedEvent> exceptionQueuedEventIterator = getUnhandledExceptionQueuedEvents().iterator();

    while (exceptionQueuedEventIterator.hasNext())
    {
        ExceptionQueuedEventContext exceptionQueuedEventContext =
                (ExceptionQueuedEventContext) exceptionQueuedEventIterator.next().getSource();

        @SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
        Throwable throwable = exceptionQueuedEventContext.getException();

        String viewId = null;

        if (!isExceptionToHandle(throwable))
        {
            continue;
        }

        FacesContext facesContext = exceptionQueuedEventContext.getContext();
        Flash flash = facesContext.getExternalContext().getFlash();

        if (throwable instanceof ViewExpiredException)
        {
            viewId = ((ViewExpiredException) throwable).getViewId();
        }
        else if (throwable instanceof ContextNotActiveException)
        {
            //the error page uses a cdi scope which isn't active as well
            //(it's recorded below - see flash.put(throwable.getClass().getName(), throwable);)
            if (flash.containsKey(ContextNotActiveException.class.getName()))
            {
                //TODO show it in case of project-stage development
                break;
            }

            if (facesContext.getViewRoot() != null)
            {
                viewId = facesContext.getViewRoot().getViewId();
            }
            else
            {
                viewId = BeanProvider.getContextualReference(ViewConfigResolver.class)
                        //has to return a value otherwise this handler wouldn't be active
                        .getDefaultErrorViewConfigDescriptor().getViewId();
            }
        }

        if (viewId != null)
        {
            UIViewRoot uiViewRoot = facesContext.getApplication().getViewHandler().createView(facesContext, viewId);

            if (uiViewRoot == null)
            {
                continue;
            }

            if (facesContext.isProjectStage(javax.faces.application.ProjectStage.Development) ||
                    ProjectStageProducer.getInstance().getProjectStage() == ProjectStage.Development ||
                    ProjectStageProducer.getInstance().getProjectStage() instanceof TestStage)
            {
                throwable.printStackTrace();
            }

            facesContext.setViewRoot(uiViewRoot);
            exceptionQueuedEventIterator.remove();

            //record the current exception -> to check it at the next call or to use it on the error-page
            flash.put(throwable.getClass().getName(), throwable);
            flash.keep(throwable.getClass().getName());

            this.viewNavigationHandler.navigateTo(DefaultErrorView.class);

            break;
        }
    }

    this.wrapped.handle();
}