001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.cache.key;
016    
017    import com.liferay.portal.kernel.cache.key.CacheKeyGenerator;
018    import com.liferay.portal.kernel.util.StringBundler;
019    import com.liferay.portal.kernel.util.StringUtil;
020    
021    /**
022     * @author Michael C. Han
023     * @author Shuyang Zhou
024     */
025    public class HashCodeCacheKeyGenerator extends BaseCacheKeyGenerator {
026    
027            public CacheKeyGenerator clone() {
028                    return new HashCodeCacheKeyGenerator();
029            }
030    
031            public String getCacheKey(String key) {
032                    return StringUtil.toHexString(key.hashCode());
033            }
034    
035            public String getCacheKey(String[] keys) {
036                    int hashCode = 0;
037                    int weight = 1;
038    
039                    for (int i = keys.length - 1; i >= 0; i--) {
040                            String s = keys[i];
041    
042                            hashCode = s.hashCode() * weight + hashCode;
043    
044                            for (int j = 0; j < s.length(); j++) {
045                                    weight *= 31;
046                            }
047                    }
048    
049                    return StringUtil.toHexString(hashCode);
050            }
051    
052            public String getCacheKey(StringBundler sb) {
053                    int hashCode = 0;
054                    int weight = 1;
055    
056                    for (int i = sb.index() - 1; i >= 0; i--) {
057                            String s = sb.stringAt(i);
058    
059                            hashCode = s.hashCode() * weight + hashCode;
060    
061                            for (int j = 0; j < s.length(); j++) {
062                                    weight *= 31;
063                            }
064                    }
065    
066                    return StringUtil.toHexString(hashCode);
067            }
068    
069    }