001/*
002 * Shredzone Commons
003 *
004 * Copyright (C) 2012 Richard "Shred" Körber
005 *   http://commons.shredzone.org
006 *
007 * This program is free software: you can redistribute it and/or modify
008 * it under the terms of the GNU Library General Public License as
009 * published by the Free Software Foundation, either version 3 of the
010 * License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU Library General Public License
018 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
019 */
020
021package org.shredzone.commons.view;
022
023import static java.util.stream.Collectors.joining;
024
025import java.util.Arrays;
026import java.util.Collection;
027
028import javax.annotation.ParametersAreNonnullByDefault;
029
030/**
031 * A signature is a hash key for a set of String elements. It is ensured that the same
032 * collection of Strings results in an equal signature object, irregarding of the string
033 * order.
034 * <p>
035 * Signatures are immutable.
036 *
037 * @author Richard "Shred" Körber
038 */
039@ParametersAreNonnullByDefault
040public final class Signature {
041
042    private final String sig;
043
044    /**
045     * Instantiates a new signature.
046     *
047     * @param elements
048     *            collection of strings to build the signature for
049     */
050    public Signature(Collection<String> elements) {
051        this.sig = elements.stream()
052                .filter(e -> e != null && !e.isEmpty())
053                .sorted()
054                .collect(joining("|"));
055    }
056
057    /**
058     * Instantiates a new signature.
059     *
060     * @param elements
061     *            array of strings to build the signature for.
062     */
063    public Signature(String[] elements) {
064        this(Arrays.asList(elements));
065    }
066
067    @Override
068    public boolean equals(Object obj) {
069        if (obj == null || !(obj instanceof Signature)) {
070            return false;
071        }
072        return ((Signature) obj).sig.equals(sig);
073    }
074
075    @Override
076    public int hashCode() {
077        return sig.hashCode();
078    }
079
080    @Override
081    public String toString() {
082        return sig;
083    }
084
085}