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.key;
017
018import javax.annotation.Nonnull;
019import java.util.HashSet;
020import java.util.Iterator;
021import java.util.Set;
022
023import org.bouncycastle.openpgp.PGPPublicKey;
024import org.bouncycastle.openpgp.PGPPublicKeyRing;
025import org.pgpainless.util.MultiMap;
026
027/**
028 * Key Selection Strategy which accepts {@link PGPPublicKey}s that are accepted by the abstract method
029 * {@link #accept(Object, Object)}.
030 *
031 * @param <O> Type that describes the owner of the key.
032 */
033public abstract class PublicKeySelectionStrategy<O> implements KeySelectionStrategy<PGPPublicKey, PGPPublicKeyRing, O> {
034
035    @Override
036    public Set<PGPPublicKey> selectKeysFromKeyRing(O identifier, @Nonnull PGPPublicKeyRing ring) {
037        Set<PGPPublicKey> keys = new HashSet<>();
038        for (Iterator<PGPPublicKey> i = ring.getPublicKeys(); i.hasNext(); ) {
039            PGPPublicKey key = i.next();
040            if (accept(identifier, key)) keys.add(key);
041        }
042        return keys;
043    }
044
045    @Override
046    public MultiMap<O, PGPPublicKey> selectKeysFromKeyRings(@Nonnull MultiMap<O, PGPPublicKeyRing> keyRings) {
047        MultiMap<O, PGPPublicKey> keys = new MultiMap<>();
048        for (O identifier : keyRings.keySet()) {
049            for (PGPPublicKeyRing ring : keyRings.get(identifier)) {
050                keys.put(identifier, selectKeysFromKeyRing(identifier, ring));
051            }
052        }
053        return keys;
054    }
055}