Thursday, June 7, 2012

Mongodb Paging Item Reader


Here, is a sample..

package org.zero.index.batch.read;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.database.AbstractPagingItemReader;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.util.Assert;

public class MongodbPagingItemReader<T> extends AbstractPagingItemReader<T> {
  private MongoOperations mongoOperations;
  private QueryContext<T> queryContext;
  private boolean strict;

  private static final Logger LOG = LoggerFactory
      .getLogger(MongodbPagingItemReader.class);

  @Override
  protected void doReadPage() {
    if (results == null) {
      results = new CopyOnWriteArrayList<T>();
    } else {
      results.clear();
    }
    final List<T> result = mongoOperations.find(
        queryContext.getQuery().limit(getPageSize()).skip(getPage()),
        queryContext.getEntityClassName(), queryContext.getCollectionName());
    if ((getPage() == 0) && result.isEmpty()) {
      if (strict) {
        throw new IllegalStateException(
            "No matching documents found (reader is in 'strict' mode)");
      }
      LOG.warn("No matching documents found");
      return;
    }
    results.addAll(result);
  }

  @Override
  protected void doJumpToPage(final int itemIndex) {
    // do nothing
  }

  /**
   * @param mongoOperations
   *          the mongoOperations to set
   */
  public void setMongoOperations(final MongoOperations mongoOperations) {
    this.mongoOperations = mongoOperations;
  }

  /**
   * @param queryContext
   *          the queryContext to set
   */
  public void setQueryContext(final QueryContext<T> queryContext) {
    this.queryContext = queryContext;
  }

  /**
   * @param strict
   */
  public void setStrict(final boolean strict) {
    this.strict = strict;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    super.afterPropertiesSet();
    Assert.notNull(mongoOperations, "mongoOperations is null");
    Assert.notNull(queryContext, "queryContext is null");
  }
}

No comments: