1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.myfaces.application.viewstate;
20
21 import java.util.Map;
22 import javax.faces.context.ExternalContext;
23 import javax.faces.context.FacesContext;
24 import org.apache.myfaces.shared.renderkit.RendererUtils;
25
26 /**
27 *
28 */
29 class CounterKeyFactory extends KeyFactory<Integer>
30 {
31
32 /**
33 * Take the counter from session scope and increment
34 *
35 * @param facesContext
36 * @return
37 */
38 @Override
39 public Integer generateKey(FacesContext facesContext)
40 {
41 ExternalContext externalContext = facesContext.getExternalContext();
42 Object sessionObj = externalContext.getSession(true);
43 Integer sequence = null;
44 // synchronized to increase sequence if multiple requests
45 // are handled at the same time for the session
46 synchronized (sessionObj)
47 {
48 Map<String, Object> map = externalContext.getSessionMap();
49 sequence = (Integer) map.get(RendererUtils.SEQUENCE_PARAM);
50 if (sequence == null || sequence.intValue() == Integer.MAX_VALUE)
51 {
52 sequence = Integer.valueOf(1);
53 }
54 else
55 {
56 sequence = Integer.valueOf(sequence.intValue() + 1);
57 }
58 map.put(RendererUtils.SEQUENCE_PARAM, sequence);
59 }
60 return sequence;
61 }
62
63 public String encode(Integer sequence)
64 {
65 return Integer.toString(sequence, Character.MAX_RADIX);
66 }
67
68 public Integer decode(String serverStateId)
69 {
70 return Integer.valueOf((String) serverStateId, Character.MAX_RADIX);
71 }
72
73 }