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;
29 import com.allanbank.mongodb.bson.NumericElement;
30 import com.allanbank.mongodb.client.message.Reply;
31 import com.allanbank.mongodb.error.ReplyException;
32
33
34
35
36
37
38
39
40
41 public class ReplyLongCallback extends AbstractReplyCallback<Long> {
42
43
44 public static final String DEFAULT_NAME = "n";
45
46
47
48
49
50 private final String myName;
51
52
53
54
55
56
57
58 public ReplyLongCallback(final Callback<Long> results) {
59 this(DEFAULT_NAME, results);
60 }
61
62
63
64
65
66
67
68
69
70 public ReplyLongCallback(final String name, final Callback<Long> results) {
71 super(results);
72
73 myName = name;
74 }
75
76
77
78
79
80
81
82
83
84
85
86 @Override
87 protected MongoDbException asError(final Reply reply) {
88 MongoDbException error = super.asError(reply);
89 if (error == null) {
90 final List<Document> results = reply.getResults();
91 if (results.size() == 1) {
92 final Document doc = results.get(0);
93 final Element nElem = doc.get(myName);
94 if (!(nElem instanceof NumericElement)) {
95 error = new ReplyException(reply, "Missing '" + myName
96 + "' field in reply.");
97 }
98 }
99 }
100 return error;
101 }
102
103
104
105
106
107
108
109
110
111 @Override
112 protected Long convert(final Reply reply) throws MongoDbException {
113 final List<Document> results = reply.getResults();
114 if (results.size() == 1) {
115 final Document doc = results.get(0);
116 final Element nElem = doc.get(myName);
117 return Long.valueOf(toLong(nElem));
118 }
119
120 return Long.valueOf(-1);
121 }
122
123
124
125
126
127
128
129
130
131 protected long toLong(final Element element) {
132 if (element instanceof NumericElement) {
133 return ((NumericElement) element).getLongValue();
134 }
135
136 return -1;
137 }
138 }