001: package org.bouncycastle.cms;
002:
003: import java.util.ArrayList;
004: import java.util.Collection;
005: import java.util.Collections;
006: import java.util.HashMap;
007: import java.util.Iterator;
008: import java.util.List;
009: import java.util.Map;
010:
011: public class RecipientInformationStore {
012: private Map table = new HashMap();
013:
014: public RecipientInformationStore(Collection recipientInfos) {
015: Iterator it = recipientInfos.iterator();
016:
017: while (it.hasNext()) {
018: RecipientInformation recipientInformation = (RecipientInformation) it
019: .next();
020: RecipientId rid = recipientInformation.getRID();
021:
022: if (table.get(rid) == null) {
023: table.put(rid, recipientInformation);
024: } else {
025: Object o = table.get(rid);
026:
027: if (o instanceof List) {
028: ((List) o).add(recipientInformation);
029: } else {
030: List l = new ArrayList();
031:
032: l.add(o);
033: l.add(recipientInformation);
034:
035: table.put(rid, l);
036: }
037: }
038: }
039: }
040:
041: /**
042: * Return the first RecipientInformation object that matches the
043: * passed in selector. Null if there are no matches.
044: *
045: * @param selector to identify a recipient
046: * @return a single RecipientInformation object. Null if none matches.
047: */
048: public RecipientInformation get(RecipientId selector) {
049: Object o = table.get(selector);
050:
051: if (o instanceof List) {
052: return (RecipientInformation) ((List) o).get(0);
053: } else {
054: return (RecipientInformation) o;
055: }
056: }
057:
058: /**
059: * Return the number of recipients in the collection.
060: *
061: * @return number of recipients identified.
062: */
063: public int size() {
064: Iterator it = table.values().iterator();
065: int count = 0;
066:
067: while (it.hasNext()) {
068: Object o = it.next();
069:
070: if (o instanceof List) {
071: count += ((List) o).size();
072: } else {
073: count++;
074: }
075: }
076:
077: return count;
078: }
079:
080: /**
081: * Return all recipients in the collection
082: *
083: * @return a collection of recipients.
084: */
085: public Collection getRecipients() {
086: List list = new ArrayList(table.size());
087: Iterator it = table.values().iterator();
088:
089: while (it.hasNext()) {
090: Object o = it.next();
091:
092: if (o instanceof List) {
093: list.addAll((List) o);
094: } else {
095: list.add(o);
096: }
097: }
098:
099: return list;
100: }
101:
102: /**
103: * Return possible empty collection with recipients matching the passed in RecipientId
104: *
105: * @param selector a recipient id to select against.
106: * @return a collection of RecipientInformation objects.
107: */
108: public Collection getRecipients(RecipientId selector) {
109: Object o = table.get(selector);
110:
111: if (o instanceof List) {
112: return new ArrayList((List) o);
113: } else if (o != null) {
114: return Collections.singletonList(o);
115: }
116:
117: return new ArrayList();
118: }
119: }
|