1 /* 2 * #%L 3 * IteratorToListCallbackAdapter.java - mongodb-async-driver - Allanbank Consulting, Inc. 4 * %% 5 * Copyright (C) 2011 - 2014 Allanbank Consulting, Inc. 6 * %% 7 * Licensed under the Apache License, Version 2.0 (the "License"); 8 * you may not use this file except in compliance with the License. 9 * You may obtain a copy of the License at 10 * 11 * http://www.apache.org/licenses/LICENSE-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, software 14 * distributed under the License is distributed on an "AS IS" BASIS, 15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 * See the License for the specific language governing permissions and 17 * limitations under the License. 18 * #L% 19 */ 20 21 package com.allanbank.mongodb.client.callback; 22 23 import java.util.ArrayList; 24 import java.util.List; 25 26 import com.allanbank.mongodb.Callback; 27 import com.allanbank.mongodb.MongoIterator; 28 import com.allanbank.mongodb.bson.Document; 29 import com.allanbank.mongodb.util.IOUtils; 30 31 /** 32 * IteratorToListCallbackAdapter provides the ability to translate a 33 * MongoIterator callback into a list callback. 34 * 35 * @copyright 2013, Allanbank Consulting, Inc., All Rights Reserved 36 */ 37 public class IteratorToListCallbackAdapter implements 38 Callback<MongoIterator<Document>> { 39 40 /** The list callback to invoke once all of the documents are collected. */ 41 private final Callback<List<Document>> myDelegate; 42 43 /** 44 * Creates a new IteratorToListCallbackAdapter. 45 * 46 * @param delegate 47 * The list callback to invoke once all of the documents are 48 * collected. 49 */ 50 public IteratorToListCallbackAdapter(final Callback<List<Document>> delegate) { 51 myDelegate = delegate; 52 } 53 54 /** 55 * {@inheritDoc} 56 * <p> 57 * Overridden to collect all of the results and then call the delegate. 58 * </p> 59 */ 60 @Override 61 public void callback(final MongoIterator<Document> result) { 62 final List<Document> docs = new ArrayList<Document>(); 63 try { 64 while (result.hasNext()) { 65 docs.add(result.next()); 66 } 67 } 68 finally { 69 IOUtils.close(result); 70 myDelegate.callback(docs); 71 } 72 } 73 74 /** 75 * {@inheritDoc} 76 * <p> 77 * Overridden to forward to the delegate. 78 * </p> 79 */ 80 @Override 81 public void exception(final Throwable thrown) { 82 myDelegate.exception(thrown); 83 } 84 }