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.List;
24
25 import com.allanbank.mongodb.Callback;
26 import com.allanbank.mongodb.MongoDbException;
27 import com.allanbank.mongodb.bson.Document;
28 import com.allanbank.mongodb.bson.element.DocumentElement;
29 import com.allanbank.mongodb.client.message.Reply;
30 import com.allanbank.mongodb.error.ReplyException;
31
32
33
34
35
36
37
38
39
40 public class ReplyDocumentCallback extends AbstractReplyCallback<Document> {
41
42
43 public static final String DEFAULT_NAME = "value";
44
45
46 private final String myName;
47
48
49
50
51
52
53
54 public ReplyDocumentCallback(final Callback<Document> results) {
55 this(DEFAULT_NAME, results);
56 }
57
58
59
60
61
62
63
64
65
66 public ReplyDocumentCallback(final String name,
67 final Callback<Document> results) {
68 super(results);
69
70 myName = name;
71 }
72
73
74
75
76
77
78
79
80
81
82
83
84 @Override
85 protected MongoDbException asError(final Reply reply) {
86 MongoDbException error = super.asError(reply);
87 if (error == null) {
88 final List<Document> results = reply.getResults();
89 if (results.size() != 1) {
90 error = new ReplyException(reply,
91 "Should only be a single document in the reply.");
92 }
93 else if (reply.getResults().get(0).get(myName) == null) {
94 error = new ReplyException(reply, "No '" + myName
95 + "' document in the reply.");
96 }
97 }
98 return error;
99 }
100
101
102
103
104
105
106
107
108
109 @Override
110 protected Document convert(final Reply reply) throws MongoDbException {
111 final List<Document> results = reply.getResults();
112 if (results.size() == 1) {
113 final DocumentElement element = results.get(0).get(
114 DocumentElement.class, myName);
115 if (element == null) {
116 return null;
117 }
118 return element.getDocument();
119 }
120
121 return null;
122 }
123 }