001/*
002 *  Copyright 2019 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.core.impl.cache;
017
018import java.util.ArrayList;
019import java.util.List;
020import java.util.Objects;
021
022/**
023 * AbstractCacheKey Class used to create cache keys as tuples
024 */
025public abstract class AbstractCacheKey
026{
027
028    private List< ? super Object> _fields;
029
030    private boolean _isKeyOnlyForInvalidate;
031
032    /** 
033     * AbstractCacheKey
034     * @param fields list of fields in the key
035     */
036    protected AbstractCacheKey(Object... fields)
037    {
038        _fields = new ArrayList<>();
039        for (Object field : fields)
040        {
041            if (field == null)
042            {
043                _isKeyOnlyForInvalidate = true;
044            }
045            _fields.add(field);
046        }
047    }
048
049    /** 
050     * true if one of fields is null
051     * @return true if the key is used for mass invalidation
052     */
053    public boolean isKeyOnlyForInvalidate()
054    {
055        return _isKeyOnlyForInvalidate;
056    }
057
058    /** 
059     * get list of fields
060     * @return the list of fields
061     */
062    public List< ? super Object> getFields()
063    {
064        return _fields;
065    }
066
067    @Override
068    public int hashCode()
069    {
070        return Objects.hash(_fields);
071    }
072
073    @Override
074    public boolean equals(Object obj)
075    {
076        if (this == obj)
077        {
078            return true;
079        }
080        if (obj == null)
081        {
082            return false;
083        }
084        if (getClass() != obj.getClass())
085        {
086            return false;
087        }
088        AbstractCacheKey other = (AbstractCacheKey) obj;
089        return Objects.equals(_fields, other._fields);
090    }
091    
092    @Override
093    public String toString()
094    {
095        return _fields.toString(); // will print '[field1Value, field2Value, ...]'
096    }
097
098}