-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathBatchManager.java
More file actions
480 lines (434 loc) · 15.3 KB
/
BatchManager.java
File metadata and controls
480 lines (434 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*
* Copyright (c) 2010-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
*/
package com.marklogic.client.example.extension;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.FailedRequestException;
import com.marklogic.client.MarkLogicIOException;
import com.marklogic.client.document.DocumentDescriptor;
import com.marklogic.client.document.DocumentManager;
import com.marklogic.client.extensions.ResourceManager;
import com.marklogic.client.extensions.ResourceServices.ServiceResult;
import com.marklogic.client.extensions.ResourceServices.ServiceResultIterator;
import com.marklogic.client.io.BaseHandle;
import com.marklogic.client.io.DOMHandle;
import com.marklogic.client.io.DocumentMetadataHandle;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.io.marker.AbstractReadHandle;
import com.marklogic.client.io.marker.AbstractWriteHandle;
import com.marklogic.client.io.marker.XMLReadHandle;
import com.marklogic.client.util.RequestParameters;
/**
* BatchManager provides an extension for executing a batch of document requests.
*/
public class BatchManager extends ResourceManager {
public class BatchRequest {
private Map<String,InputItem> items = new LinkedHashMap<>();
BatchRequest() {
super();
}
public Set<DocumentManager.Metadata> listCategories(DocumentManager.Metadata... categories) {
if (categories == null || categories.length == 0) {
return null;
}
Set<DocumentManager.Metadata> catSet = new HashSet<>();
for (DocumentManager.Metadata category: categories) {
catSet.add(category);
}
return catSet;
}
// TODO: DocumentDescriptor overloads
public BatchRequest withDelete(String uri) {
items.put(uri, new DeleteInput());
return this;
}
public BatchRequest withRead(String uri, String mimetype) {
return withRead(uri, (Set<DocumentManager.Metadata>) null, mimetype);
}
public BatchRequest withRead(String uri, DocumentManager.Metadata category, String mimetype) {
return withRead(uri, listCategories(category), mimetype);
}
public BatchRequest withRead(String uri, Set<DocumentManager.Metadata> categories, String mimetype) {
items.put(uri, new ReadInput().withMetadata(categories).withMimetype(mimetype));
return this;
}
public BatchRequest withWrite(String uri, AbstractWriteHandle content) {
return withWrite(uri, null, content);
}
// TODO: allow any metadata handle
public BatchRequest withWrite(String uri, DocumentMetadataHandle metadata, AbstractWriteHandle content) {
items.put(uri, new WriteInput().withMetadata(metadata).withContent(content));
return this;
}
}
// TODO: assemble a single thread-safe queue instead of two separate queues
static public class BatchResponse implements Iterator<OutputItem> {
boolean success = false;
Iterator<OutputItem> items;
ServiceResultIterator results;
BatchResponse() {
super();
}
public boolean getSuccess() {
return success;
}
@Override
public boolean hasNext() {
if (items == null)
return false;
return items.hasNext();
}
@Override
public OutputItem next() {
if (items == null)
return null;
OutputItem item = items.next();
if (item.exceptionMimetype != null) {
if (results == null || !results.hasNext()) {
throw new IllegalStateException("unable to get exception for request");
}
item.exception = results.next();
} else if (item instanceof ReadOutput) {
ReadOutput ritem = (ReadOutput) item;
if (ritem.metadataMimetype != null) {
if (results == null || !results.hasNext()) {
throw new IllegalStateException("unable to get metadata for read request");
}
ritem.metadata = results.next();
}
if (ritem.contentMimetype != null) {
if (results == null || !results.hasNext()) {
throw new IllegalStateException("unable to get content for read request");
}
ritem.content = results.next();
}
}
if (results != null && !results.hasNext()) {
results.close();
results = null;
}
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove output item");
}
public void close() {
if (results != null) {
results.close();
results = null;
}
items = null;
}
}
class InputItem {
DocumentDescriptor desc;
InputItem withDescriptor(DocumentDescriptor desc) {
this.desc = desc;
return this;
}
DocumentDescriptor getDescriptor() {
return desc;
}
}
class DeleteInput extends InputItem {
}
class ReadInput extends InputItem {
Set<DocumentManager.Metadata> categories;
String mimetype;
ReadInput withMetadata(Set<DocumentManager.Metadata> categories) {
this.categories = categories;
return this;
}
ReadInput withMimetype(String mimetype) {
this.mimetype = mimetype;
return this;
}
}
class WriteInput extends InputItem {
DocumentMetadataHandle metadata;
AbstractWriteHandle content;
WriteInput withMetadata(DocumentMetadataHandle metadata) {
this.metadata = metadata;
return this;
}
WriteInput withContent(AbstractWriteHandle content) {
if (content == null)
return this;
if (!(content instanceof BaseHandle)) {
throw new MarkLogicIOException(
"Write handle does not extend base handle:"+
content.getClass().getName());
}
this.content = content;
return this;
}
@SuppressWarnings("rawtypes")
String getContentMimetype() {
return ((BaseHandle) content).getMimetype();
}
DocumentMetadataHandle getMetadata() {
return metadata;
}
AbstractWriteHandle getContent() {
return content;
}
}
/**
* Enumerates the operations supported on a document in the batch.
*/
public enum OperationType {
DELETE, READ, WRITE;
}
abstract public class OutputItem {
String uri;
// DocumentDescriptor desc;
boolean success = false;
String exceptionMimetype;
ServiceResult exception;
OutputItem() {
super();
}
abstract public OperationType getOperationType();
public String getUri() {
return uri;
}
/*
public DocumentDescriptor getDesc() {
return desc;
}
*/
public boolean getSuccess() {
return success;
}
public boolean hasException() {
return (exception != null);
}
// TODO: expose throwable exception
public <R extends XMLReadHandle> R getException(R handle) {
if (exception == null)
throw new IllegalStateException("could not get exception for result");
return exception.getContent(handle);
}
}
public class DeleteOutput extends OutputItem {
DeleteOutput() {
super();
}
@Override
public OperationType getOperationType() {
return OperationType.DELETE;
}
}
public class ReadOutput extends OutputItem {
String metadataMimetype;
ServiceResult metadata;
String contentMimetype;
ServiceResult content;
ReadOutput() {
super();
}
@Override
public OperationType getOperationType() {
return OperationType.READ;
}
public boolean hasMetadata() {
return (metadata != null);
}
public DocumentMetadataHandle getMetadata() {
if (metadata == null)
throw new IllegalStateException("could not get metadata for result");
return metadata.getContent(new DocumentMetadataHandle());
}
public <R extends XMLReadHandle> R getMetadata(R handle) {
if (metadata == null)
throw new IllegalStateException("could not get metadata for result");
return metadata.getContent(handle);
}
public boolean hasContent() {
return (content != null);
}
public String getContentMimetype() {
return contentMimetype;
}
public <R extends AbstractReadHandle> R getContent(R handle) {
if (content == null)
throw new IllegalStateException("could not get content for result");
return content.getContent(handle);
}
}
public class WriteOutput extends OutputItem {
WriteOutput() {
super();
}
@Override
public OperationType getOperationType() {
return OperationType.WRITE;
}
}
static final public String NAME = "docbatch";
public BatchManager(DatabaseClient client) {
super();
client.init(NAME, this);
}
public BatchRequest newBatchRequest() {
return new BatchRequest();
}
public BatchResponse apply(BatchRequest request) {
if (request == null)
return null;
StringHandle requestManifest = new StringHandle();
List<AbstractWriteHandle> requestHandles = new ArrayList<>();
requestHandles.add(requestManifest);
StringBuilder manifestBuilder = new StringBuilder();
manifestBuilder.append("<?xml version='1.0' encoding='UTF-8'?>\n");
manifestBuilder.append("<rapi:batch-requests xmlns:rapi='http://marklogic.com/rest-api'>\n");
for (Map.Entry<String,InputItem> entry: request.items.entrySet()) {
String uri = entry.getKey();
InputItem item = entry.getValue();
if (item instanceof DeleteInput) {
manifestBuilder.append("<rapi:delete-request>\n");
manifestBuilder.append("<rapi:uri>");
manifestBuilder.append(uri);
manifestBuilder.append("</rapi:uri>\n");
manifestBuilder.append("</rapi:delete-request>\n");
} else if (item instanceof ReadInput) {
ReadInput ritem = (ReadInput) item;
manifestBuilder.append("<rapi:get-request>\n");
manifestBuilder.append("<rapi:uri>");
manifestBuilder.append(uri);
manifestBuilder.append("</rapi:uri>\n");
if (ritem.categories != null && ritem.categories.size() > 0) {
StringBuilder categoryBuilder = new StringBuilder();
categoryBuilder.append("<rapi:metadata>\n");
for (DocumentManager.Metadata category: ritem.categories) {
categoryBuilder.append("<rapi:");
categoryBuilder.append(category.name().toLowerCase());
categoryBuilder.append("/>\n");
}
categoryBuilder.append("</rapi:metadata>\n");
manifestBuilder.append(categoryBuilder.toString());
}
if (ritem.mimetype != null) {
manifestBuilder.append("<rapi:content-mimetype>");
manifestBuilder.append(ritem.mimetype);
manifestBuilder.append("</rapi:content-mimetype>\n");
}
manifestBuilder.append("</rapi:get-request>\n");
} else if (item instanceof WriteInput) {
WriteInput witem = (WriteInput) item;
manifestBuilder.append("<rapi:put-request>\n");
manifestBuilder.append("<rapi:uri>");
manifestBuilder.append(uri);
manifestBuilder.append("</rapi:uri>\n");
if (witem.content != null) {
manifestBuilder.append("<rapi:content-mimetype>");
manifestBuilder.append(witem.getContentMimetype());
manifestBuilder.append("</rapi:content-mimetype>\n");
requestHandles.add(witem.content);
}
manifestBuilder.append("</rapi:put-request>\n");
}
}
manifestBuilder.append("</rapi:batch-requests>\n");
requestManifest.set(manifestBuilder.toString());
requestManifest.setFormat(Format.XML);
ServiceResultIterator resultItr = getServices().post(
new RequestParameters(),
requestHandles.toArray(new AbstractWriteHandle[requestHandles.size()])
);
if (!resultItr.hasNext())
throw new FailedRequestException("Could not executed batch request");
DOMHandle responseManifest = resultItr.next().getContent(new DOMHandle());
List<OutputItem> items = new ArrayList<>();
boolean requestSuccess = true;
NodeList responseItems = responseManifest.get().getDocumentElement().getChildNodes();
int responseCount = responseItems.getLength();
for (int i=0; i < responseCount; i++) {
Node responseNode = responseItems.item(i);
if (responseNode.getNodeType() != Node.ELEMENT_NODE)
continue;
Element responseItem = (Element) responseNode;
String itemUri = null;
boolean itemSuccess = false;
String itemMetadata = null;
String itemContent = null;
String itemException = null;
NodeList fieldItems = responseItem.getChildNodes();
int fieldCount = fieldItems.getLength();
for (int j=0; j < fieldCount; j++) {
Node fieldNode = fieldItems.item(j);
if (fieldNode.getNodeType() != Node.ELEMENT_NODE)
continue;
Element fieldItem = (Element) fieldNode;
String fieldName = fieldItem.getLocalName();
if ("uri".equals(fieldName)) {
itemUri = fieldItem.getTextContent();
} else if ("request-succeeded".equals(fieldName)) {
itemSuccess = "true".equals(fieldItem.getTextContent());
} else if ("metadata-mimetype".equals(fieldName)) {
itemMetadata = fieldItem.getTextContent();
} else if ("content-mimetype".equals(fieldName)) {
itemContent = fieldItem.getTextContent();
} else if ("request-failure".equals(fieldName)) {
itemException = fieldItem.getTextContent();
} else {
// TODO: warn
}
}
if (requestSuccess && !itemSuccess)
requestSuccess = false;
String responseName = responseItem.getLocalName();
if ("delete-response".equals(responseName)) {
DeleteOutput deleteOutput = new DeleteOutput();
deleteOutput.uri = itemUri;
deleteOutput.success = itemSuccess;
if (itemException != null) {
deleteOutput.exceptionMimetype = itemException;
}
items.add(deleteOutput);
} else if ("get-response".equals(responseName)) {
ReadOutput readOutput = new ReadOutput();
readOutput.uri = itemUri;
readOutput.success = itemSuccess;
if (itemException != null) {
readOutput.exceptionMimetype = itemException;
} else {
if (itemMetadata != null) {
readOutput.metadataMimetype = itemMetadata;
}
if (itemContent != null) {
// TODO: set format
readOutput.contentMimetype = itemContent;
}
}
items.add(readOutput);
} else if ("put-response".equals(responseName)) {
WriteOutput writeOutput = new WriteOutput();
writeOutput.uri = itemUri;
writeOutput.success = itemSuccess;
if (itemException != null) {
writeOutput.exceptionMimetype = itemException;
}
items.add(writeOutput);
}
}
BatchResponse response = new BatchResponse();
response.success = requestSuccess;
response.items = new ConcurrentLinkedQueue<OutputItem>(items).iterator();
response.results = resultItr;
return response;
}
}