1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.cache.key;
16  
17  import com.liferay.portal.kernel.cache.key.CacheKeyGenerator;
18  import com.liferay.portal.kernel.log.Log;
19  import com.liferay.portal.kernel.log.LogFactoryUtil;
20  import com.liferay.portal.kernel.util.StringBundler;
21  
22  import java.security.MessageDigest;
23  
24  /**
25   * <a href="JavaMD5CacheKeyGenerator.java.html"><b><i>View Source</i></b></a>
26   *
27   * @author Michael C. Han
28   */
29  public class JavaMD5CacheKeyGenerator implements CacheKeyGenerator {
30  
31      public String getCacheKey(String key) {
32          try {
33              return doGetCacheKey(key);
34          }
35          catch (Exception e) {
36              _log.error(e, e);
37  
38              return key;
39          }
40      }
41  
42      public void setMaxLength(int maxLength) {
43          _maxLength = maxLength;
44      }
45  
46      protected String doGetCacheKey(String key) throws Exception {
47          if ((_maxLength > -1) && (key.length() < _maxLength)) {
48              return key;
49          }
50  
51          MessageDigest messageDigest = MessageDigest.getInstance(_ALGORITHM_MD5);
52  
53          messageDigest.update(key.getBytes());
54  
55          byte[] bytes = messageDigest.digest();
56  
57          StringBundler sb = new StringBundler(2 * bytes.length);
58  
59          for (int i = 0; i < bytes.length; i++) {
60              int value = bytes[i] & 0xff;
61  
62              sb.append((char)_HEX_CHARACTERS[value >> 4]);
63              sb.append((char)_HEX_CHARACTERS[value & 0xf]);
64          }
65  
66          return sb.toString();
67      }
68  
69      private static final String _ALGORITHM_MD5 = "MD5";
70  
71      private static final byte[] _HEX_CHARACTERS = {
72          '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
73          'e', 'f'
74      };
75  
76      private static Log _log = LogFactoryUtil.getLog(
77          JavaMD5CacheKeyGenerator.class);
78  
79      private int _maxLength = -1;
80  
81  }