001/*
002 * Copyright 2018 Paul Schaub.
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.pgpainless.key.selection.keyring;
017
018import javax.annotation.Nonnull;
019import java.util.HashSet;
020import java.util.Iterator;
021import java.util.Set;
022
023import org.bouncycastle.openpgp.PGPSecretKeyRing;
024import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
025import org.pgpainless.util.MultiMap;
026
027public abstract class SecretKeyRingSelectionStrategy<O> implements KeyRingSelectionStrategy<PGPSecretKeyRing, PGPSecretKeyRingCollection, O> {
028    @Override
029    public Set<PGPSecretKeyRing> selectKeyRingsFromCollection(O identifier, @Nonnull PGPSecretKeyRingCollection keyRingCollection) {
030        Set<PGPSecretKeyRing> accepted = new HashSet<>();
031        for (Iterator<PGPSecretKeyRing> i = keyRingCollection.getKeyRings(); i.hasNext(); ) {
032            PGPSecretKeyRing ring = i.next();
033            if (accept(identifier, ring)) accepted.add(ring);
034        }
035        return accepted;
036    }
037
038    @Override
039    public MultiMap<O, PGPSecretKeyRing> selectKeyRingsFromCollections(@Nonnull MultiMap<O, PGPSecretKeyRingCollection> keyRingCollections) {
040        MultiMap<O, PGPSecretKeyRing> keyRings = new MultiMap<>();
041        for (O identifier : keyRingCollections.keySet()) {
042            for (PGPSecretKeyRingCollection collection : keyRingCollections.get(identifier)) {
043                keyRings.put(identifier, selectKeyRingsFromCollection(identifier, collection));
044            }
045        }
046        return keyRings;
047    }
048}