/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.cache.key;

import com.liferay.portal.kernel.cache.key.CacheKeyGenerator;
import com.liferay.portal.kernel.util.Digester;
import com.liferay.portal.kernel.util.StringBundler;

import java.security.NoSuchAlgorithmException;

/**
 * @author Michael C. Han
 * @author Shuyang Zhou
 * @author Vilmos Papp
 */
public class JavaMD5CacheKeyGenerator extends MessageDigestCacheKeyGenerator {

	public JavaMD5CacheKeyGenerator() throws NoSuchAlgorithmException {
		this(-1);
	}

	public JavaMD5CacheKeyGenerator(int maxLength)
		throws NoSuchAlgorithmException {

		super(Digester.MD5);

		_maxLength = maxLength;
	}

	@Override
	public CacheKeyGenerator clone() {
		try {
			return new JavaMD5CacheKeyGenerator(_maxLength);
		}
		catch (NoSuchAlgorithmException nsae) {
			throw new IllegalStateException(nsae.getMessage(), nsae);
		}
	}

	@Override
	public String getCacheKey(String key) {
		if ((_maxLength > -1) && (key.length() < _maxLength)) {
			return key;
		}

		return (String)super.getCacheKey(key);
	}

	@Override
	public String getCacheKey(StringBundler sb) {
		if ((_maxLength > -1) && (sb.length() < _maxLength)) {
			return sb.toString();
		}

		return (String)super.getCacheKey(sb);
	}

	public void setMaxLength(int maxLength) {
		_maxLength = maxLength;
	}

	private int _maxLength = -1;

}