From ebf6a08c2fa8166aac3dbe32da0242e68495433f Mon Sep 17 00:00:00 2001 From: arjantijms Date: Tue, 7 Sep 2021 23:09:33 +0200 Subject: [PATCH] Some code cleaning Signed-off-by: arjantijms --- .../application/ApplicationAssociate.java | 8 +- .../view/FaceletViewHandlingStrategy.java | 112 ++++++------------ .../application/view/MultiViewHandler.java | 24 ++-- .../application/view/ViewMetadataImpl.java | 61 +++++----- .../sun/faces/lifecycle/RestoreViewPhase.java | 28 +++-- .../faces/application/ViewHandler.java | 5 +- 6 files changed, 95 insertions(+), 143 deletions(-) diff --git a/impl/src/main/java/com/sun/faces/application/ApplicationAssociate.java b/impl/src/main/java/com/sun/faces/application/ApplicationAssociate.java index c08930e52d..3ddd01f86d 100644 --- a/impl/src/main/java/com/sun/faces/application/ApplicationAssociate.java +++ b/impl/src/main/java/com/sun/faces/application/ApplicationAssociate.java @@ -636,7 +636,7 @@ public void relateUrlToDefiningDocumentInJar(URL url, String definingDocumentId) definingDocumentIdsToTruncatedJarUrls.put(definingDocumentId, candidate); } - protected DefaultFaceletFactory createFaceletFactory(FacesContext ctx, Compiler compiler, WebConfiguration webConfig) { + protected DefaultFaceletFactory createFaceletFactory(FacesContext context, Compiler compiler, WebConfiguration webConfig) { // refresh period boolean isProduction = applicationImpl.getProjectStage() == Production; @@ -660,7 +660,7 @@ protected DefaultFaceletFactory createFaceletFactory(FacesContext ctx, Compiler resolver = (ResourceResolver) ReflectionUtil.decorateInstance(resolverName, ResourceResolver.class, resolver); } else { - Set> resourceResolvers = getAnnotatedClasses(ctx).get(FaceletsResourceResolver.class); + Set> resourceResolvers = getAnnotatedClasses(context).get(FaceletsResourceResolver.class); if (null != resourceResolvers && !resourceResolvers.isEmpty()) { Class resolverClass = resourceResolvers.iterator().next(); if (resourceResolvers.size() > 1 && LOGGER.isLoggable(SEVERE)) { @@ -675,7 +675,7 @@ protected DefaultFaceletFactory createFaceletFactory(FacesContext ctx, Compiler // and the use of this ResousrecResolver for Composite Components // is acceptable. if (resolver != defaultResourceResolver && webConfig.isOptionEnabled(EnableFaceletsResourceResolverResolveCompositeComponents)) { - ctx.getExternalContext().getApplicationMap().put(NON_DEFAULT_RESOURCE_RESOLVER_PARAM_NAME, resolver); + context.getExternalContext().getApplicationMap().put(NON_DEFAULT_RESOURCE_RESOLVER_PARAM_NAME, resolver); } FaceletCache cache = null; @@ -703,7 +703,7 @@ protected DefaultFaceletFactory createFaceletFactory(FacesContext ctx, Compiler } DefaultFaceletFactory toReturn = new DefaultFaceletFactory(); - toReturn.init(compiler, resolver, period, cache); + toReturn.init(context, compiler, resolver, period, cache); return toReturn; } diff --git a/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java b/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java index 4e24926169..9a76eea209 100644 --- a/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java +++ b/impl/src/main/java/com/sun/faces/application/view/FaceletViewHandlingStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at @@ -23,6 +23,7 @@ import static com.sun.faces.config.WebConfiguration.WebContextInitParameter.FaceletsViewMappings; import static com.sun.faces.config.WebConfiguration.WebContextInitParameter.StateSavingMethod; import static com.sun.faces.context.StateContext.getStateContext; +import static com.sun.faces.facelets.tag.ui.UIDebug.debugRequest; import static com.sun.faces.renderkit.RenderKitUtils.getResponseStateManager; import static com.sun.faces.util.ComponentStruct.ADD; import static com.sun.faces.util.ComponentStruct.REMOVE; @@ -273,7 +274,7 @@ public UIViewRoot createView(FacesContext ctx, String viewId) { notNull("context", ctx); notNull("viewId", viewId); - if (UIDebug.debugRequest(ctx)) { + if (debugRequest(ctx)) { UIViewRoot root = (UIViewRoot) ctx.getApplication().createComponent(COMPONENT_TYPE); root.setViewId(viewId); return root; @@ -381,8 +382,8 @@ public void renderView(FacesContext ctx, UIViewRoot viewToRender) throws IOExcep try { // Only build the view if this view has not yet been built. if (!isViewPopulated(ctx, viewToRender)) { - ViewDeclarationLanguage vdl = vdlFactory.getViewDeclarationLanguage(viewToRender.getViewId()); - vdl.buildView(ctx, viewToRender); + vdlFactory.getViewDeclarationLanguage(viewToRender.getViewId()) + .buildView(ctx, viewToRender); } // Setup writer and assign it to the ctx @@ -403,8 +404,7 @@ public void renderView(FacesContext ctx, UIViewRoot viewToRender) throws IOExcep getSession(ctx); } - Writer outputWriter = extContext.getResponseOutputWriter(); - stateWriter = new WriteBehindStateWriter(outputWriter, ctx, responseBufferSize); + stateWriter = new WriteBehindStateWriter(extContext.getResponseOutputWriter(), ctx, responseBufferSize); ResponseWriter writer = origWriter.cloneWithWriter(stateWriter); ctx.setResponseWriter(writer); @@ -415,25 +415,23 @@ public void renderView(FacesContext ctx, UIViewRoot viewToRender) throws IOExcep try { ctx.getExternalContext().getFlash().doPostPhaseActions(ctx); } catch (UnsupportedOperationException uoe) { - if (LOGGER.isLoggable(FINE)) { - LOGGER.fine("ExternalContext.getFlash() throw UnsupportedOperationException -> Flash unavailable"); - } + LOGGER.fine("ExternalContext.getFlash() throw UnsupportedOperationException -> Flash unavailable"); } } else { if (ctx.isProjectStage(Development)) { FormOmittedChecker.check(ctx); } - // render the XML declaration to the response + // Render the XML declaration to the response String xmlDecl = getXMLDECLFromFacesContextAttributes(ctx); - if (null != xmlDecl) { + if (xmlDecl != null) { // Do not escape. writer.writePreamble(xmlDecl); } - // render the DOCTYPE declaration to the response + // Render the DOCTYPE declaration to the response Doctype doctype = viewToRender.getDoctype(); - if (null != doctype) { + if (doctype != null) { if (doctype instanceof UIComponent) { ((UIComponent) doctype).encodeAll(ctx); // E.g. HtmlDoctype + DoctypeRenderer } else { @@ -443,15 +441,13 @@ public void renderView(FacesContext ctx, UIViewRoot viewToRender) throws IOExcep writer.append('\n'); } - // render the view to the response + // Render the view to the response writer.startDocument(); viewToRender.encodeAll(ctx); try { ctx.getExternalContext().getFlash().doPostPhaseActions(ctx); } catch (UnsupportedOperationException uoe) { - if (LOGGER.isLoggable(FINE)) { - LOGGER.fine("ExternalContext.getFlash() throw UnsupportedOperationException -> Flash unavailable"); - } + LOGGER.fine("ExternalContext.getFlash() throw UnsupportedOperationException -> Flash unavailable"); } writer.endDocument(); } @@ -505,11 +501,9 @@ public StateManagementStrategy getStateManagementStrategy(FacesContext context, */ @Override public BeanInfo getComponentMetadata(FacesContext context, Resource ccResource) { - DefaultFaceletFactory factory = (DefaultFaceletFactory) RequestStateManager.get(context, FACELET_FACTORY); - DefaultFaceletFactory ourFactory = factory; - if (ourFactory.needsToBeRefreshed(ccResource.getURL())) { + if (factory.needsToBeRefreshed(ccResource.getURL())) { metadataCache.remove(ccResource); } @@ -859,7 +853,6 @@ protected void initialize() { * Initialize mappings, during the first request. */ protected void initializeMappings() { - String viewMappings = webConfig.getOptionValue(FaceletsViewMappings); if (viewMappings != null && viewMappings.length() > 0) { Map appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap(); @@ -897,9 +890,9 @@ protected void initializeMappings() { * @throws IOException if the writer cannot be created */ protected ResponseWriter createResponseWriter(FacesContext context) throws IOException { - ExternalContext extContext = context.getExternalContext(); RenderKit renderKit = context.getRenderKit(); + // Avoid a cryptic NullPointerException when the renderkit ID // is incorrectly set if (renderKit == null) { @@ -991,7 +984,6 @@ protected void handleFaceletNotFound(FacesContext context, String viewId, String * @return the encoding to be used for this response */ protected String getResponseEncoding(FacesContext context, String orig) { - String encoding = orig; // 1. get it from request @@ -999,7 +991,7 @@ protected String getResponseEncoding(FacesContext context, String orig) { // 2. get it from the session if (encoding == null) { - if (null != context.getExternalContext().getSession(false)) { + if (context.getExternalContext().getSession(false) != null) { Map sessionMap = context.getExternalContext().getSessionMap(); encoding = (String) sessionMap.get(CHARACTER_ENCODING_KEY); if (LOGGER.isLoggable(FINEST)) { @@ -1044,13 +1036,12 @@ protected String getResponseEncoding(FacesContext context, String orig) { * @return the content type to be used for this response */ protected String getResponseContentType(FacesContext context, String orig) { - String contentType = orig; // See if we need to override the contentType - Map m = context.getAttributes(); - if (m.containsKey("facelets.ContentType")) { - contentType = (String) m.get("facelets.ContentType"); + Map contextAttributes = context.getAttributes(); + if (contextAttributes.containsKey("facelets.ContentType")) { + contentType = (String) contextAttributes.get("facelets.ContentType"); if (LOGGER.isLoggable(FINEST)) { LOGGER.finest("Facelet specified alternate contentType '" + contentType + "'"); } @@ -1059,9 +1050,7 @@ protected String getResponseContentType(FacesContext context, String orig) { // Safety check if (contentType == null) { contentType = "text/html"; - if (LOGGER.isLoggable(FINEST)) { - LOGGER.finest("ResponseWriter created had a null ContentType, defaulting to text/html"); - } + LOGGER.finest("ResponseWriter created had a null ContentType, defaulting to text/html"); } return contentType; @@ -1202,10 +1191,9 @@ private String getCompositeComponentName(UIComponent compositeComponent) { if (library != null) { return "Composite Component: " + name + ", library: " + library; - } else { - return "Composite Component: " + name; } + return "Composite Component: " + name; } private void startTrackViewModifications(FacesContext ctx, UIViewRoot root) { @@ -1238,7 +1226,6 @@ private void markInitialState(final UIComponent component) { } private void retargetHandler(FacesContext context, AttachedObjectHandler handler, UIComponent targetComponent) { - if (UIComponent.isCompositeComponent(targetComponent)) { // RELEASE_PENDING Not keen on calling CompositeComponentTagHandler here.... List nHandlers = CompositeComponentTagHandler.getAttachedObjectHandlers(targetComponent); @@ -1284,7 +1271,6 @@ public Iterator iterator() { @Override public boolean hasNext() { - if (curIndex != -1 && curIndex < descriptors.length) { int idx = curIndex; @@ -1311,16 +1297,12 @@ public boolean hasNext() { @Override public CompCompInterfaceMethodMetadata next() { - return new CompCompInterfaceMethodMetadata(descriptors[curIndex++]); - } @Override public void remove() { - throw new UnsupportedOperationException(); - } private boolean shouldSkip(PropertyDescriptor pd) { @@ -1343,14 +1325,12 @@ private boolean shouldSkip(PropertyDescriptor pd) { */ private static final class CompCompInterfaceMethodMetadata { - private final PropertyDescriptor pd; + private final PropertyDescriptor propertyDescriptor; // -------------------------------------------------------- Constructors - CompCompInterfaceMethodMetadata(PropertyDescriptor pd) { - - this.pd = pd; - + CompCompInterfaceMethodMetadata(PropertyDescriptor propertyDescriptor) { + this.propertyDescriptor = propertyDescriptor; } // ------------------------------------------------------ Public Methods @@ -1360,13 +1340,12 @@ private static final class CompCompInterfaceMethodMetadata { * @return the method-signature for this attribute */ public String getMethodSignature(FacesContext ctx) { - - ValueExpression ms = (ValueExpression) pd.getValue("method-signature"); - if (ms != null) { - return (String) ms.getValue(ctx.getELContext()); + ValueExpression methodSignature = (ValueExpression) propertyDescriptor.getValue("method-signature"); + if (methodSignature != null) { + return (String) methodSignature.getValue(ctx.getELContext()); } - return null; + return null; } /** @@ -1374,21 +1353,19 @@ public String getMethodSignature(FacesContext ctx) { * @return an array of component targets to which a MethodExpression should be retargeted */ public String[] getTargets(FacesContext ctx) { - - ValueExpression ts = (ValueExpression) pd.getValue("targets"); - if (ts != null) { - String targets = (String) ts.getValue(ctx.getELContext()); + ValueExpression targetsExpression = (ValueExpression) propertyDescriptor.getValue("targets"); + if (targetsExpression != null) { + String targets = (String) targetsExpression.getValue(ctx.getELContext()); if (targets != null) { return Util.split(ctx.getExternalContext().getApplicationMap(), targets, " "); } } return null; - } public String getTargetAttributeName(FacesContext ctx) { - ValueExpression ve = (ValueExpression) pd.getValue("targetAttributeName"); + ValueExpression ve = (ValueExpression) propertyDescriptor.getValue("targetAttributeName"); return ve != null ? (String) ve.getValue(ctx.getELContext()) : null; } @@ -1400,7 +1377,7 @@ public String getTargetAttributeName(FacesContext ctx) { */ public boolean isRequired(FacesContext ctx) { - ValueExpression rd = (ValueExpression) pd.getValue("required"); + ValueExpression rd = (ValueExpression) propertyDescriptor.getValue("required"); return rd != null ? Boolean.valueOf(rd.getValue(ctx.getELContext()).toString()) : false; } @@ -1410,18 +1387,14 @@ public boolean isRequired(FacesContext ctx) { * composite component consumer. This value may be a ValueExpression, or a literal. */ public Object getDefault() { - - return pd.getValue("default"); - + return propertyDescriptor.getValue("default"); } /** * @return the composite component attribute name */ public String getName() { - - return pd.getName(); - + return propertyDescriptor.getName(); } } // END CompCompInterfaceMethodMetadata @@ -1447,7 +1420,6 @@ private static final class MethodRetargetHandlerManager { // -------------------------------------------------------- Constructors MethodRetargetHandlerManager() { - MethodRetargetHandler[] handlers = { new ActionRegargetHandler(), new ActionListenerRegargetHandler(), new ValidatorRegargetHandler(), new ValueChangeListenerRegargetHandler() }; for (MethodRetargetHandler h : handlers) { @@ -1466,18 +1438,14 @@ private static final class MethodRetargetHandlerManager { * attribute, or null if there is no handler available. */ private MethodRetargetHandler getRetargetHandler(String attrName) { - return handlerMap.get(attrName); - } /** * @return a MethodRetargetHandler that can retarget arbitrarily named MethodExpressions. */ private MethodRetargetHandler getDefaultHandler() { - return arbitraryHandler; - } // ------------------------------------------------------ Nested Classes @@ -1503,7 +1471,6 @@ private static final class ActionRegargetHandler extends AbstractRetargetHandler @Override public void retarget(FacesContext ctx, CompCompInterfaceMethodMetadata metadata, Object sourceValue, UIComponent target) { - String expr = sourceValue instanceof ValueExpression ? ((ValueExpression) sourceValue).getExpressionString() : sourceValue.toString(); ExpressionFactory f = ctx.getApplication().getExpressionFactory(); MethodExpression me = f.createMethodExpression(ctx.getELContext(), expr, Object.class, NO_ARGS); @@ -1514,9 +1481,7 @@ public void retarget(FacesContext ctx, CompCompInterfaceMethodMetadata metadata, @Override public String getAttribute() { - return ACTION; - } } // END ActionRegargetHandler @@ -1534,7 +1499,6 @@ private static final class ActionListenerRegargetHandler extends AbstractRetarge @Override public void retarget(FacesContext ctx, CompCompInterfaceMethodMetadata metadata, Object sourceValue, UIComponent target) { - ValueExpression ve = (ValueExpression) sourceValue; ExpressionFactory f = ctx.getApplication().getExpressionFactory(); MethodExpression me = f.createMethodExpression(ctx.getELContext(), ve.getExpressionString(), Void.TYPE, ACTION_LISTENER_ARGS); @@ -1547,9 +1511,7 @@ public void retarget(FacesContext ctx, CompCompInterfaceMethodMetadata metadata, @Override public String getAttribute() { - return ACTION_LISTENER; - } } // END ActionListenerRegargetHandler @@ -1567,7 +1529,6 @@ private static final class ValidatorRegargetHandler extends AbstractRetargetHand @Override public void retarget(FacesContext ctx, CompCompInterfaceMethodMetadata metadata, Object sourceValue, UIComponent target) { - ValueExpression ve = (ValueExpression) sourceValue; ExpressionFactory f = ctx.getApplication().getExpressionFactory(); MethodExpression me = f.createMethodExpression(ctx.getELContext(), ve.getExpressionString(), Void.TYPE, VALIDATOR_ARGS); @@ -1578,9 +1539,7 @@ public void retarget(FacesContext ctx, CompCompInterfaceMethodMetadata metadata, @Override public String getAttribute() { - return VALIDATOR; - } } // END ValidatorRegargetHandler @@ -1625,7 +1584,6 @@ private static final class ArbitraryMethodRegargetHandler extends AbstractRetarg @Override public void retarget(FacesContext ctx, CompCompInterfaceMethodMetadata metadata, Object sourceValue, UIComponent target) { - ValueExpression ve = (ValueExpression) sourceValue; ExpressionFactory f = ctx.getApplication().getExpressionFactory(); diff --git a/impl/src/main/java/com/sun/faces/application/view/MultiViewHandler.java b/impl/src/main/java/com/sun/faces/application/view/MultiViewHandler.java index bb9ee3b12c..e4d4cc29b7 100644 --- a/impl/src/main/java/com/sun/faces/application/view/MultiViewHandler.java +++ b/impl/src/main/java/com/sun/faces/application/view/MultiViewHandler.java @@ -24,14 +24,17 @@ import static com.sun.faces.util.MessageUtils.getExceptionMessageString; import static com.sun.faces.util.Util.getFacesMapping; import static com.sun.faces.util.Util.getFirstWildCardMappingToFacesServlet; +import static com.sun.faces.util.Util.getViewHandler; import static com.sun.faces.util.Util.isViewIdExactMappedToFacesServlet; import static com.sun.faces.util.Util.notNull; import static jakarta.faces.FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY; +import static jakarta.faces.push.PushContext.URI_PREFIX; import static jakarta.faces.render.RenderKitFactory.HTML_BASIC_RENDER_KIT; import static jakarta.faces.render.ResponseStateManager.NON_POSTBACK_VIEW_TOKEN_PARAM; import static jakarta.servlet.http.MappingMatch.EXACT; import static jakarta.servlet.http.MappingMatch.EXTENSION; import static jakarta.servlet.http.MappingMatch.PATH; +import static java.text.MessageFormat.format; import static java.util.Collections.unmodifiableSet; import static java.util.Objects.requireNonNull; import static java.util.logging.Level.FINE; @@ -41,7 +44,6 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; -import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -68,7 +70,6 @@ import jakarta.faces.component.UIViewRoot; import jakarta.faces.context.ExternalContext; import jakarta.faces.context.FacesContext; -import jakarta.faces.push.PushContext; import jakarta.faces.view.ViewDeclarationLanguage; import jakarta.faces.view.ViewDeclarationLanguageFactory; import jakarta.faces.view.ViewMetadata; @@ -314,8 +315,7 @@ public String getWebsocketURL(FacesContext context, String channel) { requireNonNull(channel, "channel"); ExternalContext externalContext = context.getExternalContext(); - String contextPath = externalContext.getRequestContextPath(); - return externalContext.encodeWebsocketURL(contextPath + PushContext.URI_PREFIX + "/" + channel); + return externalContext.encodeWebsocketURL(externalContext.getRequestContextPath() + URI_PREFIX + "/" + channel); } @Override @@ -328,7 +328,7 @@ public String getBookmarkableURL(FacesContext context, String viewId, Map> parameters, boolean includeViewParams) { - String encodingFromContext = (String) context.getAttributes().get(FACELETS_ENCODING_KEY); if (encodingFromContext == null) { encodingFromContext = (String) context.getViewRoot().getAttributes().get(FACELETS_ENCODING_KEY); @@ -363,11 +362,8 @@ public String getRedirectURL(FacesContext context, String viewId, Map + format("Unable to obtain response character encoding from ExternalContext {0}. Using UTF-8.", context.getExternalContext())); responseEncoding = "UTF-8"; } } else { @@ -433,6 +429,7 @@ public String deriveLogicalViewId(FacesContext context, String requestViewId) { return derivePhysicalViewId(context, requestViewId, false); } + // ------------------------------------------------------- Protected Methods protected String derivePhysicalViewId(FacesContext ctx, String requestViewId, boolean checkPhysical) { @@ -547,9 +544,8 @@ protected void addViewParameters(FacesContext ctx, String viewId, Map currentViewMapShallowCopy = Collections.emptyMap(); + Map currentViewMapShallowCopy = emptyMap(); try { context.setProcessingEvents(false); if (faceletFactory == null) { - ApplicationAssociate associate = ApplicationAssociate.getInstance(context.getExternalContext()); - faceletFactory = associate.getFaceletFactory(); - assert faceletFactory != null; + faceletFactory = ApplicationAssociate.getInstance(context.getExternalContext()) + .getFaceletFactory(); } - ViewHandler vh = context.getApplication().getViewHandler(); - result = vh.createView(context, viewId); + + metadataView = context.getApplication() + .getViewHandler() + .createView(context, viewId); // Stash away view id before invoking handlers so that // StateContext.partialStateSaving() can determine the current // view. context.getAttributes().put(RIConstants.VIEWID_KEY_NAME, viewId); + // If the currentViewRoot has a viewMap, make sure the entries are // copied to the temporary UIViewRoot before invoking handlers. - if (null != currentViewRoot) { + if (currentViewRoot != null) { Map currentViewMap = currentViewRoot.getViewMap(false); - if (null != currentViewMap && !currentViewMap.isEmpty()) { - currentViewMapShallowCopy = new HashMap<>(currentViewMap); - Map resultViewMap = result.getViewMap(true); - resultViewMap.putAll(currentViewMapShallowCopy); + if (!isEmpty(currentViewMap)) { + metadataView.getViewMap(true) + .putAll(new HashMap<>(currentViewMap)); } } - // Only replace the current context's UIViewRoot if there is - // one to replace. - if (null != currentViewRoot) { - // This clear's the ViewMap of the current UIViewRoot before + // Only replace the current context's UIViewRoot if there is one to replace. + if (currentViewRoot != null) { + // This clears the ViewMap of the current UIViewRoot before // setting the argument as the new UIViewRoot. - context.setViewRoot(result); + context.setViewRoot(metadataView); } - Facelet f = faceletFactory.getMetadataFacelet(context, result.getViewId()); - - f.apply(context, result); + faceletFactory.getMetadataFacelet(context, metadataView.getViewId()) + .apply(context, metadataView); - importConstantsIfNecessary(context, result); + importConstantsIfNecessary(context, metadataView); } catch (FacesFileNotFoundException ffnfe) { try { @@ -128,8 +123,8 @@ public UIViewRoot createMetadataView(FacesContext context) { } catch (IOException ioe) { throw new FacesException(ioe); } finally { - context.getAttributes().remove(RIConstants.VIEWID_KEY_NAME); - if (null != currentViewRoot) { + context.getAttributes().remove(VIEWID_KEY_NAME); + if (currentViewRoot != null) { context.setViewRoot(currentViewRoot); if (!currentViewMapShallowCopy.isEmpty()) { currentViewRoot.getViewMap(true).putAll(currentViewMapShallowCopy); @@ -139,10 +134,10 @@ public UIViewRoot createMetadataView(FacesContext context) { context.setProcessingEvents(true); } - return result; - + return metadataView; } + // ----------------------------------------------------------------------------------------------- UIImportConstants private static void importConstantsIfNecessary(FacesContext context, UIViewRoot root) { diff --git a/impl/src/main/java/com/sun/faces/lifecycle/RestoreViewPhase.java b/impl/src/main/java/com/sun/faces/lifecycle/RestoreViewPhase.java index bbb0a4ef41..77d22b443e 100644 --- a/impl/src/main/java/com/sun/faces/lifecycle/RestoreViewPhase.java +++ b/impl/src/main/java/com/sun/faces/lifecycle/RestoreViewPhase.java @@ -18,12 +18,16 @@ package com.sun.faces.lifecycle; +import static com.sun.faces.renderkit.RenderKitUtils.getResponseStateManager; import static com.sun.faces.util.MessageUtils.NULL_CONTEXT_ERROR_MESSAGE_ID; import static com.sun.faces.util.MessageUtils.NULL_REQUEST_VIEW_ERROR_MESSAGE_ID; import static com.sun.faces.util.MessageUtils.RESTORE_VIEW_ERROR_MESSAGE_ID; import static com.sun.faces.util.MessageUtils.getExceptionMessageString; import static com.sun.faces.util.Util.getViewHandler; import static com.sun.faces.util.Util.isOneOf; +import static jakarta.faces.event.PhaseId.RESTORE_VIEW; +import static jakarta.faces.render.ResponseStateManager.NON_POSTBACK_VIEW_TOKEN_PARAM; +import static jakarta.faces.view.ViewMetadata.hasMetadata; import static java.util.logging.Level.FINE; import static java.util.logging.Level.SEVERE; @@ -37,7 +41,6 @@ import java.util.Set; import java.util.logging.Logger; -import com.sun.faces.renderkit.RenderKitUtils; import com.sun.faces.util.FacesLogger; import com.sun.faces.util.MessageUtils; import com.sun.faces.util.Util; @@ -188,7 +191,7 @@ public void execute(FacesContext facesContext) throws FacesException { viewRoot = metadata.createMetadataView(facesContext); // Only skip to render response if there is no metadata - if (!ViewMetadata.hasMetadata(viewRoot)) { + if (!hasMetadata(viewRoot)) { facesContext.renderResponse(); } } @@ -234,22 +237,23 @@ private void maybeTakeProtectedViewAction(FacesContext context, ViewHandler view // how grizzly does this. Set urlPatterns = viewHandler.getProtectedViewsUnmodifiable(); + // Implement section 12.1 of the Servlet spec (consider using Jakarta Authorization, perhaps via SPI) - boolean currentViewIsProtected = isProtectedView(viewId, urlPatterns); - if (currentViewIsProtected) { + if (isProtectedView(viewId, urlPatterns)) { ExternalContext extContext = context.getExternalContext(); Map headers = extContext.getRequestHeaderMap(); // Check the token - String rkId = viewHandler.calculateRenderKitId(context); - ResponseStateManager rsm = RenderKitUtils.getResponseStateManager(context, rkId); - String incomingSecretKeyValue = extContext.getRequestParameterMap().get(ResponseStateManager.NON_POSTBACK_VIEW_TOKEN_PARAM); - if (null != incomingSecretKeyValue) { + ResponseStateManager rsm = getResponseStateManager(context, viewHandler.calculateRenderKitId(context)); + + String incomingSecretKeyValue = extContext.getRequestParameterMap().get(NON_POSTBACK_VIEW_TOKEN_PARAM); + if (incomingSecretKeyValue != null) { try { incomingSecretKeyValue = URLEncoder.encode(incomingSecretKeyValue, "UTF-8"); } catch (UnsupportedEncodingException e) { if (LOGGER.isLoggable(SEVERE)) { - LOGGER.log(SEVERE, "Unable to re-encode value of request parameter " + ResponseStateManager.NON_POSTBACK_VIEW_TOKEN_PARAM + ":" + LOGGER.log(SEVERE, + "Unable to re-encode value of request parameter " + NON_POSTBACK_VIEW_TOKEN_PARAM + ":" + incomingSecretKeyValue, e); } incomingSecretKeyValue = null; @@ -257,7 +261,7 @@ private void maybeTakeProtectedViewAction(FacesContext context, ViewHandler view } String correctSecretKeyValue = rsm.getCryptographicallyStrongTokenFromSession(context); - if (null == incomingSecretKeyValue || !correctSecretKeyValue.equals(incomingSecretKeyValue)) { + if (incomingSecretKeyValue == null || !correctSecretKeyValue.equals(incomingSecretKeyValue)) { LOGGER.log(SEVERE, "correctSecretKeyValue = {0} incomingSecretKeyValue = {1}", new Object[] { correctSecretKeyValue, incomingSecretKeyValue }); throw new ProtectedViewException(); @@ -282,6 +286,7 @@ private void maybeTakeProtectedViewAction(FacesContext context, ViewHandler view } } } + // Check the origin header if (headers.containsKey("Origin")) { String origin = headers.get("Origin"); @@ -404,6 +409,7 @@ private void deliverPostRestoreStateEvent(FacesContext facesContext) throws Face } } + // --------------------------------------------------------- Private Methods /** @@ -421,7 +427,7 @@ private void notifyAfter(FacesContext context, Lifecycle lifecycle) { MethodExpression afterPhase = viewRoot.getAfterPhaseListener(); if (afterPhase != null) { try { - PhaseEvent event = new PhaseEvent(context, PhaseId.RESTORE_VIEW, lifecycle); + PhaseEvent event = new PhaseEvent(context, RESTORE_VIEW, lifecycle); afterPhase.invoke(context.getELContext(), new Object[] { event }); } catch (Exception e) { if (LOGGER.isLoggable(SEVERE)) { diff --git a/impl/src/main/java/jakarta/faces/application/ViewHandler.java b/impl/src/main/java/jakarta/faces/application/ViewHandler.java index 81c2c0eaaa..cfe1f0a6dc 100644 --- a/impl/src/main/java/jakarta/faces/application/ViewHandler.java +++ b/impl/src/main/java/jakarta/faces/application/ViewHandler.java @@ -18,7 +18,6 @@ import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; -import static java.util.logging.Level.WARNING; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -240,9 +239,7 @@ public void initView(FacesContext context) throws FacesException { context.getExternalContext().setRequestCharacterEncoding(encoding); } catch (UnsupportedEncodingException e) { String message = "Can't set encoding to: " + encoding + " Exception:" + e.getMessage(); - if (log.isLoggable(WARNING)) { - log.fine(message); - } + log.fine(message); throw new FacesException(message, e); }