Ptidej-v5.2-master/Ptidej Reporting Tests/src/net/sf/jasperreports/engine/data/JRJpaDataSource.java
/*
 * ============================================================================
 * GNU Lesser General Public License
 * ============================================================================
 *
 * JasperReports - Free Java report-generating library.
 * Copyright (C) 2001-2005 JasperSoft Corporation http://www.jaspersoft.com
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 * 
 * JasperSoft Corporation
 * 303 Second Street, Suite 450 North
 * San Francisco, CA 94107
 * http://www.jaspersoft.com
 */
package net.sf.jasperreports.engine.data;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JRRewindableDataSource;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.query.JRJpaQueryExecuter;

/**
 * Java Persistence API data source that uses <code>javax.persistence.Query.getResultList()</code>.
 * <p/>
 * The query result can be paginated by not retrieving all the rows at once.
 * <p/>
 * Fields are mapped to values in the result following these rules:
 * <ul>
 * <li>if the query returns a single object/bean (e.g. <code>SELECT m FROM Movie m</code> or
 * <code>SELECT NEW MovieDescription(m.title, m.genre) FROM Movie m</code>), then the fields are
 * mapped to bean property names.</li>
 * <li>if the query returns multiple objects per row (e.g. <code>SELECT m.title, m.gender FROM Movie m</code>),
 * the fields are mapped using the following syntax: COLUMN_<em>index</em>[.<em>property</em>], with the
 * indexes starting from 1.  Example mappings: COLUMN_1, COLUMN_2, COLUMN_2.title, COLUMN_2.movie.title.</li>
 * </ul>
 * 
 * @author Marcel Overdijk (marceloverdijk@hotmail.com)
 * @version $Id: JRJpaDataSource.java,v 1.1 2008/09/29 16:22:08 guehene Exp $
 * @see net.sf.jasperreports.engine.query.JRJpaQueryExecuterFactory#PROPERTY_JPA_QUERY_PAGE_SIZE
 */
public class JRJpaDataSource extends JRAbstractBeanDataSource implements JRRewindableDataSource {
	private static final String MAPPING_INDEX_PREFIX = "COLUMN_";
	private static final int MAPPING_INDEX_PREFIX_LENGTH = MAPPING_INDEX_PREFIX.length();
	private static final String MAPPING_INDEX_PROPERTY_SEP = ".";
	private static final int MAPPING_INDEX_PROPERTY_SEP_LENGTH = MAPPING_INDEX_PROPERTY_SEP.length();
	
	private final JRJpaQueryExecuter queryExecuter;
	private final int pageSize;
	private int pageCount;
	private boolean nextPage;
	private List returnValues;
	private Iterator iterator;
	protected Object currentRow;
	private Map fieldValueReaders;

	public JRJpaDataSource(JRJpaQueryExecuter queryExecuter, int pageSize) {
		super(true);

		this.queryExecuter = queryExecuter;
		this.pageSize = pageSize;
		
		this.fieldValueReaders = new HashMap();
		
		this.pageCount = 0;
		fetchPage();
	}

	protected void fetchPage() {
		if (this.pageSize <= 0) {
			this.returnValues = this.queryExecuter.getResultList();
			this.nextPage = false;
		}
		else {
			this.returnValues = this.queryExecuter.getResultList(this.pageCount * this.pageSize, this.pageSize);
			this.nextPage = this.returnValues.size() == this.pageSize;
		}

		++this.pageCount;

		initIterator();
	}

	public boolean next() {
		if (this.iterator == null) {
			return false;
		}
		
		boolean hasNext = this.iterator.hasNext();
		if (!hasNext && this.nextPage) {
			fetchPage();
			hasNext = this.iterator != null && this.iterator.hasNext();
		}
		
		if (hasNext) {
			this.currentRow = this.iterator.next();
		}

		return hasNext;
	}

	public void moveFirst() {
		if (this.pageCount == 1) {
			initIterator();
		}
		else {
			this.pageCount = 0;
			fetchPage();
		}
	}

	private void initIterator() {
		this.iterator = this.returnValues == null ? null : this.returnValues.iterator();
	}
	
	public Object getFieldValue(JRField field) throws JRException {
		FieldValueReader reader = getFieldValueReader(field);
		return reader.getValue();
	}
	
	protected FieldValueReader getFieldValueReader(JRField field)
	{
		FieldValueReader reader = (FieldValueReader) this.fieldValueReaders.get(field.getName());
		if (reader == null)
		{
			String mapping = getPropertyName(field);
			reader = createReader(mapping);
			this.fieldValueReaders.put(field.getName(), reader);
		}
		return reader;
	}

	private FieldValueReader createReader(String mapping)
	{
		FieldValueReader reader = null;
		if (mapping.startsWith(MAPPING_INDEX_PREFIX))
		{
			int propertySepIdx = mapping.indexOf(MAPPING_INDEX_PROPERTY_SEP, MAPPING_INDEX_PREFIX_LENGTH + 1);
			if (propertySepIdx < 0)
			{
				String indexStr = mapping.substring(MAPPING_INDEX_PREFIX_LENGTH);
				try
				{
					int index = Integer.parseInt(indexStr);
					reader = new IndexReader(index - 1);
				}
				catch (NumberFormatException e)
				{
					//ignore
				}
			}
			else
			{
				String indexStr = mapping.substring(MAPPING_INDEX_PREFIX_LENGTH, propertySepIdx);
				try
				{
					int index = Integer.parseInt(indexStr);
					String property = mapping.substring(propertySepIdx + MAPPING_INDEX_PROPERTY_SEP_LENGTH);
					reader = new IndexPropertyReader(index - 1, property);
				}
				catch (NumberFormatException e)
				{
					//ignore
				}
			}
		}

		//default to a property mapping
		if (reader == null)
		{
			reader = new PropertyReader(mapping);
		}
		
		return reader;
	}

	protected static interface FieldValueReader
	{
		Object getValue() throws JRException;
	}
	
	protected class PropertyReader implements FieldValueReader
	{
		private final String property;
		
		public PropertyReader(String property)
		{
			this.property = property;
		}
		
		public Object getValue() throws JRException
		{
			return getBeanProperty(JRJpaDataSource.this.currentRow, this.property);
		}	
	}
	
	protected class IndexReader implements FieldValueReader
	{
		private final int position;
		
		public IndexReader(int position)
		{
			this.position = position;
		}
		
		public Object getValue() throws JRException
		{
			Object[] values = (Object[]) JRJpaDataSource.this.currentRow;
			if (this.position < 0 || this.position >= values.length)
			{
				throw new JRRuntimeException("Index " + this.position + " out of bounds for query result of length " + values.length);
			}
			return values[this.position];
		}	
	}
	
	protected class IndexPropertyReader implements FieldValueReader
	{
		private final int position;
		private final String property;
		
		public IndexPropertyReader(int position, String property)
		{
			this.position = position;
			this.property = property;
		}
		
		public Object getValue() throws JRException
		{
			Object[] values = (Object[]) JRJpaDataSource.this.currentRow;
			if (this.position < 0 || this.position >= values.length)
			{
				throw new JRRuntimeException("Index " + this.position + " out of bounds for query result of length " + values.length);
			}
			return getBeanProperty(values[this.position], this.property);
		}
	}
}
