001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2014-2015 ForgeRock AS.
015 */
016
017package org.forgerock.openig.jwt.dirty;
018
019import java.util.Collection;
020import java.util.Iterator;
021import java.util.Set;
022
023import org.forgerock.http.util.SetDecorator;
024
025/**
026 * A {@link Set} decorator that notifies the provided {@link DirtyListener} when one ore more elements are removed.
027 * @param <E> type of the set
028 */
029public class DirtySet<E> extends SetDecorator<E> {
030
031    private final DirtyListener listener;
032
033    /**
034     * Constructs a new set decorator, wrapping the specified set.
035     *
036     * @param set
037     *         the set to wrap with the decorator.
038     * @param listener
039     *         the change observer
040     */
041    public DirtySet(final Set<E> set, final DirtyListener listener) {
042        super(set);
043        this.listener = listener;
044    }
045
046    @Override
047    public Iterator<E> iterator() {
048        return new DirtyIterator<>(super.iterator(), listener);
049    }
050
051    @Override
052    public boolean remove(final Object o) {
053        if (super.remove(o)) {
054            listener.onElementsRemoved();
055            return true;
056        }
057        return false;
058    }
059
060    @Override
061    public boolean removeAll(final Collection<?> c) {
062        if (super.removeAll(c)) {
063            listener.onElementsRemoved();
064            return true;
065        }
066        return false;
067    }
068
069    @Override
070    public boolean retainAll(final Collection<?> c) {
071        if (super.retainAll(c)) {
072            listener.onElementsRemoved();
073            return true;
074        }
075        return false;
076    }
077
078    @Override
079    public void clear() {
080        super.clear();
081        listener.onElementsRemoved();
082    }
083}