001    /**
002     * Copyright (c) 2000-2013 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.Digester;
019    import com.liferay.portal.kernel.util.StringBundler;
020    
021    import java.security.NoSuchAlgorithmException;
022    
023    /**
024     * @author Michael C. Han
025     * @author Shuyang Zhou
026     * @author Vilmos Papp
027     */
028    public class JavaMD5CacheKeyGenerator extends MessageDigestCacheKeyGenerator {
029    
030            public JavaMD5CacheKeyGenerator() throws NoSuchAlgorithmException {
031                    this(-1);
032            }
033    
034            public JavaMD5CacheKeyGenerator(int maxLength)
035                    throws NoSuchAlgorithmException {
036    
037                    super(Digester.MD5);
038    
039                    _maxLength = maxLength;
040            }
041    
042            @Override
043            public CacheKeyGenerator clone() {
044                    try {
045                            return new JavaMD5CacheKeyGenerator(_maxLength);
046                    }
047                    catch (NoSuchAlgorithmException nsae) {
048                            throw new IllegalStateException(nsae.getMessage(), nsae);
049                    }
050            }
051    
052            @Override
053            public String getCacheKey(String key) {
054                    if ((_maxLength > -1) && (key.length() < _maxLength)) {
055                            return key;
056                    }
057    
058                    return (String)super.getCacheKey(key);
059            }
060    
061            @Override
062            public String getCacheKey(StringBundler sb) {
063                    if ((_maxLength > -1) && (sb.length() < _maxLength)) {
064                            return sb.toString();
065                    }
066    
067                    return (String)super.getCacheKey(sb);
068            }
069    
070            public void setMaxLength(int maxLength) {
071                    _maxLength = maxLength;
072            }
073    
074            private int _maxLength = -1;
075    
076    }