All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mongodb.OperationIterable Maven / Gradle / Ivy

Go to download

The MongoDB Java Driver uber-artifact, containing mongodb-driver, mongodb-driver-core, and bson

The newest version!
/*
 * Copyright (c) 2008-2014 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mongodb;

import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoIterable;
import com.mongodb.operation.BatchCursor;
import com.mongodb.operation.OperationExecutor;
import com.mongodb.operation.ReadOperation;

import java.util.Collection;

/**
 * MongoIterable implementation that aids iteration over the results of results of an inline map-reduce operation.
 *
 * @param  the return type of the map reduce
 * @since 3.0
 */
class OperationIterable implements MongoIterable {
    private final ReadOperation> operation;
    private final ReadPreference readPreference;
    private final OperationExecutor executor;

    OperationIterable(final ReadOperation> operation, final ReadPreference readPreference,
                      final OperationExecutor executor) {
        this.operation = operation;
        this.readPreference = readPreference;
        this.executor = executor;
    }

    @Override
    public MongoCursor iterator() {
        return new MongoBatchCursorAdapter(executor.execute(operation, readPreference));
    }

    @Override
    public T first() {
        MongoCursor cursor = iterator();
        try {
            if (!cursor.hasNext())  {
                return null;
            }
            return cursor.next();
        } finally {
            cursor.close();
        }
    }

    @Override
    public  MongoIterable map(final Function mapper) {
        return new MappingIterable(this, mapper);
    }

    @Override
    public void forEach(final Block block) {
        MongoCursor cursor = iterator();
        try {
            while (cursor.hasNext()) {
                block.apply(cursor.next());
            }
        } finally {
            cursor.close();
        }
    }

    @Override
    public > A into(final A target) {
        forEach(new Block() {
            @Override
            public void apply(final T t) {
                target.add(t);
            }
        });
        return target;
    }

    @Override
    public MongoIterable batchSize(final int batchSize) {
        throw new UnsupportedOperationException();
    }

}