com.formkiq.core.dao.AbstractDaoImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.formkiq.core.dao.AbstractDaoImpl.java

Source

/*
 * Copyright (C) 2016 FormKiQ Inc.
 *
 * 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 com.formkiq.core.dao;

import java.lang.reflect.InvocationTargetException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.hibernate.Hibernate;
import org.hibernate.Session;

import com.formkiq.core.domain.type.PaginationDTO;
import com.formkiq.core.form.bean.ObjectBuilder;
import com.formkiq.core.util.Strings;

/**
 * AbstractDao.
 *
 */
public abstract class AbstractDaoImpl implements AbstractDao {

    /** Default MAX Results. */
    protected static final int DEFAULT_MAX_RESULTS = 10;

    /** EntityManager. */
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * default contructor.
     */
    public AbstractDaoImpl() {
    }

    @SuppressWarnings("resource")
    @Override
    public Blob convertToBlob(final byte[] data) {
        Session session = getEntityManager().unwrap(Session.class);
        Blob blob = Hibernate.getLobCreator(session).createBlob(data);
        return blob;
    }

    /**
    * @return EntityManager
    */
    public EntityManager getEntityManager() {
        return this.entityManager;
    }

    /**
    * Return a single result, catch NoResultException and return NULL.
    * @param query Query
    * @return Object
    */
    protected Object getSingleResult(final Query query) {

        Object t;

        try {

            t = query.getSingleResult();

        } catch (NoResultException e) {
            t = null;
        }

        return t;
    }

    @Override
    public <T> void save(final Collection<T> entities) {
        for (Object entity : entities) {
            this.entityManager.merge(entity);
        }
    }

    @Override
    public byte[] toBytesArray(final Blob blob) {

        try {
            int blobLength = (int) blob.length();
            byte[] blobAsBytes = blob.getBytes(1, blobLength);
            return blobAsBytes;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Transform results from a AliasToEntityMapResultTransformer
     * to an actual class.
     * Better than using AliasToBeanResultTransformer
     * because it supports nested classes.
     * @param <T> Type of class
     * @param maps {@link List}
     * @param clazz {@link Class}
     * @return {@link List}
     */
    protected <T> List<T> transformMapListToObject(final List<Map<String, Object>> maps, final Class<T> clazz) {

        BeanUtilsBean utils = ObjectBuilder.getBeanUtils();

        List<T> list = new ArrayList<>();

        try {

            for (Map<String, Object> map : maps) {
                T bean = clazz.newInstance();

                utils.populate(bean, map);
                list.add(bean);
            }

            return list;

        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Update Pagination Information and return truncated list objects.
     * @param <T> T
     * @param dto {@link PaginationDTO}
     * @param offset int
     * @param max int
     * @param list List
     * @return List
     */
    protected <T> List<T> updatePagination(final PaginationDTO dto, final int offset, final int max,
            final List<T> list) {

        int listcount = list.size();

        if (offset > 0) {
            String prevToken = Strings.generateOffsetToken(offset - max, max);
            dto.setPrevtoken(prevToken);
        }

        if (listcount > max) {
            int offset1 = offset + max;
            String nextToken = Strings.generateOffsetToken(offset1, max);
            dto.setNexttoken(nextToken);
        }

        if (list.size() > max) {
            list.remove(max);
        }

        return list;
    }
}