Ptidej-v5.2-master/Ptidej Reporting Tests/src/net/sf/jasperreports/engine/query/JRHibernateQueryExecuter.java
/*
 * ============================================================================
 * GNU Lesser General Public License
 * ============================================================================
 *
 * JasperReports - Free Java report-generating library.
 * Copyright (C) 2001-2006 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.query;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRDataset;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JRValueParameter;
import net.sf.jasperreports.engine.data.JRHibernateIterateDataSource;
import net.sf.jasperreports.engine.data.JRHibernateListDataSource;
import net.sf.jasperreports.engine.data.JRHibernateScrollDataSource;
import net.sf.jasperreports.engine.util.JRProperties;
import net.sf.jasperreports.engine.util.JRStringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.type.Type;

/**
 * HQL query executer that uses Hibernate 3.
 * 
 * @author Lucian Chirita (lucianc@users.sourceforge.net)
 * @version $Id: JRHibernateQueryExecuter.java,v 1.1 2008/09/29 16:20:33 guehene Exp $
 */
public class JRHibernateQueryExecuter extends JRAbstractQueryExecuter
{
	private static final Log log = LogFactory.getLog(JRHibernateQueryExecuter.class);
	
	private static final Map hibernateTypeMap;
	
	static
	{
		hibernateTypeMap = new HashMap();
		hibernateTypeMap.put(Boolean.class, Hibernate.BOOLEAN);
		hibernateTypeMap.put(Byte.class, Hibernate.BYTE);
		hibernateTypeMap.put(Double.class, Hibernate.DOUBLE);
		hibernateTypeMap.put(Float.class, Hibernate.FLOAT);
		hibernateTypeMap.put(Integer.class, Hibernate.INTEGER);
		hibernateTypeMap.put(Long.class, Hibernate.LONG);
		hibernateTypeMap.put(Short.class, Hibernate.SHORT);
		hibernateTypeMap.put(java.math.BigDecimal.class, Hibernate.BIG_DECIMAL);
		hibernateTypeMap.put(java.math.BigInteger.class, Hibernate.BIG_INTEGER);
		hibernateTypeMap.put(Character.class, Hibernate.CHARACTER);
		hibernateTypeMap.put(String.class, Hibernate.STRING);
		hibernateTypeMap.put(java.util.Date.class, Hibernate.DATE);
		hibernateTypeMap.put(java.sql.Timestamp.class, Hibernate.TIMESTAMP);
		hibernateTypeMap.put(java.sql.Time.class, Hibernate.TIME);
	}

	private final Integer reportMaxCount;
	
	private Session session;
	private Query query;
	private boolean queryRunning;
	private ScrollableResults scrollableResults;
	private boolean isClearCache;

	
	public JRHibernateQueryExecuter(JRDataset dataset, Map parameters)
	{
		super(dataset, parameters);
		
		this.session = (Session) getParameterValue(JRHibernateQueryExecuterFactory.PARAMETER_HIBERNATE_SESSION);
		this.reportMaxCount = (Integer) getParameterValue(JRParameter.REPORT_MAX_COUNT);
		this.isClearCache = JRProperties.getBooleanProperty(dataset, 
				JRHibernateQueryExecuterFactory.PROPERTY_HIBERNATE_CLEAR_CACHE,
				false);

		if (this.session == null)
		{
			log.warn("The supplied org.hibernate.Session object is null.");
		}
		
		parseQuery();
	}
	
	
	/**
	 * Creates an instance of {@link JRHibernateListDataSource JRHibernateListDataSource},
	 * {@link JRHibernateIterateDataSource JRHibernateIterateDataSource} or
	 * {@link JRHibernateScrollDataSource JRHibernateScrollDataSource}, depending on the 
	 */
	public JRDataSource createDatasource() throws JRException
	{
		JRDataSource datasource = null;
		String queryString = getQueryString();
		
		if (this.session != null && queryString != null && queryString.trim().length() > 0)
		{
			createQuery(queryString);

			datasource = createResultDatasource();
		}

		return datasource;
	}

	/**
	 * Creates a data source out of the query result.
	 * 
	 * @return the data source
	 */
	protected JRDataSource createResultDatasource()
	{
		JRDataSource resDatasource;
		
		String runType = JRProperties.getProperty(this.dataset, 
				JRHibernateQueryExecuterFactory.PROPERTY_HIBERNATE_QUERY_RUN_TYPE);
		boolean useFieldDescriptions = JRProperties.getBooleanProperty(this.dataset, 
				JRHibernateQueryExecuterFactory.PROPERTY_HIBERNATE_FIELD_MAPPING_DESCRIPTIONS,
				true);
		
		if (runType == null || runType.equals(JRHibernateQueryExecuterFactory.VALUE_HIBERNATE_QUERY_RUN_TYPE_LIST))
		{
			try
			{
				int pageSize = JRProperties.getIntegerProperty(this.dataset, 
						JRHibernateQueryExecuterFactory.PROPERTY_HIBERNATE_QUERY_LIST_PAGE_SIZE,
						0);

				resDatasource = new JRHibernateListDataSource(this, useFieldDescriptions, pageSize);
			}
			catch (NumberFormatException e)
			{
				throw new JRRuntimeException("The " + JRHibernateQueryExecuterFactory.PROPERTY_HIBERNATE_QUERY_LIST_PAGE_SIZE +
						" property must be numerical.");
			}
		}
		else if (runType.equals(JRHibernateQueryExecuterFactory.VALUE_HIBERNATE_QUERY_RUN_TYPE_ITERATE))
		{
			resDatasource = new JRHibernateIterateDataSource(this, useFieldDescriptions);
		}
		else if (runType.equals(JRHibernateQueryExecuterFactory.VALUE_HIBERNATE_QUERY_RUN_TYPE_SCROLL))
		{
			resDatasource = new JRHibernateScrollDataSource(this, useFieldDescriptions);
		}
		else
		{
			throw new JRRuntimeException("Unknown value for the " + JRHibernateQueryExecuterFactory.PROPERTY_HIBERNATE_QUERY_RUN_TYPE +
					" property.  Possible values are " + JRHibernateQueryExecuterFactory.VALUE_HIBERNATE_QUERY_RUN_TYPE_LIST + ", " +
					JRHibernateQueryExecuterFactory.VALUE_HIBERNATE_QUERY_RUN_TYPE_ITERATE + " and " +
					JRHibernateQueryExecuterFactory.VALUE_HIBERNATE_QUERY_RUN_TYPE_SCROLL + ".");
		}
		
		return resDatasource;
	}

	
	/**
	 * Creates the Hibernate query object.
	 * <p/>
	 * If the value of the {@link JRHibernateQueryExecuterFactory#PARAMETER_HIBERNATE_FILTER_COLLECTION PARAMETER_HIBERNATE_FILTER_COLLECTION}
	 * is not null, then a filter query is created using the value of the paramter as the collection.
	 * 
	 * @param queryString the query string
	 */
	protected synchronized void createQuery(String queryString)
	{
		if (log.isDebugEnabled())
		{
			log.debug("HQL query: " + queryString);
		}
		
		Object filterCollection = getParameterValue(JRHibernateQueryExecuterFactory.PARAMETER_HIBERNATE_FILTER_COLLECTION);
		if (filterCollection == null)
		{
			this.query = this.session.createQuery(queryString);
		}
		else
		{
			this.query = this.session.createFilter(filterCollection, queryString);
		}
		this.query.setReadOnly(true);
		
		int fetchSize = JRProperties.getIntegerProperty(this.dataset,
				JRJdbcQueryExecuterFactory.PROPERTY_JDBC_FETCH_SIZE,
				0);
		if (fetchSize != 0)
		{
			this.query.setFetchSize(fetchSize);
		}
		
		setParameters();
	}

	/**
	 * Binds values for all the query paramters.
	 */
	protected void setParameters()
	{
		List parameterNames = getCollectedParameterNames();
		
		if (!parameterNames.isEmpty())
		{
			Set namesSet = new HashSet();
			
			for (Iterator iter = parameterNames.iterator(); iter.hasNext();)
			{
				String parameterName = (String) iter.next();
				if (namesSet.add(parameterName))
				{
					JRValueParameter parameter = getValueParameter(parameterName);
					setParameter(parameter);
				}
			}
		}
	}
	
	
	/**
	 * Binds a paramter value to a query paramter.
	 * 
	 * @param parameter the report parameter
	 */
	protected void setParameter(JRValueParameter parameter)
	{
		String hqlParamName = getHqlParameterName(parameter.getName());
		Class clazz = parameter.getValueClass();
		Object parameterValue = parameter.getValue();
		
		if (log.isDebugEnabled())
		{
			log.debug("Parameter " + hqlParamName + " of type " + clazz.getName() + ": " + parameterValue);
		}
		
		Type type = (Type) hibernateTypeMap.get(clazz);
		
		if (type != null)
		{
			this.query.setParameter(hqlParamName, parameterValue, type);
		}
		else if (Collection.class.isAssignableFrom(clazz))
		{
			this.query.setParameterList(hqlParamName, (Collection) parameterValue);
		}
		else
		{
			if (this.session.getSessionFactory().getClassMetadata(clazz) != null) //param type is a hibernate mapped entity
			{
				this.query.setEntity(hqlParamName, parameterValue);
			}
			else //let hibernate try to guess the type
			{
				this.query.setParameter(hqlParamName, parameterValue);
			}
		}
	}

	
	/**
	 * Closes the scrollable result when <em>scroll</em> execution type is used.
	 */
	public synchronized void close()
	{
		closeScrollableResults();

		this.query = null;
	}


	/**
	 * Closes the scrollable results of the query.
	 */
	public void closeScrollableResults()
	{
		if (this.scrollableResults != null)
		{
			try
			{
				this.scrollableResults.close();
			}
			finally
			{
				this.scrollableResults = null;
			}
		}
	}

	
	public synchronized boolean cancelQuery() throws JRException
	{
		if (this.queryRunning)
		{
			this.session.cancelQuery();
			return true;
		}
		
		return false;
	}

	protected String getParameterReplacement(String parameterName)
	{
		return ':' + getHqlParameterName(parameterName);
	}

	protected String getHqlParameterName(String parameterName)
	{
		return '_' + JRStringUtil.getLiteral(parameterName);
	}
	
	
	/**
	 * Returns the return types of the HQL query.
	 * 
	 * @return the return types of the HQL query
	 */
	public Type[] getReturnTypes()
	{
		return this.query.getReturnTypes();
	}
	
	
	/**
	 * Returns the aliases of the HQL query.
	 * 
	 * @return the aliases of the HQL query
	 */
	public String[] getReturnAliases()
	{
		return this.query.getReturnAliases();
	}
	
	
	/**
	 * Returns the dataset for which the query executer has been created.
	 * 
	 * @return the dataset for which the query executer has been created
	 */
	public JRDataset getDataset()
	{
		return this.dataset;
	}
	
	
	/**
	 * Runs the query by calling <code>org.hibernate.Query.list()</code>.
	 * <p/>
	 * All the result rows are returned.
	 * 
	 * @return the result of the query as a list
	 */
	public List list()
	{
		setMaxCount();
		
		setQueryRunning(true);
		try
		{
			return this.query.list();
		}
		finally
		{
			setQueryRunning(false);
		}
	}

	protected synchronized void setQueryRunning(boolean queryRunning)
	{
		this.queryRunning = queryRunning;
	}

	
	private void setMaxCount()
	{
		if (this.reportMaxCount != null)
		{
			this.query.setMaxResults(this.reportMaxCount.intValue());
		}
	}
	
	
	/**
	 * Returns a page of the query results by calling <code>org.hibernate.Query.iterate()</code>.
	 * 
	 * @param firstIndex the index of the first row to return
	 * @param resultCount the number of rows to return
	 * @return result row list
	 */
	public List list(int firstIndex, int resultCount)
	{
		if (this.reportMaxCount != null && firstIndex + resultCount > this.reportMaxCount.intValue())
		{
			resultCount = this.reportMaxCount.intValue() - firstIndex;
		}
		
		this.query.setFirstResult(firstIndex);
		this.query.setMaxResults(resultCount);
		if (this.isClearCache)
			clearCache();
		
		return this.query.list();
	}
	
	
	/**
	 * Runs the query by calling <code>org.hibernate.Query.iterate()</code>.
	 * 
	 * @return query iterator
	 */
	public Iterator iterate()
	{
		setMaxCount();
		
		setQueryRunning(true);
		try
		{
			return this.query.iterate();
		}
		finally
		{
			setQueryRunning(false);
		}
	}
	
	
	/**
	 * Runs the query by calling <code>org.hibernate.Query.scroll()</code>.
	 * 
	 * @return scrollable results of the query
	 */
	public ScrollableResults scroll()
	{
		setMaxCount();
		
		setQueryRunning(true);
		try
		{
			this.scrollableResults = this.query.scroll(ScrollMode.FORWARD_ONLY);
		}
		finally
		{
			setQueryRunning(false);
		}
		
		return this.scrollableResults;
	}
	
	public void clearCache()
	{
		this.session.flush();
		this.session.clear();
	}
}
