001 package org.apache.myfaces.tobago.util; 002 003 /* 004 * Licensed to the Apache Software Foundation (ASF) under one or more 005 * contributor license agreements. See the NOTICE file distributed with 006 * this work for additional information regarding copyright ownership. 007 * The ASF licenses this file to You under the Apache License, Version 2.0 008 * (the "License"); you may not use this file except in compliance with 009 * the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019 020 import javax.faces.context.FacesContext; 021 import java.util.HashSet; 022 import java.util.Map; 023 import java.util.Locale; 024 025 public class AccessKeyMap { 026 027 private static final char[] KEYS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 028 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 029 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 030 031 private static final String REQUEST_MAP_KEY = "accessKeysRequestMapKey"; 032 033 private HashSet set; 034 private String dublicated = ""; 035 036 037 public static AccessKeyMap getInstance(FacesContext facesContext) { 038 final Map requestMap = facesContext.getExternalContext().getRequestMap(); 039 AccessKeyMap keyMap = (AccessKeyMap) requestMap.get(REQUEST_MAP_KEY); 040 if (keyMap == null) { 041 keyMap = new AccessKeyMap(); 042 requestMap.put(REQUEST_MAP_KEY, keyMap); 043 } 044 return keyMap; 045 } 046 047 private AccessKeyMap() { 048 set = new HashSet(); 049 } 050 051 private HashSet getSet() { 052 return set; 053 } 054 055 private String getDublicated() { 056 return dublicated; 057 } 058 059 private void addDublicated(char key) { 060 dublicated = dublicated + key; 061 } 062 063 public static boolean addAccessKey(FacesContext facesContext, Character key) { 064 key = new Character(key.toString().toLowerCase(Locale.ENGLISH).charAt(0)); 065 final AccessKeyMap instance = getInstance(facesContext); 066 if (instance.getSet().contains(key)) { 067 instance.addDublicated(key.charValue()); 068 return false; 069 } else { 070 instance.getSet().add(key); 071 return true; 072 } 073 } 074 075 076 public static String getDublicatedKeys(FacesContext facesContext) { 077 return getInstance(facesContext).getDublicated(); 078 } 079 080 public static String getUnusedKeys(FacesContext facesContext) { 081 HashSet set = getInstance(facesContext).getSet(); 082 StringBuilder sb = new StringBuilder(); 083 for (int i = 0; i < KEYS.length; i++) { 084 if (!set.contains(new Character(KEYS[i]))) { 085 sb.append(KEYS[i]); 086 } 087 } 088 return sb.toString(); 089 } 090 }