1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package com.allanbank.mongodb.client.callback;
22
23 import java.util.Collections;
24 import java.util.List;
25
26 import com.allanbank.mongodb.Callback;
27 import com.allanbank.mongodb.MongoDbException;
28 import com.allanbank.mongodb.MongoIterator;
29 import com.allanbank.mongodb.bson.Document;
30 import com.allanbank.mongodb.bson.Element;
31 import com.allanbank.mongodb.bson.element.ArrayElement;
32 import com.allanbank.mongodb.client.SimpleMongoIteratorImpl;
33 import com.allanbank.mongodb.client.message.Reply;
34 import com.allanbank.mongodb.error.ReplyException;
35
36
37
38
39
40
41
42
43
44 public class ReplyArrayCallback extends
45 AbstractReplyCallback<MongoIterator<Element>> {
46
47
48 public static final String DEFAULT_NAME = "values";
49
50
51 private final String myName;
52
53
54
55
56
57
58
59 public ReplyArrayCallback(final Callback<MongoIterator<Element>> results) {
60 this(DEFAULT_NAME, results);
61 }
62
63
64
65
66
67
68
69
70
71 public ReplyArrayCallback(final String name,
72 final Callback<MongoIterator<Element>> results) {
73 super(results);
74
75 myName = name;
76 }
77
78
79
80
81
82
83
84
85
86
87
88
89 @Override
90 protected MongoDbException asError(final Reply reply) {
91 MongoDbException error = super.asError(reply);
92 if (error == null) {
93 final List<Document> results = reply.getResults();
94 if (results.size() != 1) {
95 error = new ReplyException(reply,
96 "Should only be a single document in the reply.");
97 }
98 else if (reply.getResults().get(0).find(ArrayElement.class, myName)
99 .isEmpty()) {
100 error = new ReplyException(reply, "No '" + myName
101 + "' array in the reply.");
102 }
103 }
104 return error;
105 }
106
107
108
109
110
111
112
113
114
115 @Override
116 protected MongoIterator<Element> convert(final Reply reply)
117 throws MongoDbException {
118 final List<Document> results = reply.getResults();
119 if (results.size() == 1) {
120 List<Element> entries = Collections.emptyList();
121 final Document document = results.get(0);
122 final ArrayElement array = document.findFirst(ArrayElement.class,
123 myName);
124 if (array != null) {
125 entries = array.getEntries();
126 }
127
128 return new SimpleMongoIteratorImpl<Element>(entries);
129 }
130
131 return null;
132 }
133 }