001    /**
002     * Copyright (c) 2000-present 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    
020    /**
021     * @author Michael C. Han
022     * @author Shuyang Zhou
023     */
024    public class HashCodeCacheKeyGenerator extends BaseCacheKeyGenerator {
025    
026            @Override
027            public CacheKeyGenerator clone() {
028                    return new HashCodeCacheKeyGenerator();
029            }
030    
031            @Override
032            public Integer getCacheKey(String key) {
033                    return key.hashCode();
034            }
035    
036            @Override
037            public Integer getCacheKey(String[] keys) {
038                    int hashCode = 0;
039                    int weight = 1;
040    
041                    for (int i = keys.length - 1; i >= 0; i--) {
042                            String s = keys[i];
043    
044                            hashCode = s.hashCode() * weight + hashCode;
045    
046                            for (int j = s.length(); j > 0; j--) {
047                                    weight *= 31;
048                            }
049                    }
050    
051                    return hashCode;
052            }
053    
054            @Override
055            public Integer getCacheKey(StringBundler sb) {
056                    int hashCode = 0;
057                    int weight = 1;
058    
059                    String[] array = sb.getStrings();
060    
061                    for (int i = sb.index() - 1; i >= 0; i--) {
062                            String s = array[i];
063    
064                            hashCode = s.hashCode() * weight + hashCode;
065    
066                            for (int j = s.length(); j > 0; j--) {
067                                    weight *= 31;
068                            }
069                    }
070    
071                    return hashCode;
072            }
073    
074    }