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); } }
public void testComponentAnnotatations() throws Exception { getFacesContext() .getAttributes() .put("javax.faces.IS_POSTBACK_AND_RESTORE_VIEW", Boolean.FALSE); Application application = getFacesContext().getApplication(); application.addComponent("CustomInput", CustomOutput.class.getName()); CustomOutput c = (CustomOutput) application.createComponent("CustomInput"); CustomOutput c2 = (CustomOutput) application.createComponent("CustomInput"); UIViewRoot root = getFacesContext().getViewRoot(); root.getChildren().add(c); root.getChildren().add(c2); assertTrue(c.getEvent() instanceof AfterAddToParentEvent); assertTrue(c2.getEvent() instanceof AfterAddToParentEvent); List<UIComponent> headComponents = root.getComponentResources(getFacesContext(), "head"); System.out.println(headComponents.toString()); assertTrue(headComponents.size() == 1); assertTrue(headComponents.get(0) instanceof UIOutput); assertTrue("test".equals(headComponents.get(0).getAttributes().get("library"))); List<UIComponent> bodyComponents = root.getComponentResources(getFacesContext(), "body"); assertTrue(bodyComponents.size() == 1); assertTrue(bodyComponents.get(0) instanceof UIOutput); assertTrue("test.js".equals(bodyComponents.get(0).getAttributes().get("name"))); assertTrue("body".equals(bodyComponents.get(0).getAttributes().get("target"))); application.addComponent("CustomInput2", CustomOutput2.class.getName()); CustomOutput2 c3 = (CustomOutput2) application.createComponent("CustomInput2"); root.getChildren().add(c3); assertTrue(c3.getEvent() instanceof AfterAddToParentEvent); c3.reset(); c3.encodeAll(getFacesContext()); assertTrue(c3.getEvent() instanceof BeforeRenderEvent); }
public void testResourceBundle() throws Exception { ResourceBundle rb = null; UIViewRoot root = new UIViewRoot(); root.setLocale(Locale.ENGLISH); getFacesContext().setViewRoot(root); // negative test, non-existant rb rb = application.getResourceBundle(getFacesContext(), "bogusName"); assertNull(rb); // basic test, existing rb rb = application.getResourceBundle(getFacesContext(), "testResourceBundle"); assertNotNull(rb); String value = rb.getString("value1"); assertEquals("Jerry", value); // switch locale to German getFacesContext().getViewRoot().setLocale(Locale.GERMAN); rb = application.getResourceBundle(getFacesContext(), "testResourceBundle"); assertNotNull(rb); value = rb.getString("value1"); assertEquals("Bernhard", value); // switch to a different rb rb = application.getResourceBundle(getFacesContext(), "testResourceBundle2"); assertNotNull(rb); value = rb.getString("label"); assertEquals("Abflug", value); }
public void setUp() { super.setUp(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setViewId("viewId"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); }
@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); }
public static void setLocale(FacesContext context, Locale locale) { UIViewRoot viewRoot = context.getViewRoot(); if (viewRoot != null) { viewRoot.setLocale(locale); } }
public static Locale getLocale(FacesContext context) { Locale locale = null; UIViewRoot viewRoot = context.getViewRoot(); if (viewRoot != null) locale = viewRoot.getLocale(); if (locale == null) locale = Locale.getDefault(); return locale; }
/** * Build the view. * * @param ctx the {@link FacesContext} for the current request * @param view the {@link UIViewRoot} to populate based of the Facelet template * @throws IOException if an error occurs building the view. */ @Override public void buildView(FacesContext ctx, UIViewRoot view) throws IOException { if (Util.isViewPopulated(ctx, view)) { return; } updateStateSavingType(ctx, view.getViewId()); view.setViewId(view.getViewId()); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Building View: " + view.getViewId()); } if (faceletFactory == null) { ApplicationAssociate associate = ApplicationAssociate.getInstance(ctx.getExternalContext()); faceletFactory = associate.getFaceletFactory(); assert (faceletFactory != null); } RequestStateManager.set(ctx, RequestStateManager.FACELET_FACTORY, faceletFactory); Facelet f = faceletFactory.getFacelet(view.getViewId()); // populate UIViewRoot f.apply(ctx, view); doPostBuildActions(view); Util.setViewPopulated(ctx, view); }
private void deliverPostRestoreStateEvent(FacesContext facesContext) throws FacesException { UIViewRoot root = facesContext.getViewRoot(); final PostRestoreStateEvent postRestoreStateEvent = new PostRestoreStateEvent(root); try { Set<VisitHint> hints = EnumSet.of(VisitHint.SKIP_ITERATION); VisitContext visitContext = VisitContext.createVisitContext(facesContext, null, hints); root.visitTree( visitContext, new VisitCallback() { public VisitResult visit(VisitContext context, UIComponent target) { postRestoreStateEvent.setComponent(target); target.processEvent(postRestoreStateEvent); //noinspection ReturnInsideFinallyBlock return VisitResult.ACCEPT; } }); } catch (AbortProcessingException e) { facesContext .getApplication() .publishEvent( facesContext, ExceptionQueuedEvent.class, new ExceptionQueuedEventContext(facesContext, e, null, PhaseId.RESTORE_VIEW)); } }
/** * @param ctx FacesContext. * @param viewId the view ID to check or null if viewId is unknown. * @return <code>true</code> if partial state saving should be used for the specified view ID, * otherwise <code>false</code> */ public boolean isPartialStateSaving(FacesContext ctx, String viewId) { // track UIViewRoot changes UIViewRoot root = ctx.getViewRoot(); UIViewRoot refRoot = viewRootRef.get(); if (root != refRoot) { // set weak reference to current viewRoot this.viewRootRef = new WeakReference<UIViewRoot>(root); // On first call in restore phase, viewRoot is null, so we treat the first // change to not null not as a changing viewRoot. if (refRoot != null) { // view root changed in request processing - force usage of a // new AddRemoveListener instance for the new viewId ... modListener = null; // ... and also force check for partial state saving for the new viewId partialLocked = false; } } if (!partialLocked) { if (viewId == null) { if (root != null) { viewId = root.getViewId(); } else { // View root has not yet been initialized. Check to see whether // the target view id has been stashed away for us. viewId = (String) ctx.getAttributes().get(RIConstants.VIEWID_KEY_NAME); } } partial = stateInfo.usePartialStateSaving(viewId); partialLocked = true; } return partial; }
/** @see javax.faces.context.FacesContext#getRenderKit() */ public RenderKit getRenderKit() { assertNotReleased(); UIViewRoot vr = getViewRoot(); if (vr == null) { return (null); } String renderKitId = vr.getRenderKitId(); if (renderKitId == null) { return null; } if (renderKitId.equals(lastRkId)) { return lastRk; } else { lastRk = rkFactory.getRenderKit(this, renderKitId); if (lastRk == null) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log( Level.SEVERE, "Unable to locate renderkit " + "instance for render-kit-id {0}. Using {1} instead.", new String[] {renderKitId, RenderKitFactory.HTML_BASIC_RENDER_KIT}); } } lastRkId = renderKitId; return lastRk; } }
public ComponentWrapper startElement( FacesContext context, ComponentWrapper parent, String uri, String localName, String qName, Attributes attributes) throws IOException { UIViewRoot root = context.getViewRoot(); HtmlOutputLink link = (HtmlOutputLink) context.getApplication().createComponent(HtmlOutputLink.COMPONENT_TYPE); link.setId(root.createUniqueId()); parent.getComponent().getChildren().add(link); link.setTarget("_parent"); ToolCategoryComponent parentCategoryComponent = findParentCategory(parent); ToolComponent parentComponent = findParentTool(parent); if (parentComponent.getPage() != null) { // Resolve the site_type of the form /portal/category/<siteId>/<categoryKey>/<optionalToolId> String url = parentCategoryComponent.getContext() + "/category/" + parentCategoryComponent.getSiteId() + "/" + parentCategoryComponent.getToolCategory().getKey() + "/" + parentComponent.getPage().getId(); link.setValue(url); } return new ComponentWrapper(parent, link, this); }
/** Test the built-in conversion for those renderers that have it. */ public void testEmptyStrings() { UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setLocale(Locale.US); UIInput text = new UIInput(), hidden = new UIInput(), secret = new UIInput(); text.setId("text"); hidden.setId("hidden"); secret.setId("secret"); text.setRendererType("Text"); hidden.setRendererType("Hidden"); secret.setRendererType("Secret"); root.getChildren().add(text); root.getChildren().add(hidden); root.getChildren().add(secret); TextRenderer textRenderer = new TextRenderer(); HiddenRenderer hiddenRenderer = new HiddenRenderer(); SecretRenderer secretRenderer = new SecretRenderer(); try { textRenderer.decode(getFacesContext(), text); hiddenRenderer.decode(getFacesContext(), hidden); secretRenderer.decode(getFacesContext(), secret); } catch (Throwable e) { assertTrue(false); } assertTrue(text.isValid()); assertTrue(hidden.isValid()); assertTrue(secret.isValid()); }
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); } }
/** * Installs a <code>SystemEventListener</code> on the <code>UIViewRoot</code> to track components * added to or removed from the view. */ public void startTrackViewModifications(FacesContext ctx, UIViewRoot root) { if (modListener == null) { modListener = new AddRemoveListener(ctx); root.subscribeToViewEvent(PostAddToViewEvent.class, modListener); root.subscribeToViewEvent(PreRemoveFromViewEvent.class, modListener); } setTrackViewModifications(true); }
protected Map<String, Object> getViewMap() { UIViewRoot viewRoot = getViewRoot(); if (viewRoot != null) { return viewRoot.getViewMap(true); } return null; }
/** * Inspect the annotations in the ViewConfigStore, enforcing any restrictions applicable to this * phase * * @param event * @param phaseIdType */ private void performObservation(PhaseEvent event, PhaseIdType phaseIdType) { UIViewRoot viewRoot = (UIViewRoot) event.getFacesContext().getViewRoot(); List<? extends Annotation> restrictionsForPhase = getRestrictionsForPhase(phaseIdType, viewRoot.getViewId()); if (restrictionsForPhase != null) { log.debugf("Enforcing on phase %s", phaseIdType); enforce(event.getFacesContext(), viewRoot, restrictionsForPhase); } }
/** Constructor. */ public DynamicParentComponent() { setRendererType("com.sun.faces.test.agnostic.statesaving.basic.DynamicParentComponentRenderer"); FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); if (!context.isPostback()) { root.subscribeToViewEvent(PreRenderViewEvent.class, this); } }
private int getFlatSize() { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); UIData outerData = (UIData) root.findComponent(list.getOuterDataName()), innerData = (UIData) root.findComponent(list.getInnerDataName()); int size = outerData.getRowCount() * innerData.getRowCount(); return size; }
/** @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent) */ public void beforePhase(PhaseEvent event) { LOGGER.debug("Before phase {0}", event.getPhaseId()); if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) { UIViewRoot viewRoot = event.getFacesContext().getViewRoot(); if (viewRoot != null) { LOGGER.debug( "Subscribing to event {0} with listener {1}", PRERENDER_EVENT_CLASS, HOOKING_EVENT); viewRoot.subscribeToEvent(PRERENDER_EVENT_CLASS, HOOKING_EVENT); } } }
// // Methods from TestCase // public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); application = aFactory.getApplication(); UIViewRoot viewRoot = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); viewRoot.setViewId("viewId"); viewRoot.setLocale(Locale.US); getFacesContext().setViewRoot(viewRoot); }
public void inserir() { EntityManager manager = this.getManager(); FornecedorDao fncDao = new FornecedorDaoJpa(manager); fncDao.save(fornecedor); this.mensagens.info(); FacesContext facesContext = FacesContext.getCurrentInstance(); UIViewRoot uiViewRoot = facesContext.getViewRoot(); limparComponente.cleanSubmittedValues(uiViewRoot.findComponent("form:painel")); /*return "/cadastro/fornecedor.xhtml";*/ }
/** Reload the current active page. */ public static void reloadPage() { FacesContext context = FacesContext.getCurrentInstance(); String viewId = context.getViewRoot().getViewId(); ViewHandler handler = context.getApplication().getViewHandler(); UIViewRoot root = handler.createView(context, viewId); root.setViewId(viewId); context.setViewRoot(root); }
/** * @see javax.faces.view.ViewDeclarationLanguage#renderView(javax.faces.context.FacesContext, * javax.faces.component.UIViewRoot) */ public void renderView(FacesContext ctx, UIViewRoot viewToRender) throws IOException { // suppress rendering if "rendered" property on the component is // false if (!viewToRender.isRendered()) { return; } // log request if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Rendering View: " + viewToRender.getViewId()); } WriteBehindStateWriter stateWriter = null; try { // Only build the view if this view has not yet been built. if (!Util.isViewPopulated(ctx, viewToRender)) { this.buildView(ctx, viewToRender); } // setup writer and assign it to the ctx ResponseWriter origWriter = ctx.getResponseWriter(); if (origWriter == null) { origWriter = createResponseWriter(ctx); } stateWriter = new WriteBehindStateWriter(origWriter, ctx, responseBufferSize); ResponseWriter writer = origWriter.cloneWithWriter(stateWriter); ctx.setResponseWriter(writer); // render the view to the response writer.startDocument(); viewToRender.encodeAll(ctx); writer.endDocument(); // finish writing writer.close(); boolean writtenState = stateWriter.stateWritten(); // flush to origWriter if (writtenState) { stateWriter.flushToWriter(); } } catch (FileNotFoundException fnfe) { this.handleFaceletNotFound(ctx, viewToRender.getViewId(), fnfe.getMessage()); } catch (Exception e) { this.handleRenderException(ctx, e); } finally { if (stateWriter != null) stateWriter.release(); } }
@Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); UIViewRoot viewRoot = context.getViewRoot(); ListIterator iter = (viewRoot.getComponentResources(context, "body")).listIterator(); while (iter.hasNext()) { UIComponent resource = (UIComponent) iter.next(); resource.encodeAll(context); } RenderKitUtils.renderUnhandledMessages(context); writer.endElement("body"); }
/** * @see javax.faces.view.ViewDeclarationLanguage#createView(javax.faces.context.FacesContext, * String) * @return */ @Override public UIViewRoot createView(FacesContext ctx, String viewId) { if (UIDebug.debugRequest(ctx)) { UIViewRoot root = (UIViewRoot) ctx.getApplication().createComponent(UIViewRoot.COMPONENT_TYPE); root.setViewId(viewId); return root; } return super.createView(ctx, viewId); }
/** * This is a separate method to account for handling the content after the view tag. * * <p>Create a new ResponseWriter around this response's Writer. Set it into the FacesContext, * saving the old one aside. * * <p>call encodeBegin(), encodeChildren(), encodeEnd() on the argument <code>UIViewRoot</code>. * * <p>Restore the old ResponseWriter into the FacesContext. * * <p>Write out the after view content to the response's writer. * * <p>Flush the response buffer, and remove the after view content from the request scope. * * @param context the <code>FacesContext</code> for the current request * @param viewToRender the view to render * @throws java.io.IOException if an error occurs rendering the view to the client * @throws javax.faces.FacesException if some error occurs within the framework processing */ private void doRenderView(FacesContext context, UIViewRoot viewToRender) throws IOException { if (null != associate) { associate.responseRendered(); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "About to render view " + viewToRender.getViewId()); } viewToRender.encodeAll(context); }
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); } } }
/** @see FacesContext#setViewRoot(javax.faces.component.UIViewRoot) */ public void setViewRoot(UIViewRoot root) { assertNotReleased(); Util.notNull("root", root); if (viewRoot != null && !viewRoot.equals(root)) { Map<String, Object> viewMap = viewRoot.getViewMap(false); if (viewMap != null) { viewRoot.getViewMap().clear(); } } viewRoot = root; }
/** * @param context the <code>FacesContext</code> for the current request * @return the Locale from the UIViewRoot, the the value of Locale.getDefault() */ public static Locale getLocaleFromContextOrSystem(FacesContext context) { Locale result, temp = Locale.getDefault(); UIViewRoot root; result = temp; if (null != context) { if (null != (root = context.getViewRoot())) { if (null == (result = root.getLocale())) { result = temp; } } } return result; }