/*
* Copyright 2011 Objectos, Fábrica de Software LTDA.
*
* 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 br.com.objectos.comuns.relational;
import java.util.Iterator;
import java.util.List;
import br.com.objectos.comuns.relational.search.SimplePage;
import com.google.inject.Inject;
/**
* @author marcio.endo@objectos.com.br (Marcio Endo)
*/
public class EntityIteratorGenGuice implements EntityIteratorGen {
private final QueryExec exec;
@Inject
EntityIteratorGenGuice(QueryExec exec) {
this.exec = exec;
}
@Override
public <E> Iterator<E> iteratorFor(Class<?> entityClass) {
return new Iterador<E>(entityClass, exec);
}
private static class Iterador<E> implements Iterator<E> {
private final Class<?> entityClass;
private final QueryExec exec;
private final int maxResults = 50;
private int page = 0;
private Iterator<E> iterator;
public Iterador(Class<?> entityClass, QueryExec exec) {
this.entityClass = entityClass;
this.exec = exec;
}
@Override
public boolean hasNext() {
if (iterator == null || !iterator.hasNext()) {
updateIterator();
}
return iterator.hasNext();
}
@Override
public E next() {
return iterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private void updateIterator() {
List<E> itens = getNextPage();
iterator = itens.iterator();
}
private List<E> getNextPage() {
int firstResult = firstResult();
SimplePage paginator = SimplePage.build() //
.startAt(firstResult) //
.withLengthOf(maxResults) //
.get();
page++;
return exec.listPage(entityClass, paginator);
}
private int firstResult() {
return page * maxResults;
}
}
}