You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by de...@apache.org on 2018/05/08 12:48:22 UTC
[myfaces] 19/28: MYFACES-3645 review/refactor/document ViewState
handling (step 1. move related code to new package
org.apache.myfaces.application.viewstate) for 2.1.x-client-window branch
(merge revision 1410171)
This is an automated email from the ASF dual-hosted git repository.
deki pushed a commit to branch 2.1.x-client-window
in repository https://gitbox.apache.org/repos/asf/myfaces.git
commit e88788718339c3c3da1945dce49a07b1e47ee518
Author: Leonardo Uribe <lu...@apache.org>
AuthorDate: Fri Nov 16 03:29:54 2012 +0000
MYFACES-3645 review/refactor/document ViewState handling (step 1. move related code to new package org.apache.myfaces.application.viewstate) for 2.1.x-client-window branch (merge revision 1410171)
---
.../myfaces/application/StateManagerImpl.java | 2 +-
.../myfaces/application/ViewHandlerImpl.java | 2 +-
.../viewstate/ClientSideStateCacheImpl.java | 2 +-
.../viewstate/ServerSideStateCacheImpl.java | 2 +-
.../application/viewstate/SessionIdGenerator.java | 2 +-
.../viewstate/StateCacheFactoryImpl.java | 2 +-
.../application/viewstate/StateCacheUtils.java | 3 +-
.../renderkit/ClientSideStateCacheImpl.java | 175 ---
.../renderkit/ServerSideStateCacheImpl.java | 1498 --------------------
.../myfaces/renderkit/SessionIdGenerator.java | 288 ----
.../myfaces/renderkit/StateCacheFactoryImpl.java | 50 -
.../apache/myfaces/renderkit/StateCacheUtils.java | 81 --
.../renderkit/html/HtmlResponseStateManager.java | 2 +-
.../view/jsp/JspViewDeclarationLanguage.java | 2 +-
.../viewstate/ClientSideStateCacheTest.java | 27 +-
.../viewstate/ServerSideStateCacheTest.java | 2 +-
.../renderkit/ClientSideStateCacheTest.java | 211 ---
.../renderkit/ServerSideStateCacheTest.java | 269 ----
18 files changed, 26 insertions(+), 2594 deletions(-)
diff --git a/impl/src/main/java/org/apache/myfaces/application/StateManagerImpl.java b/impl/src/main/java/org/apache/myfaces/application/StateManagerImpl.java
index 2950525..3431003 100644
--- a/impl/src/main/java/org/apache/myfaces/application/StateManagerImpl.java
+++ b/impl/src/main/java/org/apache/myfaces/application/StateManagerImpl.java
@@ -37,7 +37,7 @@ import javax.faces.render.ResponseStateManager;
import javax.faces.view.StateManagementStrategy;
import javax.faces.view.ViewDeclarationLanguage;
-import org.apache.myfaces.renderkit.StateCacheUtils;
+import org.apache.myfaces.application.viewstate.StateCacheUtils;
public class StateManagerImpl extends StateManager
{
diff --git a/impl/src/main/java/org/apache/myfaces/application/ViewHandlerImpl.java b/impl/src/main/java/org/apache/myfaces/application/ViewHandlerImpl.java
index d95b275..c55512c 100644
--- a/impl/src/main/java/org/apache/myfaces/application/ViewHandlerImpl.java
+++ b/impl/src/main/java/org/apache/myfaces/application/ViewHandlerImpl.java
@@ -45,7 +45,7 @@ import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.ViewMetadata;
import javax.servlet.http.HttpServletResponse;
-import org.apache.myfaces.renderkit.StateCacheUtils;
+import org.apache.myfaces.application.viewstate.StateCacheUtils;
import org.apache.myfaces.shared.application.DefaultViewHandlerSupport;
import org.apache.myfaces.shared.application.InvalidViewIdException;
import org.apache.myfaces.shared.application.ViewHandlerSupport;
diff --git a/impl/src/main/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheImpl.java b/impl/src/main/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheImpl.java
index 9cc1ee1..e790cb7 100644
--- a/impl/src/main/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheImpl.java
+++ b/impl/src/main/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheImpl.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.myfaces.renderkit;
+package org.apache.myfaces.application.viewstate;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
diff --git a/impl/src/main/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheImpl.java b/impl/src/main/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheImpl.java
index 652cb24..ad527f2 100644
--- a/impl/src/main/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheImpl.java
+++ b/impl/src/main/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheImpl.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.myfaces.renderkit;
+package org.apache.myfaces.application.viewstate;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
diff --git a/impl/src/main/java/org/apache/myfaces/application/viewstate/SessionIdGenerator.java b/impl/src/main/java/org/apache/myfaces/application/viewstate/SessionIdGenerator.java
index dd09fef..0d6bc2e 100644
--- a/impl/src/main/java/org/apache/myfaces/application/viewstate/SessionIdGenerator.java
+++ b/impl/src/main/java/org/apache/myfaces/application/viewstate/SessionIdGenerator.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.myfaces.renderkit;
+package org.apache.myfaces.application.viewstate;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
diff --git a/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheFactoryImpl.java b/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheFactoryImpl.java
index 0fbbf15..81bb2f9 100644
--- a/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheFactoryImpl.java
+++ b/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheFactoryImpl.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.myfaces.renderkit;
+package org.apache.myfaces.application.viewstate;
import javax.faces.context.FacesContext;
diff --git a/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheUtils.java b/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheUtils.java
index 7bdc15a..09c3ebd 100644
--- a/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheUtils.java
+++ b/impl/src/main/java/org/apache/myfaces/application/viewstate/StateCacheUtils.java
@@ -16,10 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.myfaces.renderkit;
+package org.apache.myfaces.application.viewstate;
import javax.faces.FacesWrapper;
import javax.faces.render.ResponseStateManager;
+import org.apache.myfaces.renderkit.MyfacesResponseStateManager;
public class StateCacheUtils
{
diff --git a/impl/src/main/java/org/apache/myfaces/renderkit/ClientSideStateCacheImpl.java b/impl/src/main/java/org/apache/myfaces/renderkit/ClientSideStateCacheImpl.java
deleted file mode 100644
index 9cc1ee1..0000000
--- a/impl/src/main/java/org/apache/myfaces/renderkit/ClientSideStateCacheImpl.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.myfaces.renderkit;
-
-import javax.faces.context.ExternalContext;
-import javax.faces.context.FacesContext;
-
-import org.apache.myfaces.application.StateCache;
-import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFWebConfigParam;
-import org.apache.myfaces.shared.util.WebConfigParamUtils;
-
-class ClientSideStateCacheImpl extends StateCache<Object, Object>
-{
-
- /**
- * Define the time in minutes where the view state is valid when
- * client side state saving is used. By default it is set to 0
- * (infinite).
- */
- @JSFWebConfigParam(since="2.1.9, 2.0.15", defaultValue="0", group="state")
- public static final String INIT_PARAM_CLIENT_VIEW_STATE_TIMEOUT =
- "org.apache.myfaces.CLIENT_VIEW_STATE_TIMEOUT";
- public static final Long INIT_PARAM_CLIENT_VIEW_STATE_TIMEOUT_DEFAULT = 0L;
-
- private static final int STATE_PARAM = 0;
- private static final int VIEWID_PARAM = 1;
- private static final int TIMESTAMP_PARAM = 2;
-
- private static final Object[] EMPTY_STATES = new Object[]{null, null};
-
- private Long _clientViewStateTimeout;
-
- @Override
- public Object saveSerializedView(FacesContext facesContext,
- Object serializedView)
- {
- // The state in this case the state is saved on the token sent to
- // the client (isWriteStateAfterRenderViewRequired() is set to true).
- // No additional operation is required here.
- return encodeSerializedState(facesContext, serializedView);
- }
-
- @Override
- public Object restoreSerializedView(FacesContext facesContext,
- String viewId, Object viewState)
- {
- Object[] state = (Object[]) viewState;
- long clientViewStateTimeout = getClientViewStateTimeout(facesContext.getExternalContext());
-
- if (clientViewStateTimeout > 0L)
- {
- Long timeStamp = (Long) state[TIMESTAMP_PARAM];
- if (timeStamp == null)
- {
- //If no timestamp, state is invalid.
- return null;
- }
- long passedTime = (System.currentTimeMillis() - timeStamp.longValue()) / 60000;
-
- if (passedTime > clientViewStateTimeout)
- {
- //expire
- return null;
- }
- }
-
- String restoredViewId = (String) state[VIEWID_PARAM];
-
- if (viewId != null && !viewId.equals(restoredViewId))
- {
- //invalid viewId, expire
- return null;
- }
-
- //return the state
- if (state[STATE_PARAM] == null)
- {
- return EMPTY_STATES;
- }
- else
- {
- Object serializedView = state[STATE_PARAM];
- if (serializedView instanceof Object[] &&
- ((Object[])serializedView).length == 2 &&
- ((Object[])serializedView)[0] == null &&
- ((Object[])serializedView)[1] == null)
- {
- // Remember inside the state null is stored as an empty array.
- return null;
- }
-
- return state[STATE_PARAM];
- }
- }
-
- @Override
- public Object encodeSerializedState(FacesContext facesContext,
- Object serializedView)
- {
- Object[] state = null;
-
- if (getClientViewStateTimeout(facesContext.getExternalContext()).longValue() > 0L)
- {
- state = new Object[3];
- state[TIMESTAMP_PARAM] = System.currentTimeMillis();
- }
- else
- {
- state = new Object[2];
- }
-
- if (serializedView == null)
- {
- state[STATE_PARAM] = EMPTY_STATES;
- }
- else if (serializedView instanceof Object[] &&
- ((Object[])serializedView).length == 2 &&
- ((Object[])serializedView)[0] == null &&
- ((Object[])serializedView)[1] == null)
- {
- // The generated state can be considered zero, set it as null
- // into the map.
- state[STATE_PARAM] = null;
- }
- else
- {
- state[STATE_PARAM] = serializedView;
- }
-
- state[VIEWID_PARAM] = facesContext.getViewRoot().getViewId();
-
- return state;
- }
-
- @Override
- public boolean isWriteStateAfterRenderViewRequired(FacesContext facesContext)
- {
- return true;
- }
-
- /**
- * @return the _clientViewStateTimeout
- */
- protected Long getClientViewStateTimeout(ExternalContext context)
- {
- if (_clientViewStateTimeout == null)
- {
- _clientViewStateTimeout = WebConfigParamUtils.getLongInitParameter(
- context, INIT_PARAM_CLIENT_VIEW_STATE_TIMEOUT,
- INIT_PARAM_CLIENT_VIEW_STATE_TIMEOUT_DEFAULT);
- if (_clientViewStateTimeout.longValue() < 0L)
- {
- _clientViewStateTimeout = 0L;
- }
- }
- return _clientViewStateTimeout;
- }
-
-}
diff --git a/impl/src/main/java/org/apache/myfaces/renderkit/ServerSideStateCacheImpl.java b/impl/src/main/java/org/apache/myfaces/renderkit/ServerSideStateCacheImpl.java
deleted file mode 100644
index 652cb24..0000000
--- a/impl/src/main/java/org/apache/myfaces/renderkit/ServerSideStateCacheImpl.java
+++ /dev/null
@@ -1,1498 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.myfaces.renderkit;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.io.Serializable;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
-import javax.faces.application.ProjectStage;
-
-import javax.faces.context.ExternalContext;
-import javax.faces.context.FacesContext;
-import javax.faces.lifecycle.ClientWindow;
-import org.apache.commons.codec.DecoderException;
-import org.apache.commons.codec.binary.Hex;
-
-import org.apache.commons.collections.map.AbstractReferenceMap;
-import org.apache.commons.collections.map.LRUMap;
-import org.apache.commons.collections.map.ReferenceMap;
-import org.apache.myfaces.application.StateCache;
-import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFWebConfigParam;
-import org.apache.myfaces.shared.renderkit.RendererUtils;
-import org.apache.myfaces.shared.util.MyFacesObjectInputStream;
-import org.apache.myfaces.shared.util.WebConfigParamUtils;
-
-class ServerSideStateCacheImpl extends StateCache<Object, Object>
-{
- private static final Logger log = Logger.getLogger(ServerSideStateCacheImpl.class.getName());
-
- private static final String SERIALIZED_VIEW_SESSION_ATTR=
- ServerSideStateCacheImpl.class.getName() + ".SERIALIZED_VIEW";
-
- private static final String RESTORED_SERIALIZED_VIEW_REQUEST_ATTR =
- ServerSideStateCacheImpl.class.getName() + ".RESTORED_SERIALIZED_VIEW";
-
- private static final String RESTORED_VIEW_KEY_REQUEST_ATTR =
- ServerSideStateCacheImpl.class.getName() + ".RESTORED_VIEW_KEY";
-
- /**
- * Defines the amount (default = 20) of the latest views are stored in session.
- *
- * <p>Only applicable if state saving method is "server" (= default).
- * </p>
- *
- */
- @JSFWebConfigParam(defaultValue="20",since="1.1", classType="java.lang.Integer", group="state", tags="performance")
- private static final String NUMBER_OF_VIEWS_IN_SESSION_PARAM = "org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION";
-
- /**
- * Indicates the amount of views (default is not active) that should be stored in session between sequential
- * POST or POST-REDIRECT-GET if org.apache.myfaces.USE_FLASH_SCOPE_PURGE_VIEWS_IN_SESSION is true.
- *
- * <p>Only applicable if state saving method is "server" (= default). For example, if this param has value = 2 and
- * in your custom webapp there is a form that is clicked 3 times, only 2 views
- * will be stored and the third one (the one stored the first time) will be
- * removed from session, even if the view can
- * store more sessions org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION.
- * This feature becomes useful for multi-window applications.
- * where without this feature a window can swallow all view slots so
- * the other ones will throw ViewExpiredException.</p>
- */
- @JSFWebConfigParam(since="2.0.6", classType="java.lang.Integer", group="state", tags="performance")
- private static final String NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION_PARAM
- = "org.apache.myfaces.NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION";
-
- /**
- * Default value for <code>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</code> context parameter.
- */
- private static final int DEFAULT_NUMBER_OF_VIEWS_IN_SESSION = 20;
-
- /**
- * Indicate if the state should be serialized before save it on the session.
- * <p>
- * Only applicable if state saving method is "server" (= default).
- * If <code>true</code> (default) the state will be serialized to a byte stream before it is written to the session.
- * If <code>false</code> the state will not be serialized to a byte stream.
- * </p>
- */
- @JSFWebConfigParam(defaultValue="true",since="1.1", expectedValues="true,false", group="state", tags="performance")
- private static final String SERIALIZE_STATE_IN_SESSION_PARAM = "org.apache.myfaces.SERIALIZE_STATE_IN_SESSION";
-
- /**
- * Indicates that the serialized state will be compressed before it is written to the session. By default true.
- *
- * Only applicable if state saving method is "server" (= default) and if
- * <code>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</code> is <code>true</code> (= default).
- * If <code>true</code> (default) the serialized state will be compressed before it is written to the session.
- * If <code>false</code> the state will not be compressed.
- */
- @JSFWebConfigParam(defaultValue="true",since="1.1", expectedValues="true,false", group="state", tags="performance")
- private static final String COMPRESS_SERVER_STATE_PARAM = "org.apache.myfaces.COMPRESS_STATE_IN_SESSION";
-
- /**
- * Default value for <code>org.apache.myfaces.COMPRESS_STATE_IN_SESSION</code> context parameter.
- */
- private static final boolean DEFAULT_COMPRESS_SERVER_STATE_PARAM = true;
-
- /**
- * Default value for <code>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</code> context parameter.
- */
- private static final boolean DEFAULT_SERIALIZE_STATE_IN_SESSION = true;
-
- /**
- * Define the way of handle old view references(views removed from session), making possible to
- * store it in a cache, so the state manager first try to get the view from the session. If is it
- * not found and soft or weak ReferenceMap is used, it try to get from it.
- * <p>
- * Only applicable if state saving method is "server" (= default).
- * </p>
- * <p>
- * The gc is responsible for remove the views, according to the rules used for soft, weak or phantom
- * references. If a key in soft and weak mode is garbage collected, its values are purged.
- * </p>
- * <p>
- * By default no cache is used, so views removed from session became phantom references.
- * </p>
- * <ul>
- * <li> off, no: default, no cache is used</li>
- * <li> hard-soft: use an ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.SOFT)</li>
- * <li> soft: use an ReferenceMap(AbstractReferenceMap.SOFT, AbstractReferenceMap.SOFT, true) </li>
- * <li> soft-weak: use an ReferenceMap(AbstractReferenceMap.SOFT, AbstractReferenceMap.WEAK, true) </li>
- * <li> weak: use an ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK, true) </li>
- * </ul>
- *
- */
- @JSFWebConfigParam(defaultValue="off", expectedValues="off, no, hard-soft, soft, soft-weak, weak",
- since="1.2.5", group="state", tags="performance")
- private static final String CACHE_OLD_VIEWS_IN_SESSION_MODE = "org.apache.myfaces.CACHE_OLD_VIEWS_IN_SESSION_MODE";
-
- /**
- * This option uses an hard-soft ReferenceMap, but it could cause a
- * memory leak, because the keys are not removed by any method
- * (MYFACES-1660). So use with caution.
- */
- private static final String CACHE_OLD_VIEWS_IN_SESSION_MODE_HARD_SOFT = "hard-soft";
-
- private static final String CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT = "soft";
-
- private static final String CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT_WEAK = "soft-weak";
-
- private static final String CACHE_OLD_VIEWS_IN_SESSION_MODE_WEAK = "weak";
-
- private static final String CACHE_OLD_VIEWS_IN_SESSION_MODE_OFF = "off";
-
- /**
- * Allow use flash scope to keep track of the views used in session and the previous ones,
- * so server side state saving can delete old views even if POST-REDIRECT-GET pattern is used.
- *
- * <p>
- * Only applicable if state saving method is "server" (= default).
- * The default value is false.</p>
- */
- @JSFWebConfigParam(since="2.0.6", defaultValue="false", expectedValues="true, false", group="state")
- private static final String USE_FLASH_SCOPE_PURGE_VIEWS_IN_SESSION
- = "org.apache.myfaces.USE_FLASH_SCOPE_PURGE_VIEWS_IN_SESSION";
-
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_NONE = "none";
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM = "secureRandom";
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_RANDOM = "random";
-
- /**
- * Adds a random key to the generated view state session token.
- */
- @JSFWebConfigParam(since="2.1.9, 2.0.15", expectedValues="secureRandom, random, none",
- defaultValue="none", group="state")
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_PARAM
- = "org.apache.myfaces.RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN";
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_PARAM_DEFAULT =
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_NONE;
-
- /**
- * Set the default length of the random key added to the view state session token.
- * By default is 8.
- */
- @JSFWebConfigParam(since="2.1.9, 2.0.15", defaultValue="8", group="state")
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_LENGTH_PARAM
- = "org.apache.myfaces.RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_LENGTH";
- private static final int RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_LENGTH_PARAM_DEFAULT = 8;
-
- /**
- * Sets the random class to initialize the secure random id generator.
- * By default it uses java.security.SecureRandom
- */
- @JSFWebConfigParam(since="2.1.9, 2.0.15", group="state")
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_CLASS_PARAM
- = "org.apache.myfaces.RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_CLASS";
-
- /**
- * Sets the random provider to initialize the secure random id generator.
- */
- @JSFWebConfigParam(since="2.1.9, 2.0.15", group="state")
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_PROVIDER_PARAM
- = "org.apache.myfaces.RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_PROVIDER";
-
- /**
- * Sets the random algorithm to initialize the secure random id generator.
- * By default is SHA1PRNG
- */
- @JSFWebConfigParam(since="2.1.9, 2.0.15", defaultValue="SHA1PRNG", group="state")
- private static final String RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_ALGORITM_PARAM
- = "org.apache.myfaces.RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_ALGORITM";
-
-
- private static final int UNCOMPRESSED_FLAG = 0;
- private static final int COMPRESSED_FLAG = 1;
-
- private static final Object[] EMPTY_STATES = new Object[]{null, null};
-
- //private static final int JSF_SEQUENCE_INDEX = 0;
-
- private Boolean _useFlashScopePurgeViewsInSession = null;
-
- private Integer _numberOfSequentialViewsInSession = null;
- private boolean _numberOfSequentialViewsInSessionSet = false;
-
- //private final KeyFactory keyFactory;
- private SessionViewStorageFactory sessionViewStorageFactory;
-
- public ServerSideStateCacheImpl()
- {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- String randomMode = WebConfigParamUtils.getStringInitParameter(facesContext.getExternalContext(),
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_PARAM,
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_PARAM_DEFAULT);
- if (RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM.equals(randomMode))
- {
- //keyFactory = new SecureRandomKeyFactory(facesContext);
- sessionViewStorageFactory = new RandomSessionViewStorageFactory(
- new SecureRandomKeyFactory(facesContext));
- }
- else if (RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_RANDOM.equals(randomMode))
- {
- //keyFactory = new RandomKeyFactory(facesContext);
- sessionViewStorageFactory = new RandomSessionViewStorageFactory(
- new RandomKeyFactory(facesContext));
- }
- else
- {
- //keyFactory = new CounterKeyFactory();
- sessionViewStorageFactory = new CounterSessionViewStorageFactory(new CounterKeyFactory());
- }
- }
-
- //------------------------------------- METHODS COPIED FROM JspStateManagerImpl--------------------------------
-
- protected Object getServerStateId(FacesContext facesContext, Object state)
- {
- if (state != null)
- {
- return getKeyFactory(facesContext).decode(state);
- }
- return null;
- }
-
- protected void saveSerializedViewInServletSession(FacesContext context,
- Object serializedView)
- {
- Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
- SerializedViewCollection viewCollection = (SerializedViewCollection) sessionMap
- .get(SERIALIZED_VIEW_SESSION_ATTR);
- if (viewCollection == null)
- {
- viewCollection = getSessionViewStorageFactory().createSerializedViewCollection(context);
- sessionMap.put(SERIALIZED_VIEW_SESSION_ATTR, viewCollection);
- }
-
- Map<Object,Object> attributeMap = context.getAttributes();
-
- SerializedViewKey key = null;
- if (getNumberOfSequentialViewsInSession(context.getExternalContext()) != null &&
- getNumberOfSequentialViewsInSession(context.getExternalContext()) > 0)
- {
- key = (SerializedViewKey) attributeMap.get(RESTORED_VIEW_KEY_REQUEST_ATTR);
-
- if (key == null )
- {
- // Check if clientWindow is enabled and if the last view key is stored
- // into session, so we can use it to chain the precedence in GET-GET
- // cases.
- ClientWindow clientWindow = context.getExternalContext().getClientWindow();
- if (clientWindow != null)
- {
- key = (SerializedViewKey) viewCollection.
- getLastWindowKey(context, clientWindow.getId());
- }
- else if (isUseFlashScopePurgeViewsInSession(context.getExternalContext()) &&
- Boolean.TRUE.equals(context.getExternalContext().getRequestMap()
- .get("oam.Flash.REDIRECT.PREVIOUSREQUEST")))
- {
- key = (SerializedViewKey)
- context.getExternalContext().getFlash().get(RESTORED_VIEW_KEY_REQUEST_ATTR);
- }
- }
- }
-
- SerializedViewKey nextKey = getSessionViewStorageFactory().createSerializedViewKey(
- context, context.getViewRoot().getViewId(), getNextViewSequence(context));
- viewCollection.add(context, serializeView(context, serializedView), nextKey, key);
-
- ClientWindow clientWindow = context.getExternalContext().getClientWindow();
- if (clientWindow != null)
- {
- //Update the last key generated for the current windowId in session map
- viewCollection.putLastWindowKey(context, clientWindow.getId(), nextKey);
- }
-
- // replace the value to notify the container about the change
- sessionMap.put(SERIALIZED_VIEW_SESSION_ATTR, viewCollection);
- }
-
- protected Object getSerializedViewFromServletSession(FacesContext context, String viewId, Object sequence)
- {
- ExternalContext externalContext = context.getExternalContext();
- Map<Object, Object> attributeMap = context.getAttributes();
- Object serializedView = null;
- if (attributeMap.containsKey(RESTORED_SERIALIZED_VIEW_REQUEST_ATTR))
- {
- serializedView = attributeMap.get(RESTORED_SERIALIZED_VIEW_REQUEST_ATTR);
- }
- else
- {
- SerializedViewCollection viewCollection = (SerializedViewCollection) externalContext
- .getSessionMap().get(SERIALIZED_VIEW_SESSION_ATTR);
- if (viewCollection != null)
- {
- if (sequence != null)
- {
- Object state = viewCollection.get(
- getSessionViewStorageFactory().createSerializedViewKey(
- context, viewId, sequence));
- if (state != null)
- {
- serializedView = deserializeView(state);
- }
- }
- }
- attributeMap.put(RESTORED_SERIALIZED_VIEW_REQUEST_ATTR, serializedView);
-
- if (getNumberOfSequentialViewsInSession(externalContext) != null &&
- getNumberOfSequentialViewsInSession(externalContext) > 0)
- {
- SerializedViewKey key = getSessionViewStorageFactory().
- createSerializedViewKey(context, viewId, sequence);
- attributeMap.put(RESTORED_VIEW_KEY_REQUEST_ATTR, key);
-
- if (isUseFlashScopePurgeViewsInSession(externalContext))
- {
- externalContext.getFlash().put(RESTORED_VIEW_KEY_REQUEST_ATTR, key);
- externalContext.getFlash().keep(RESTORED_VIEW_KEY_REQUEST_ATTR);
- }
- }
-
- nextViewSequence(context);
- }
- return serializedView;
- }
-
- public Object getNextViewSequence(FacesContext context)
- {
- Object sequence = context.getAttributes().get(RendererUtils.SEQUENCE_PARAM);
- if (sequence == null)
- {
- sequence = nextViewSequence(context);
- context.getAttributes().put(RendererUtils.SEQUENCE_PARAM, sequence);
- }
- return sequence;
- }
-
- public Object nextViewSequence(FacesContext facescontext)
- {
- Object sequence = getKeyFactory(facescontext).generateKey(facescontext);
- facescontext.getAttributes().put(RendererUtils.SEQUENCE_PARAM, sequence);
- return sequence;
- }
-
- protected Object serializeView(FacesContext context, Object serializedView)
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Entering serializeView");
- }
-
- if(isSerializeStateInSession(context))
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Processing serializeView - serialize state in session");
- }
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
- try
- {
- OutputStream os = baos;
- if(isCompressStateInSession(context))
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Processing serializeView - serialize compressed");
- }
-
- os.write(COMPRESSED_FLAG);
- os = new GZIPOutputStream(os, 1024);
- }
- else
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Processing serializeView - serialize uncompressed");
- }
-
- os.write(UNCOMPRESSED_FLAG);
- }
-
- //Object[] stateArray = (Object[]) serializedView;
-
- ObjectOutputStream out = new ObjectOutputStream(os);
-
- out.writeObject(serializedView);
- //out.writeObject(stateArray[0]);
- //out.writeObject(stateArray[1]);
- out.close();
- baos.close();
-
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Exiting serializeView - serialized. Bytes : " + baos.size());
- }
- return baos.toByteArray();
- }
- catch (IOException e)
- {
- log.log(Level.SEVERE, "Exiting serializeView - Could not serialize state: " + e.getMessage(), e);
- return null;
- }
- }
-
-
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Exiting serializeView - do not serialize state in session.");
- }
-
- return serializedView;
-
- }
-
- /**
- * Reads the value of the <code>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</code> context parameter.
- * @see #SERIALIZE_STATE_IN_SESSION_PARAM
- * @param context <code>FacesContext</code> for the request we are processing.
- * @return boolean true, if the server state should be serialized in the session
- */
- protected boolean isSerializeStateInSession(FacesContext context)
- {
- String value = context.getExternalContext().getInitParameter(
- SERIALIZE_STATE_IN_SESSION_PARAM);
- boolean serialize = DEFAULT_SERIALIZE_STATE_IN_SESSION;
- if (value != null)
- {
- serialize = Boolean.valueOf(value);
- }
- return serialize;
- }
-
- /**
- * Reads the value of the <code>org.apache.myfaces.COMPRESS_STATE_IN_SESSION</code> context parameter.
- * @see #COMPRESS_SERVER_STATE_PARAM
- * @param context <code>FacesContext</code> for the request we are processing.
- * @return boolean true, if the server state steam should be compressed
- */
- protected boolean isCompressStateInSession(FacesContext context)
- {
- String value = context.getExternalContext().getInitParameter(
- COMPRESS_SERVER_STATE_PARAM);
- boolean compress = DEFAULT_COMPRESS_SERVER_STATE_PARAM;
- if (value != null)
- {
- compress = Boolean.valueOf(value);
- }
- return compress;
- }
-
- protected Object deserializeView(Object state)
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Entering deserializeView");
- }
-
- if(state instanceof byte[])
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Processing deserializeView - deserializing serialized state. Bytes : "
- + ((byte[]) state).length);
- }
-
- try
- {
- ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) state);
- InputStream is = bais;
- if(is.read() == COMPRESSED_FLAG)
- {
- is = new GZIPInputStream(is);
- }
- ObjectInputStream ois = null;
- try
- {
- final ObjectInputStream in = new MyFacesObjectInputStream(is);
- ois = in;
- Object object = null;
- if (System.getSecurityManager() != null)
- {
- object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>()
- {
- public Object run() throws PrivilegedActionException, IOException, ClassNotFoundException
- {
- //return new Object[] {in.readObject(), in.readObject()};
- return in.readObject();
- }
- });
- }
- else
- {
- //object = new Object[] {in.readObject(), in.readObject()};
- object = in.readObject();
- }
- return object;
- }
- finally
- {
- if (ois != null)
- {
- ois.close();
- ois = null;
- }
- }
- }
- catch (PrivilegedActionException e)
- {
- log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(), e);
- return null;
- }
- catch (IOException e)
- {
- log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(), e);
- return null;
- }
- catch (ClassNotFoundException e)
- {
- log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(), e);
- return null;
- }
- }
- else if (state instanceof Object[])
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Exiting deserializeView - state not serialized.");
- }
-
- return state;
- }
- else if(state == null)
- {
- log.severe("Exiting deserializeView - this method should not be called with a null-state.");
- return null;
- }
- else
- {
- log.severe("Exiting deserializeView - this method should not be called with a state of type : "
- + state.getClass());
- return null;
- }
- }
-
- protected static class SerializedViewCollection implements Serializable
- {
- private static final long serialVersionUID = -3734849062185115847L;
-
- private final List<SerializedViewKey> _keys
- = new ArrayList<SerializedViewKey>(DEFAULT_NUMBER_OF_VIEWS_IN_SESSION);
- private final Map<SerializedViewKey, Object> _serializedViews = new HashMap<SerializedViewKey, Object>();
-
- private final Map<SerializedViewKey, SerializedViewKey> _precedence =
- new HashMap<SerializedViewKey, SerializedViewKey>();
-
- private Map<String, SerializedViewKey> _lastWindowKeys = null;
-
- // old views will be hold as soft references which will be removed by
- // the garbage collector if free memory is low
- private transient Map<Object, Object> _oldSerializedViews = null;
-
- public synchronized void add(FacesContext context, Object state, SerializedViewKey key,
- SerializedViewKey previousRestoredKey)
- {
- if (state == null)
- {
- state = EMPTY_STATES;
- }
- else if (state instanceof Object[] &&
- ((Object[])state).length == 2 &&
- ((Object[])state)[0] == null &&
- ((Object[])state)[1] == null)
- {
- // The generated state can be considered zero, set it as null
- // into the map.
- state = null;
- }
-
- Integer maxCount = getNumberOfSequentialViewsInSession(context);
- if (maxCount != null)
- {
- if (previousRestoredKey != null)
- {
- if (!_serializedViews.isEmpty())
- {
- _precedence.put((SerializedViewKey) key, previousRestoredKey);
- }
- else
- {
- // Note when the session is invalidated, _serializedViews map is empty,
- // but we could have a not null previousRestoredKey (the last one before
- // invalidate the session), so we need to check that condition before
- // set the precence. In that way, we ensure the precedence map will always
- // have valid keys.
- previousRestoredKey = null;
- }
- }
- }
- _serializedViews.put(key, state);
-
- while (_keys.remove(key))
- {
- // do nothing
- }
- _keys.add(key);
-
- if (previousRestoredKey != null && maxCount != null && maxCount > 0)
- {
- int count = 0;
- SerializedViewKey previousKey = (SerializedViewKey) key;
- do
- {
- previousKey = _precedence.get(previousKey);
- count++;
- } while (previousKey != null && count < maxCount);
-
- if (previousKey != null)
- {
- SerializedViewKey keyToRemove = (SerializedViewKey) previousKey;
- // In theory it should be only one key but just to be sure
- // do it in a loop, but in this case if cache old views is on,
- // put on that map.
- do
- {
- while (_keys.remove(keyToRemove))
- {
- // do nothing
- }
-
- if (_serializedViews.containsKey(keyToRemove) &&
- !CACHE_OLD_VIEWS_IN_SESSION_MODE_OFF.equals(getCacheOldViewsInSessionMode(context)))
- {
- getOldSerializedViewsMap().put(keyToRemove, _serializedViews.remove(keyToRemove));
- }
- else
- {
- _serializedViews.remove(keyToRemove);
- }
-
- keyToRemove = _precedence.remove(keyToRemove);
- } while(keyToRemove != null);
- }
- }
-
- int views = getNumberOfViewsInSession(context);
- while (_keys.size() > views)
- {
- key = _keys.remove(0);
-
- if (maxCount != null && maxCount > 0)
- {
- SerializedViewKey keyToRemove = (SerializedViewKey) key;
- // Note in this case the key to delete is the oldest one,
- // so it could be at least one precedence, but to be safe
- // do it with a loop.
- do
- {
- keyToRemove = _precedence.remove(keyToRemove);
- } while (keyToRemove != null);
- }
-
- if (_serializedViews.containsKey(key) &&
- !CACHE_OLD_VIEWS_IN_SESSION_MODE_OFF.equals(getCacheOldViewsInSessionMode(context)))
- {
-
- getOldSerializedViewsMap().put(key, _serializedViews.remove(key));
- }
- else
- {
- _serializedViews.remove(key);
- }
- }
- }
-
- protected Integer getNumberOfSequentialViewsInSession(FacesContext context)
- {
- return WebConfigParamUtils.getIntegerInitParameter(context.getExternalContext(),
- NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION_PARAM);
- }
-
- /**
- * Reads the amount (default = 20) of views to be stored in session.
- * @see #NUMBER_OF_VIEWS_IN_SESSION_PARAM
- * @param context FacesContext for the current request, we are processing
- * @return Number vf views stored in the session
- */
- protected int getNumberOfViewsInSession(FacesContext context)
- {
- String value = context.getExternalContext().getInitParameter(
- NUMBER_OF_VIEWS_IN_SESSION_PARAM);
- int views = DEFAULT_NUMBER_OF_VIEWS_IN_SESSION;
- if (value != null)
- {
- try
- {
- views = Integer.parseInt(value);
- if (views <= 0)
- {
- log.severe("Configured value for " + NUMBER_OF_VIEWS_IN_SESSION_PARAM
- + " is not valid, must be an value > 0, using default value ("
- + DEFAULT_NUMBER_OF_VIEWS_IN_SESSION);
- views = DEFAULT_NUMBER_OF_VIEWS_IN_SESSION;
- }
- }
- catch (Throwable e)
- {
- log.log(Level.SEVERE, "Error determining the value for " + NUMBER_OF_VIEWS_IN_SESSION_PARAM
- + ", expected an integer value > 0, using default value ("
- + DEFAULT_NUMBER_OF_VIEWS_IN_SESSION + "): " + e.getMessage(), e);
- }
- }
- return views;
- }
-
- public synchronized void putLastWindowKey(FacesContext context, String id, SerializedViewKey key)
- {
- if (_lastWindowKeys == null)
- {
- Integer i = getNumberOfSequentialViewsInSession(context);
- int j = getNumberOfViewsInSession(context);
- if (i != null && i.intValue() > 0)
- {
- _lastWindowKeys = new LRUMap((j / i.intValue()) + 1);
- }
- else
- {
- _lastWindowKeys = new LRUMap(j + 1);
- }
- }
- _lastWindowKeys.put(id, key);
- }
-
- public SerializedViewKey getLastWindowKey(FacesContext context, String id)
- {
- if (_lastWindowKeys != null)
- {
- return _lastWindowKeys.get(id);
- }
- return null;
- }
-
- /**
- * @return old serialized views map
- */
- @SuppressWarnings("unchecked")
- protected Map<Object, Object> getOldSerializedViewsMap()
- {
- FacesContext context = FacesContext.getCurrentInstance();
- if (_oldSerializedViews == null && context != null)
- {
- String cacheMode = getCacheOldViewsInSessionMode(context);
- if (CACHE_OLD_VIEWS_IN_SESSION_MODE_WEAK.equals(cacheMode))
- {
- _oldSerializedViews = new ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK, true);
- }
- else if (CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT_WEAK.equals(cacheMode))
- {
- _oldSerializedViews = new ReferenceMap(AbstractReferenceMap.SOFT, AbstractReferenceMap.WEAK, true);
- }
- else if (CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT.equals(cacheMode))
- {
- _oldSerializedViews = new ReferenceMap(AbstractReferenceMap.SOFT, AbstractReferenceMap.SOFT, true);
- }
- else if (CACHE_OLD_VIEWS_IN_SESSION_MODE_HARD_SOFT.equals(cacheMode))
- {
- _oldSerializedViews = new ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.SOFT);
- }
- }
-
- return _oldSerializedViews;
- }
-
- /**
- * Reads the value of the <code>org.apache.myfaces.CACHE_OLD_VIEWS_IN_SESSION_MODE</code> context parameter.
- *
- * @since 1.2.5
- * @param context
- * @return constant indicating caching mode
- * @see #CACHE_OLD_VIEWS_IN_SESSION_MODE
- */
- protected String getCacheOldViewsInSessionMode(FacesContext context)
- {
- String value = context.getExternalContext().getInitParameter(
- CACHE_OLD_VIEWS_IN_SESSION_MODE);
- if (value == null)
- {
- return CACHE_OLD_VIEWS_IN_SESSION_MODE_OFF;
- }
- else if (value.equalsIgnoreCase(CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT))
- {
- return CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT;
- }
- else if (value.equalsIgnoreCase(CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT_WEAK))
- {
- return CACHE_OLD_VIEWS_IN_SESSION_MODE_SOFT_WEAK;
- }
- else if (value.equalsIgnoreCase(CACHE_OLD_VIEWS_IN_SESSION_MODE_WEAK))
- {
- return CACHE_OLD_VIEWS_IN_SESSION_MODE_WEAK;
- }
- else if (value.equalsIgnoreCase(CACHE_OLD_VIEWS_IN_SESSION_MODE_HARD_SOFT))
- {
- return CACHE_OLD_VIEWS_IN_SESSION_MODE_HARD_SOFT;
- }
- else
- {
- return CACHE_OLD_VIEWS_IN_SESSION_MODE_OFF;
- }
- }
-
- public Object get(SerializedViewKey key)
- {
- Object value = _serializedViews.get(key);
- if (value == null)
- {
- if (_serializedViews.containsKey(key))
- {
- return EMPTY_STATES;
- }
- Map<Object,Object> oldSerializedViewMap = getOldSerializedViewsMap();
- if (oldSerializedViewMap != null)
- {
- value = oldSerializedViewMap.get(key);
- if (value == null && oldSerializedViewMap.containsKey(key) )
- {
- return EMPTY_STATES;
- }
- }
- }
- else if (value instanceof Object[] &&
- ((Object[])value).length == 2 &&
- ((Object[])value)[0] == null &&
- ((Object[])value)[1] == null)
- {
- // Remember inside the state map null is stored as an empty array.
- return null;
- }
- return value;
- }
- }
-
- /**
- * Base implementation where all keys used to identify the state of a view should
- * extend.
- */
- protected abstract static class SerializedViewKey implements Serializable
- {
- }
-
- /**
- * Implementation of SerializedViewKey, where the hashCode of the viewId is used
- * and the sequenceId is a numeric value.
- */
- private static class IntIntSerializedViewKey extends SerializedViewKey
- implements Serializable
- {
- private static final long serialVersionUID = -1170697124386063642L;
-
- private final int _viewId;
- private final int _sequenceId;
-
- public IntIntSerializedViewKey(int viewId, int sequence)
- {
- _sequenceId = sequence;
- _viewId = viewId;
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (obj == null)
- {
- return false;
- }
- if (getClass() != obj.getClass())
- {
- return false;
- }
- final IntIntSerializedViewKey other = (IntIntSerializedViewKey) obj;
- if (this._viewId != other._viewId)
- {
- return false;
- }
- if (this._sequenceId != other._sequenceId)
- {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode()
- {
- int hash = 7;
- hash = 83 * hash + this._viewId;
- hash = 83 * hash + this._sequenceId;
- return hash;
- }
- }
-
- /**
- * Implementation of SerializedViewKey, where the hashCode of the viewId is used
- * and the sequenceId is a string value.
- */
- private static class IntByteArraySerializedViewKey extends SerializedViewKey
- implements Serializable
- {
- private final int _viewId;
- private final byte[] _sequenceId;
-
- public IntByteArraySerializedViewKey(int viewId, byte[] sequence)
- {
- _sequenceId = sequence;
- _viewId = viewId;
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (obj == null)
- {
- return false;
- }
- if (getClass() != obj.getClass())
- {
- return false;
- }
- final IntByteArraySerializedViewKey other = (IntByteArraySerializedViewKey) obj;
- if (this._viewId != other._viewId)
- {
- return false;
- }
- if (!Arrays.equals(this._sequenceId, other._sequenceId))
- {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode()
- {
- int hash = 5;
- hash = 37 * hash + this._viewId;
- hash = 37 * hash + Arrays.hashCode(this._sequenceId);
- return hash;
- }
- }
-
-
- /**
- * Implementation of SerializedViewKey, where the viewId and the sequenceId can be
- * anything.
- */
- private static class ReferenceSerializedViewKey<I,K> extends SerializedViewKey
- implements Serializable
- {
- private static final long serialVersionUID = -1170697124386063642L;
-
- private final I _viewId;
- private final K _sequenceId;
-
- public ReferenceSerializedViewKey()
- {
- _sequenceId = null;
- _viewId = null;
- }
- public ReferenceSerializedViewKey(I viewId, K sequence)
- {
- _sequenceId = sequence;
- _viewId = viewId;
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (obj == null)
- {
- return false;
- }
- if (getClass() != obj.getClass())
- {
- return false;
- }
- final ReferenceSerializedViewKey<I, K> other = (ReferenceSerializedViewKey<I, K>) obj;
- if (this._viewId != other._viewId && (this._viewId == null || !this._viewId.equals(other._viewId)))
- {
- return false;
- }
- if (this._sequenceId != other._sequenceId &&
- (this._sequenceId == null || !this._sequenceId.equals(other._sequenceId)))
- {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode()
- {
- int hash = 7;
- hash = 83 * hash + (this._viewId != null ? this._viewId.hashCode() : 0);
- hash = 83 * hash + (this._sequenceId != null ? this._sequenceId.hashCode() : 0);
- return hash;
- }
- }
-
- //------------------------------------- METHOD FROM StateCache ------------------------------------------------
-
- @Override
- public Object saveSerializedView(FacesContext facesContext, Object serializedView)
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Processing saveSerializedView - server-side state saving - save state");
- }
- //save state in server session
- saveSerializedViewInServletSession(facesContext, serializedView);
-
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Exiting saveSerializedView - server-side state saving - saved state");
- }
-
- return encodeSerializedState(facesContext, serializedView);
- }
-
- @Override
- public Object restoreSerializedView(FacesContext facesContext, String viewId, Object viewState)
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.finest("Restoring view from session");
- }
-
- Object serverStateId = getServerStateId(facesContext, viewState);
-
- return (serverStateId == null)
- ? null
- : getSerializedViewFromServletSession(facesContext, viewId, serverStateId);
- }
-
- public Object encodeSerializedState(FacesContext facesContext, Object serializedView)
- {
- return getKeyFactory(facesContext).encode(getNextViewSequence(facesContext));
- }
-
- @Override
- public boolean isWriteStateAfterRenderViewRequired(FacesContext facesContext)
- {
- return false;
- }
-
- //------------------------------------- Custom methods -----------------------------------------------------
-
- private boolean isUseFlashScopePurgeViewsInSession(ExternalContext externalContext)
- {
- if (_useFlashScopePurgeViewsInSession == null)
- {
- _useFlashScopePurgeViewsInSession = WebConfigParamUtils.getBooleanInitParameter(
- externalContext, USE_FLASH_SCOPE_PURGE_VIEWS_IN_SESSION, false);
- }
- return _useFlashScopePurgeViewsInSession;
- }
-
- private Integer getNumberOfSequentialViewsInSession(ExternalContext externalContext)
- {
- if (!_numberOfSequentialViewsInSessionSet)
- {
- _numberOfSequentialViewsInSession = WebConfigParamUtils.getIntegerInitParameter(
- externalContext,
- NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION_PARAM);
- _numberOfSequentialViewsInSessionSet = true;
- }
- return _numberOfSequentialViewsInSession;
- }
-
- protected KeyFactory getKeyFactory(FacesContext facesContext)
- {
- //return keyFactory;
- return sessionViewStorageFactory.getKeyFactory();
- }
-
- protected SessionViewStorageFactory getSessionViewStorageFactory()
- {
- return sessionViewStorageFactory;
- }
-
-
- protected abstract static class KeyFactory<K, V>
- {
-
- /**
- * Generates a unique key per session
- *
- * @param facesContext
- * @return
- */
- public abstract K generateKey(FacesContext facesContext);
-
- /**
- * Encode a Key into a value that will be used as view state session token
- *
- * @param key
- * @return
- */
- public abstract V encode(K key);
-
- /**
- * Decode a view state session token into a key
- *
- * @param value
- * @return
- */
- public abstract K decode(V value);
-
- }
-
- private static class CounterKeyFactory extends KeyFactory<Integer, String>
- {
- /**
- * Take the counter from session scope and increment
- *
- * @param facesContext
- * @return
- */
- @Override
- public Integer generateKey(FacesContext facesContext)
- {
- ExternalContext externalContext = facesContext.getExternalContext();
- Object sessionObj = externalContext.getSession(true);
- Integer sequence = null;
- synchronized(sessionObj) // synchronized to increase sequence if multiple requests
- // are handled at the same time for the session
- {
- Map<String, Object> map = externalContext.getSessionMap();
- sequence = (Integer) map.get(RendererUtils.SEQUENCE_PARAM);
- if(sequence == null || sequence.intValue() == Integer.MAX_VALUE)
- {
- sequence = Integer.valueOf(1);
- }
- else
- {
- sequence = Integer.valueOf(sequence.intValue() + 1);
- }
- map.put(RendererUtils.SEQUENCE_PARAM, sequence);
- }
- return sequence;
- }
-
- public String encode(Integer sequence)
- {
- return Integer.toString(sequence, Character.MAX_RADIX);
- }
-
- public Integer decode(String serverStateId)
- {
- return Integer.valueOf((String) serverStateId, Character.MAX_RADIX);
- }
- }
-
- /**
- * This factory generate a key composed by a counter and a random number. The
- * counter ensures uniqueness, and the random number prevents guess the next
- * session token.
- */
- private static class SecureRandomKeyFactory extends KeyFactory<byte[], String>
- {
- private final SessionIdGenerator sessionIdGenerator;
- private final int length;
-
- public SecureRandomKeyFactory(FacesContext facesContext)
- {
- length = WebConfigParamUtils.getIntegerInitParameter(facesContext.getExternalContext(),
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_LENGTH_PARAM,
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_LENGTH_PARAM_DEFAULT);
- sessionIdGenerator = new SessionIdGenerator();
- sessionIdGenerator.setSessionIdLength(length);
- String secureRandomClass = WebConfigParamUtils.getStringInitParameter(
- facesContext.getExternalContext(),
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_CLASS_PARAM);
- if (secureRandomClass != null)
- {
- sessionIdGenerator.setSecureRandomClass(secureRandomClass);
- }
- String secureRandomProvider = WebConfigParamUtils.getStringInitParameter(
- facesContext.getExternalContext(),
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_PROVIDER_PARAM);
- if (secureRandomProvider != null)
- {
- sessionIdGenerator.setSecureRandomProvider(secureRandomProvider);
- }
- String secureRandomAlgorithm = WebConfigParamUtils.getStringInitParameter(
- facesContext.getExternalContext(),
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_SECURE_RANDOM_ALGORITM_PARAM);
- if (secureRandomAlgorithm != null)
- {
- sessionIdGenerator.setSecureRandomAlgorithm(secureRandomAlgorithm);
- }
- }
-
- public Integer generateCounterKey(FacesContext facesContext)
- {
- ExternalContext externalContext = facesContext.getExternalContext();
- Object sessionObj = externalContext.getSession(true);
- Integer sequence = null;
- synchronized(sessionObj) // synchronized to increase sequence if multiple requests
- // are handled at the same time for the session
- {
- Map<String, Object> map = externalContext.getSessionMap();
- sequence = (Integer) map.get(RendererUtils.SEQUENCE_PARAM);
- if(sequence == null || sequence.intValue() == Integer.MAX_VALUE)
- {
- sequence = Integer.valueOf(1);
- }
- else
- {
- sequence = Integer.valueOf(sequence.intValue() + 1);
- }
- map.put(RendererUtils.SEQUENCE_PARAM, sequence);
- }
- return sequence;
- }
-
- @Override
- public byte[] generateKey(FacesContext facesContext)
- {
- byte[] array = new byte[length];
- byte[] key = new byte[length+4];
-
- sessionIdGenerator.getRandomBytes(array);
- for (int i = 0; i < array.length; i++)
- {
- key[i] = array[i];
- }
- int value = generateCounterKey(facesContext);
- key[array.length] = (byte) (value >>> 24);
- key[array.length+1] = (byte) (value >>> 16);
- key[array.length+2] = (byte) (value >>> 8);
- key[array.length+3] = (byte) (value);
-
- return key;
- }
-
- @Override
- public String encode(byte[] key)
- {
- return new String(Hex.encodeHex(key));
- }
-
- @Override
- public byte[] decode(String value)
- {
- try
- {
- return Hex.decodeHex(value.toCharArray());
- }
- catch (DecoderException ex)
- {
- // Cannot decode, ignore silently, later it will be handled as
- // ViewExpiredException
- }
- return null;
- }
- }
-
- private static class RandomKeyFactory extends KeyFactory<byte[], String>
- {
- private final Random random;
- private final int length;
-
- public RandomKeyFactory(FacesContext facesContext)
- {
- length = WebConfigParamUtils.getIntegerInitParameter(facesContext.getExternalContext(),
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_LENGTH_PARAM,
- RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN_LENGTH_PARAM_DEFAULT);
- random = new Random(((int)System.nanoTime())+this.hashCode());
- }
-
- public Integer generateCounterKey(FacesContext facesContext)
- {
- ExternalContext externalContext = facesContext.getExternalContext();
- Object sessionObj = externalContext.getSession(true);
- Integer sequence = null;
- synchronized(sessionObj) // synchronized to increase sequence if multiple requests
- // are handled at the same time for the session
- {
- Map<String, Object> map = externalContext.getSessionMap();
- sequence = (Integer) map.get(RendererUtils.SEQUENCE_PARAM);
- if(sequence == null || sequence.intValue() == Integer.MAX_VALUE)
- {
- sequence = Integer.valueOf(1);
- }
- else
- {
- sequence = Integer.valueOf(sequence.intValue() + 1);
- }
- map.put(RendererUtils.SEQUENCE_PARAM, sequence);
- }
- return sequence;
- }
-
- @Override
- public byte[] generateKey(FacesContext facesContext)
- {
- byte[] array = new byte[length];
- byte[] key = new byte[length+4];
-
- //sessionIdGenerator.getRandomBytes(array);
- random.nextBytes(array);
- for (int i = 0; i < array.length; i++)
- {
- key[i] = array[i];
- }
- int value = generateCounterKey(facesContext);
- key[array.length] = (byte) (value >>> 24);
- key[array.length+1] = (byte) (value >>> 16);
- key[array.length+2] = (byte) (value >>> 8);
- key[array.length+3] = (byte) (value);
-
- return key;
- }
-
- @Override
- public String encode(byte[] key)
- {
- return new String(Hex.encodeHex(key));
- }
-
- @Override
- public byte[] decode(String value)
- {
- try
- {
- return Hex.decodeHex(value.toCharArray());
- }
- catch (DecoderException ex)
- {
- // Cannot decode, ignore silently, later it will be handled as
- // ViewExpiredException
- }
- return null;
- }
- }
-
- /**
- *
- * @param <T>
- * @param <K>
- * @param <V>
- */
- protected abstract static class SessionViewStorageFactory <T extends KeyFactory<K,V>, K, V >
- {
- private KeyFactory<K, V> keyFactory;
-
- public SessionViewStorageFactory(KeyFactory<K, V> keyFactory)
- {
- this.keyFactory = keyFactory;
- }
-
- public KeyFactory<K, V> getKeyFactory()
- {
- return keyFactory;
- }
-
- public abstract SerializedViewCollection createSerializedViewCollection(
- FacesContext context);
-
- public abstract SerializedViewKey createSerializedViewKey(
- FacesContext facesContext, String viewId, K key);
-
- }
-
- private static class CounterSessionViewStorageFactory
- extends SessionViewStorageFactory <KeyFactory <Integer,String>, Integer, String>
- {
- public CounterSessionViewStorageFactory(KeyFactory<Integer, String> keyFactory)
- {
- super(keyFactory);
- }
-
- @Override
- public SerializedViewCollection createSerializedViewCollection(
- FacesContext context)
- {
- return new SerializedViewCollection();
- }
-
- @Override
- public SerializedViewKey createSerializedViewKey(
- FacesContext context, String viewId, Integer key)
- {
- if (context.isProjectStage(ProjectStage.Production))
- {
- return new IntIntSerializedViewKey(viewId == null ? 0 : viewId.hashCode(), key);
- }
- else
- {
- return new ReferenceSerializedViewKey(viewId, key);
- }
- }
- }
-
- private static class RandomSessionViewStorageFactory
- extends SessionViewStorageFactory <KeyFactory <byte[],String>, byte[], String>
- {
- public RandomSessionViewStorageFactory(KeyFactory<byte[], String> keyFactory)
- {
- super(keyFactory);
- }
-
- @Override
- public SerializedViewCollection createSerializedViewCollection(
- FacesContext context)
- {
- return new SerializedViewCollection();
- }
-
- @Override
- public SerializedViewKey createSerializedViewKey(
- FacesContext context, String viewId, byte[] key)
- {
- if (context.isProjectStage(ProjectStage.Production))
- {
- return new IntByteArraySerializedViewKey(viewId == null ? 0 : viewId.hashCode(), key);
- }
- else
- {
- return new ReferenceSerializedViewKey(viewId, key);
- }
- }
- }
-}
diff --git a/impl/src/main/java/org/apache/myfaces/renderkit/SessionIdGenerator.java b/impl/src/main/java/org/apache/myfaces/renderkit/SessionIdGenerator.java
deleted file mode 100644
index dd09fef..0000000
--- a/impl/src/main/java/org/apache/myfaces/renderkit/SessionIdGenerator.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.myfaces.renderkit;
-
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.SecureRandom;
-import java.util.Queue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * NOTE: Class taken from tomcat 7 org.apache.catalina.util.SessionIdGenerator
- * and used here as an alternative for server side state token encryption.
- *
- * @author Leonardo Uribe
- */
-class SessionIdGenerator
-{
-
- private static Logger log = Logger.getLogger(SessionIdGenerator.class.getName());
- //private static StringManager sm =
- // StringManager.getManager("org.apache.catalina.util");
-
- /**
- * Queue of random number generator objects to be used when creating session
- * identifiers. If the queue is empty when a random number generator is
- * required, a new random number generator object is created. This is
- * designed this way since random number generators use a sync to make them
- * thread-safe and the sync makes using a a single object slow(er).
- */
- private Queue<SecureRandom> randoms =
- new ConcurrentLinkedQueue<SecureRandom>();
- /**
- * The Java class name of the secure random number generator class to be
- * used when generating session identifiers. The random number generator
- * class must be self-seeding and have a zero-argument constructor. If not
- * specified, an instance of {@link SecureRandom} will be generated.
- */
- private String secureRandomClass = null;
- /**
- * The name of the algorithm to use to create instances of
- * {@link SecureRandom} which are used to generate session IDs. If no
- * algorithm is specified, SHA1PRNG is used. To use the platform default
- * (which may be SHA1PRNG), specify the empty string. If an invalid
- * algorithm and/or provider is specified the {@link SecureRandom} instances
- * will be created using the defaults. If that fails, the {@link
- * SecureRandom} instances will be created using platform defaults.
- */
- private String secureRandomAlgorithm = "SHA1PRNG";
- /**
- * The name of the provider to use to create instances of
- * {@link SecureRandom} which are used to generate session IDs. If no
- * algorithm is specified the of SHA1PRNG default is used. If an invalid
- * algorithm and/or provider is specified the {@link SecureRandom} instances
- * will be created using the defaults. If that fails, the {@link
- * SecureRandom} instances will be created using platform defaults.
- */
- private String secureRandomProvider = null;
- /**
- * Node identifier when in a cluster. Defaults to the empty string.
- */
- private String jvmRoute = "";
- /**
- * Number of bytes in a session ID. Defaults to 16.
- */
- private int sessionIdLength = 16;
-
- /**
- * Specify a non-default @{link {@link SecureRandom} implementation to use.
- *
- * @param secureRandomClass The fully-qualified class name
- */
- public void setSecureRandomClass(String secureRandomClass)
- {
- this.secureRandomClass = secureRandomClass;
- }
-
- /**
- * Specify a non-default algorithm to use to generate random numbers.
- *
- * @param secureRandomAlgorithm The name of the algorithm
- */
- public void setSecureRandomAlgorithm(String secureRandomAlgorithm)
- {
- this.secureRandomAlgorithm = secureRandomAlgorithm;
- }
-
- /**
- * Specify a non-default provider to use to generate random numbers.
- *
- * @param secureRandomProvider The name of the provider
- */
- public void setSecureRandomProvider(String secureRandomProvider)
- {
- this.secureRandomProvider = secureRandomProvider;
- }
-
- /**
- * Specify the node identifier associated with this node which will be
- * included in the generated session ID.
- *
- * @param jvmRoute The node identifier
- */
- public void setJvmRoute(String jvmRoute)
- {
- this.jvmRoute = jvmRoute;
- }
-
- /**
- * Specify the number of bytes for a session ID
- *
- * @param sessionIdLength Number of bytes
- */
- public void setSessionIdLength(int sessionIdLength)
- {
- this.sessionIdLength = sessionIdLength;
- }
-
- /**
- * Generate and return a new session identifier.
- */
- public String generateSessionId()
- {
-
- byte random[] = new byte[16];
-
- // Render the result as a String of hexadecimal digits
- StringBuilder buffer = new StringBuilder();
-
- int resultLenBytes = 0;
-
- while (resultLenBytes < sessionIdLength)
- {
- getRandomBytes(random);
- for (int j = 0;
- j < random.length && resultLenBytes < sessionIdLength;
- j++)
- {
- byte b1 = (byte) ((random[j] & 0xf0) >> 4);
- byte b2 = (byte) (random[j] & 0x0f);
- if (b1 < 10)
- {
- buffer.append((char) ('0' + b1));
- }
- else
- {
- buffer.append((char) ('A' + (b1 - 10)));
- }
- if (b2 < 10)
- {
- buffer.append((char) ('0' + b2));
- }
- else
- {
- buffer.append((char) ('A' + (b2 - 10)));
- }
- resultLenBytes++;
- }
- }
-
- if (jvmRoute != null && jvmRoute.length() > 0)
- {
- buffer.append('.').append(jvmRoute);
- }
-
- return buffer.toString();
- }
-
- public void getRandomBytes(byte bytes[])
- {
- SecureRandom random = randoms.poll();
- if (random == null)
- {
- random = createSecureRandom();
- }
- random.nextBytes(bytes);
- randoms.add(random);
- }
-
- /**
- * Create a new random number generator instance we should use for
- * generating session identifiers.
- */
- private SecureRandom createSecureRandom()
- {
-
- SecureRandom result = null;
-
- long t1 = System.currentTimeMillis();
- if (secureRandomClass != null)
- {
- try
- {
- // Construct and seed a new random number generator
- Class<?> clazz = Class.forName(secureRandomClass);
- result = (SecureRandom) clazz.newInstance();
- }
- catch (Exception e)
- {
- log.log(Level.SEVERE, "Exception initializing random number generator of class "+
- secureRandomClass + ". Falling back to java.secure.SecureRandom", e);
- }
- }
-
- if (result == null)
- {
- // No secureRandomClass or creation failed. Use SecureRandom.
- try
- {
- if (secureRandomProvider != null
- && secureRandomProvider.length() > 0)
- {
- result = SecureRandom.getInstance(secureRandomAlgorithm,
- secureRandomProvider);
- }
- else
- {
- if (secureRandomAlgorithm != null
- && secureRandomAlgorithm.length() > 0)
- {
- result = SecureRandom.getInstance(secureRandomAlgorithm);
- }
- }
- }
- catch (NoSuchAlgorithmException e)
- {
- log.log(Level.SEVERE, "Exception initializing random number generator using algorithm: "+
- secureRandomAlgorithm, e);
- }
- catch (NoSuchProviderException e)
- {
- log.log(Level.SEVERE, "Exception initializing random number generator using provider: " +
- secureRandomProvider, e);
- }
- }
-
- if (result == null)
- {
- // Invalid provider / algorithm
- try
- {
- result = SecureRandom.getInstance("SHA1PRNG");
- }
- catch (NoSuchAlgorithmException e)
- {
- log.log(Level.SEVERE, "Invalid provider / algoritm SHA1PRNG for generate secure random token", e);
- }
- }
-
- if (result == null)
- {
- // Nothing works - use platform default
- result = new SecureRandom();
- }
-
- // Force seeding to take place
- result.nextInt();
-
- long t2 = System.currentTimeMillis();
- if ((t2 - t1) > 100)
- {
- if (log.isLoggable(Level.FINEST))
- {
- log.info("Creation of SecureRandom instance for session ID generation using ["
- +result.getAlgorithm()+"] took ["+Long.valueOf(t2 - t1)+"] milliseconds.");
- }
- }
- return result;
- }
-}
diff --git a/impl/src/main/java/org/apache/myfaces/renderkit/StateCacheFactoryImpl.java b/impl/src/main/java/org/apache/myfaces/renderkit/StateCacheFactoryImpl.java
deleted file mode 100644
index 0fbbf15..0000000
--- a/impl/src/main/java/org/apache/myfaces/renderkit/StateCacheFactoryImpl.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.myfaces.renderkit;
-
-import javax.faces.context.FacesContext;
-
-import org.apache.myfaces.application.StateCache;
-import org.apache.myfaces.application.StateCacheFactory;
-
-public class StateCacheFactoryImpl extends StateCacheFactory
-{
-
- private StateCache _clientSideStateCache;
- private StateCache _serverSideStateCache;
-
- public StateCacheFactoryImpl()
- {
- _clientSideStateCache = new ClientSideStateCacheImpl();
- _serverSideStateCache = new ServerSideStateCacheImpl();
- }
-
- @Override
- public StateCache getStateCache(FacesContext facesContext)
- {
- if (facesContext.getApplication().getStateManager().isSavingStateInClient(facesContext))
- {
- return _clientSideStateCache;
- }
- else
- {
- return _serverSideStateCache;
- }
- }
-}
diff --git a/impl/src/main/java/org/apache/myfaces/renderkit/StateCacheUtils.java b/impl/src/main/java/org/apache/myfaces/renderkit/StateCacheUtils.java
deleted file mode 100644
index 7bdc15a..0000000
--- a/impl/src/main/java/org/apache/myfaces/renderkit/StateCacheUtils.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.myfaces.renderkit;
-
-import javax.faces.FacesWrapper;
-import javax.faces.render.ResponseStateManager;
-
-public class StateCacheUtils
-{
- public static boolean isMyFacesResponseStateManager(ResponseStateManager rsm)
- {
- if (rsm instanceof MyfacesResponseStateManager)
- {
- return true;
- }
- else
- {
- ResponseStateManager rsm1 = rsm;
- while (rsm1 != null)
- {
- if (rsm1 instanceof MyfacesResponseStateManager)
- {
- return true;
- }
- if (rsm1 instanceof FacesWrapper)
- {
- rsm1 = ((FacesWrapper<? extends ResponseStateManager>) rsm1).getWrapped();
- }
- else
- {
- rsm1 = null;
- }
- }
- return false;
- }
- }
-
- public static MyfacesResponseStateManager getMyFacesResponseStateManager(ResponseStateManager rsm)
- {
- if (rsm instanceof MyfacesResponseStateManager)
- {
- return (MyfacesResponseStateManager) rsm;
- }
- else
- {
- ResponseStateManager rsm1 = rsm;
- while (rsm1 != null)
- {
- if (rsm1 instanceof MyfacesResponseStateManager)
- {
- return (MyfacesResponseStateManager) rsm1;
- }
- if (rsm1 instanceof FacesWrapper)
- {
- rsm1 = ((FacesWrapper<? extends ResponseStateManager>) rsm1).getWrapped();
- }
- else
- {
- rsm1 = null;
- }
- }
- return null;
- }
- }
-}
diff --git a/impl/src/main/java/org/apache/myfaces/renderkit/html/HtmlResponseStateManager.java b/impl/src/main/java/org/apache/myfaces/renderkit/html/HtmlResponseStateManager.java
index 845aa95..6ee30d4 100755
--- a/impl/src/main/java/org/apache/myfaces/renderkit/html/HtmlResponseStateManager.java
+++ b/impl/src/main/java/org/apache/myfaces/renderkit/html/HtmlResponseStateManager.java
@@ -33,9 +33,9 @@ import javax.faces.render.ResponseStateManager;
import org.apache.myfaces.application.StateCache;
import org.apache.myfaces.application.StateCacheFactory;
+import org.apache.myfaces.application.viewstate.StateCacheFactoryImpl;
import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFWebConfigParam;
import org.apache.myfaces.renderkit.MyfacesResponseStateManager;
-import org.apache.myfaces.renderkit.StateCacheFactoryImpl;
import org.apache.myfaces.shared.config.MyfacesConfig;
import org.apache.myfaces.shared.renderkit.html.HTML;
import org.apache.myfaces.shared.renderkit.html.HtmlRendererUtils;
diff --git a/impl/src/main/java/org/apache/myfaces/view/jsp/JspViewDeclarationLanguage.java b/impl/src/main/java/org/apache/myfaces/view/jsp/JspViewDeclarationLanguage.java
index 7d74920..5c9f203 100644
--- a/impl/src/main/java/org/apache/myfaces/view/jsp/JspViewDeclarationLanguage.java
+++ b/impl/src/main/java/org/apache/myfaces/view/jsp/JspViewDeclarationLanguage.java
@@ -35,7 +35,7 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.core.Config;
import org.apache.myfaces.application.jsp.ServletViewResponseWrapper;
-import org.apache.myfaces.renderkit.StateCacheUtils;
+import org.apache.myfaces.application.viewstate.StateCacheUtils;
import org.apache.myfaces.shared.view.JspViewDeclarationLanguageBase;
import org.apache.myfaces.view.facelets.tag.composite.CompositeLibrary;
import org.apache.myfaces.view.facelets.tag.jsf.core.CoreLibrary;
diff --git a/impl/src/test/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheTest.java b/impl/src/test/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheTest.java
index a601f3b..80c921e 100644
--- a/impl/src/test/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheTest.java
+++ b/impl/src/test/java/org/apache/myfaces/application/viewstate/ClientSideStateCacheTest.java
@@ -1,19 +1,22 @@
/*
- * Copyright 2012 The Apache Software Foundation.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
-package org.apache.myfaces.renderkit;
+package org.apache.myfaces.application.viewstate;
import javax.faces.application.StateManager;
import org.apache.myfaces.application.StateCache;
diff --git a/impl/src/test/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheTest.java b/impl/src/test/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheTest.java
index cf680c0..d6f230f 100644
--- a/impl/src/test/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheTest.java
+++ b/impl/src/test/java/org/apache/myfaces/application/viewstate/ServerSideStateCacheTest.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.myfaces.renderkit;
+package org.apache.myfaces.application.viewstate;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
diff --git a/impl/src/test/java/org/apache/myfaces/renderkit/ClientSideStateCacheTest.java b/impl/src/test/java/org/apache/myfaces/renderkit/ClientSideStateCacheTest.java
deleted file mode 100644
index a601f3b..0000000
--- a/impl/src/test/java/org/apache/myfaces/renderkit/ClientSideStateCacheTest.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright 2012 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.myfaces.renderkit;
-
-import javax.faces.application.StateManager;
-import org.apache.myfaces.application.StateCache;
-import org.apache.myfaces.test.base.junit4.AbstractJsfConfigurableMultipleRequestsTestCase;
-import org.junit.Test;
-import org.testng.Assert;
-
-/**
- *
- * @author lu4242
- */
-public class ClientSideStateCacheTest extends AbstractJsfConfigurableMultipleRequestsTestCase
-{
-
- private static final int TIMESTAMP_PARAM = 2;
-
- @Test
- public void testSaveRestoreState() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_CLIENT);
-
- // Initialization
- setupRequest();
- StateCache stateCache = new ClientSideStateCacheImpl();
- tearDownRequest();
-
- Object savedToken;
- Object firstSavedToken;
-
- try
- {
- setupRequest();
-
- facesContext.getViewRoot().setViewId("view1.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 1);
- firstSavedToken = savedToken;
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- Object value = stateCache.restoreSerializedView(facesContext, "view1.xhtml", savedToken);
-
- Assert.assertEquals(1, value);
-
- facesContext.getViewRoot().setViewId("view2.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 2);
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- Object value = stateCache.restoreSerializedView(facesContext, "view2.xhtml", savedToken);
-
- Assert.assertEquals(2, value);
-
- facesContext.getViewRoot().setViewId("view2.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 3);
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- Object value = stateCache.restoreSerializedView(facesContext, "view1.xhtml", firstSavedToken);
-
- Assert.assertEquals(1, value);
- }
- finally
- {
- tearDownRequest();
- }
- }
-
- @Test
- public void testSaveRestoreStateWrongViewId() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_CLIENT);
-
- // Initialization
- setupRequest();
- StateCache stateCache = new ClientSideStateCacheImpl();
- tearDownRequest();
-
- Object savedToken;
- Object firstSavedToken;
-
- try
- {
- setupRequest();
-
- facesContext.getViewRoot().setViewId("/view1.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 1);
- firstSavedToken = savedToken;
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- // Note we are trying to restore restoring another different view with a token from the previous view.
- // It should return null and later throw ViewExpiredException
- // In client side state saving, the encoded viewId inside the state should be compared against the passed one.
- // as parameter.
- Object value = stateCache.restoreSerializedView(facesContext, "/view2.xhtml", firstSavedToken);
-
- Assert.assertNull(value);
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- // It should restore this:
- Object value = stateCache.restoreSerializedView(facesContext, "/view1.xhtml", firstSavedToken);
-
- Assert.assertEquals(1, value);
- }
- finally
- {
- tearDownRequest();
- }
-
- }
-
- @Test
- public void testSaveRestoreStateClientTimeout() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_CLIENT);
- servletContext.addInitParameter(ClientSideStateCacheImpl.INIT_PARAM_CLIENT_VIEW_STATE_TIMEOUT, "2");
-
- // Initialization
- setupRequest();
- StateCache stateCache = new ClientSideStateCacheImpl();
- tearDownRequest();
-
- Object savedToken;
- Object firstSavedToken;
-
- try
- {
- setupRequest();
-
- facesContext.getViewRoot().setViewId("/view1.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 1);
- firstSavedToken = savedToken;
- }
- finally
- {
- tearDownRequest();
- }
-
- //Change timestamp to a previous date
- Long timestamp = (Long)((Object[])firstSavedToken)[TIMESTAMP_PARAM];
- ((Object[])firstSavedToken)[TIMESTAMP_PARAM] = timestamp.longValue() - 60000*3;
-
- try
- {
- setupRequest();
-
- // It should return null, because the timeStamp was changed to a previous date
- Object value = stateCache.restoreSerializedView(facesContext, "/view1.xhtml", firstSavedToken);
-
- Assert.assertNull(value);
- }
- finally
- {
- tearDownRequest();
- }
- }
-
-
-}
diff --git a/impl/src/test/java/org/apache/myfaces/renderkit/ServerSideStateCacheTest.java b/impl/src/test/java/org/apache/myfaces/renderkit/ServerSideStateCacheTest.java
deleted file mode 100644
index cf680c0..0000000
--- a/impl/src/test/java/org/apache/myfaces/renderkit/ServerSideStateCacheTest.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.myfaces.renderkit;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.Map;
-import javax.faces.application.ProjectStage;
-import javax.faces.application.StateManager;
-
-import org.apache.myfaces.application.StateCache;
-import org.apache.myfaces.test.base.junit4.AbstractJsfConfigurableMultipleRequestsTestCase;
-import org.junit.Test;
-import org.testng.Assert;
-
-public class ServerSideStateCacheTest extends AbstractJsfConfigurableMultipleRequestsTestCase
-{
-
- @Test
- public void testNumberOfSequentialViewsInSession() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_SERVER);
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION", "5");
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION", "2");
-
- // Initialization
- setupRequest();
- StateCache stateCache = new ServerSideStateCacheImpl();
- tearDownRequest();
-
- Object savedToken;
- Object firstSavedToken;
-
- try
- {
- setupRequest();
-
- facesContext.getViewRoot().setViewId("view1.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 1);
- firstSavedToken = savedToken;
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- Object value = stateCache.restoreSerializedView(facesContext, "view1.xhtml", savedToken);
-
- Assert.assertEquals(1, value);
-
- facesContext.getViewRoot().setViewId("view2.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 2);
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- Object value = stateCache.restoreSerializedView(facesContext, "view2.xhtml", savedToken);
-
- Assert.assertEquals(2, value);
-
- facesContext.getViewRoot().setViewId("view2.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 3);
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- Object value = stateCache.restoreSerializedView(facesContext, "view1.xhtml", firstSavedToken);
-
- // Since org.apache.myfaces.NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION is 2, the first one was already discarded
- Assert.assertNull(value);
- }
- finally
- {
- tearDownRequest();
- }
- }
-
- @Test
- public void testSaveRestoreStateWrongViewId() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_SERVER);
-
- // Initialization
- setupRequest();
- StateCache stateCache = new ClientSideStateCacheImpl();
- tearDownRequest();
-
- Object savedToken;
- Object firstSavedToken;
-
- try
- {
- setupRequest();
-
- facesContext.getViewRoot().setViewId("/view1.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 1);
- firstSavedToken = savedToken;
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- // Note we are trying to restore restoring another different view with a token from the previous view.
- // It should return null and later throw ViewExpiredException
- // In server side state saving, the hashCode of the viewId should be part of the key used to restore
- // the state, along with a counter.
- Object value = stateCache.restoreSerializedView(facesContext, "/view2.xhtml", firstSavedToken);
-
- Assert.assertNull(value);
- }
- finally
- {
- tearDownRequest();
- }
-
- try
- {
- setupRequest();
-
- // It should restore this:
- Object value = stateCache.restoreSerializedView(facesContext, "/view1.xhtml", firstSavedToken);
-
- Assert.assertEquals(1, value);
- }
- finally
- {
- tearDownRequest();
- }
-
- }
-
- @Test
- public void testNonExistingViewId() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_SERVER);
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION", "5");
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION", "2");
-
- // this issue only happens in projectstage Production
- servletContext.addInitParameter("faces.PROJECT_STAGE", "Production");
-
- try
- {
- // Initialization
- setupRequest();
-
- // we need to take a viewId which is null -> not existing.
- facesContext.getViewRoot().setViewId(null);
-
- StateCache stateCache = new ServerSideStateCacheImpl();
- Object savedToken = stateCache.saveSerializedView(facesContext, 1);
-
- }
- finally
- {
- tearDownRequest();
- }
-
- }
-
- public void tryStateKeySerialization() throws Exception
- {
- // Initialization
- setupRequest();
- StateCache stateCache = new ServerSideStateCacheImpl();
- tearDownRequest();
-
- Object savedToken;
- Object firstSavedToken;
-
- try
- {
- setupRequest();
- facesContext.getViewRoot().setViewId("view1.xhtml");
- savedToken = stateCache.saveSerializedView(facesContext, 1);
- firstSavedToken = savedToken;
-
- for (Map.Entry<String, Object> entry : facesContext.getExternalContext().getSessionMap().entrySet())
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(128);
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(entry.getValue());
- oos.flush();
- baos.flush();
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- ObjectInputStream ois = new ObjectInputStream(bais);
- Object blorg = ois.readObject();
- }
- }
- finally
- {
- tearDownRequest();
- }
- }
-
- @Test
- public void testStateKeySerialization1() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_SERVER);
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION", "5");
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION", "2");
- servletContext.addInitParameter(ProjectStage.PROJECT_STAGE_PARAM_NAME, ProjectStage.Production.toString());
-
- tryStateKeySerialization();
- }
-
- @Test
- public void testStateKeySerialization2() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_SERVER);
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION", "5");
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION", "2");
- servletContext.addInitParameter(ProjectStage.PROJECT_STAGE_PARAM_NAME, ProjectStage.Production.toString());
- servletContext.addInitParameter("org.apache.myfaces.RANDOM_KEY_IN_VIEW_STATE_SESSION_TOKEN", "random");
-
- tryStateKeySerialization();
- }
-
- @Test
- public void testStateKeySerialization3() throws Exception
- {
- servletContext.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME, StateManager.STATE_SAVING_METHOD_SERVER);
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION", "5");
- servletContext.addInitParameter("org.apache.myfaces.NUMBER_OF_SEQUENTIAL_VIEWS_IN_SESSION", "2");
- servletContext.addInitParameter(ProjectStage.PROJECT_STAGE_PARAM_NAME, ProjectStage.Development.toString());
-
- tryStateKeySerialization();
- }
-
-}
--
To stop receiving notification emails like this one, please contact
deki@apache.org.