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

com.mtvnet.boxspring.external.hibernate.HibernateBeanSource Maven / Gradle / Ivy

The newest version!
/**
 * Copyright (c) 2009, MTV Networks. All rights reserved.
 *
 * This program is licensed to you under the Apache License Version 2.0,
 * and you may not use this file except in compliance with the Apache License Version 2.0.
 * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Apache License Version 2.0 is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
 */
/**
 * 
 */
package com.mtvnet.boxspring.external.hibernate;

import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.NotReadablePropertyException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.mtvnet.boxspring.external.ExternalBeanSource;

/**
 * @author edelsonj
 * 
 */
public class HibernateBeanSource extends HibernateDaoSupport implements ExternalBeanSource {

    private Class beanClass;

    private String beanNameProperty;

    public boolean containsBean(final String name) {
        Number count = (Number) getHibernateTemplate().execute(new HibernateCallback() {

            public Number doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(String.format(
                        "select count(%s) from %s where %s = ?", beanNameProperty, beanClass
                                .getName(), beanNameProperty));
                q.setString(0, name);
                return (Number) q.uniqueResult();
            }
        });
        return (count.intValue() > 0);
    }

    public  T getBean(String name, Class type) {
        type = useDefaultType(type);
        List beans = getHibernateTemplate()
                .find(
                        String.format("from %s beans where beans.%s = ?", type.getName(),
                                beanNameProperty), name);
        if (beans.size() == 0) {
            throw new NoSuchBeanDefinitionException(name, String.format(
                    "Looked in class %s using name property %s", beanClass.getName(),
                    beanNameProperty));
        } else {
            return beans.get(0);
        }
    }

    @SuppressWarnings("unchecked")
    public int getBeanCount(Class type) {
        type = useDefaultType(type);

        List count = getHibernateTemplate().find(
                String.format("select count(%s) from %s", beanNameProperty, type.getName()));
        return count.get(0).intValue();
    }

    @SuppressWarnings("unchecked")
    public List getBeanNames(Class type) {
        type = useDefaultType(type);

        if (isMappedClass(type)) {
            List names = getHibernateTemplate().find(
                    String.format("select %s from %s", beanNameProperty, type.getName()));
            return names;
        } else {
            return Collections.emptyList();
        }
    }

    @SuppressWarnings("unchecked")
    public Map getBeansOfType(Class type) {
        type = useDefaultType(type);

        if (isMappedClass(type)) {
            List beans = getHibernateTemplate().find(
                    String.format("from %s", type.getName()));
            Map retval = new HashMap(beans.size());
            for (Object o : beans) {
                try {
                    retval.put(PropertyUtils.getProperty(o, beanNameProperty).toString(), o);
                } catch (Exception e) {
                    throw new NotReadablePropertyException(o.getClass(), beanNameProperty);
                }
            }
            return retval;
        } else {
            return Collections.emptyMap();
        }
    }

    @Required
    public void setBeanClass(Class beanClass) {
        this.beanClass = beanClass;
    }

    @Required
    public void setBeanNameProperty(String beanNameProperty) {
        this.beanNameProperty = beanNameProperty;
    }

    private boolean isMappedClass(Class type) {
        return getSessionFactory().getClassMetadata(type) != null;
    }

    private Class useDefaultType(Class type) {
        if (type == null) {
            type = beanClass;
        }
        return type;
    }

    public  T getBean(Class requiredType) {
        throw new UnsupportedOperationException(
                "HibernateBeanSource doesn't support getBean(Class)");
    }

}