001/*
002 * nimbus-jose-jwt
003 *
004 * Copyright 2012-2016, Connect2id Ltd.
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
007 * this file except in compliance with the License. You may obtain a copy of the
008 * License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software distributed
013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
015 * specific language governing permissions and limitations under the License.
016 */
017
018package com.nimbusds.jose.jwk;
019
020
021import java.util.*;
022
023import net.jcip.annotations.Immutable;
024
025
026/**
027 * Selects (filters) one or more JSON Web Keys (JWKs) from a JWK set.
028 *
029 * @author Vladimir Dzhuvinov
030 * @version 2015-04-15
031 */
032@Immutable
033public final class JWKSelector {
034
035
036        /**
037         * The JWK matcher.
038         */
039        private final JWKMatcher matcher;
040
041
042        /**
043         * Creates a new JWK selector (filter).
044         *
045         * @param matcher Specifies the JWK matching criteria. Must not be
046         *                {@code null}.
047         */
048        public JWKSelector(final JWKMatcher matcher) {
049
050                if (matcher == null) {
051                        throw new IllegalArgumentException("The JWK matcher must not be null");
052                }
053
054                this.matcher = matcher;
055        }
056
057
058        /**
059         * Returns the JWK matcher.
060         *
061         * @return The JWK matcher.
062         */
063        public JWKMatcher getMatcher() {
064
065                return matcher;
066        }
067
068
069        /**
070         * Selects the keys from the specified JWK set according to the
071         * matcher's criteria.
072         *
073         * @param jwkSet The JWK set. May be {@code null}.
074         *
075         * @return The selected keys, ordered by their position in the JWK set,
076         *         empty list if none were matched or the JWK is {@code null}.
077         */
078        public List<JWK> select(final JWKSet jwkSet) {
079
080                List<JWK> selectedKeys = new LinkedList<>();
081
082                if (jwkSet == null)
083                        return selectedKeys;
084
085                for (JWK key: jwkSet.getKeys()) {
086
087                        if (matcher.matches(key)) {
088                                selectedKeys.add(key);
089                        }
090                }
091
092                return selectedKeys;
093        }
094}