net.navasoft.madcoin.backend.model.controller.impl.CategoryDataAccess.java Source code

Java tutorial

Introduction

Here is the source code for net.navasoft.madcoin.backend.model.controller.impl.CategoryDataAccess.java

Source

/*******************************************************************************
 * Copyright 2014 Juan Diego Navarre Gonzalez
 * 
 * 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 net.navasoft.madcoin.backend.model.controller.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import net.navasoft.madcoin.backend.model.controller.exceptions.AlreadyOnSourceException;
import net.navasoft.madcoin.backend.model.controller.exceptions.IllegalOrphanException;
import net.navasoft.madcoin.backend.model.controller.exceptions.NonexistentEntityException;
import net.navasoft.madcoin.backend.model.controller.helper.ComplexId;
import net.navasoft.madcoin.backend.model.controller.helper.impl.JPAHelper;
import net.navasoft.madcoin.backend.model.entities.ReferenceMode;
import net.navasoft.madcoin.backend.model.entities.impl.BusinessLines;
import net.navasoft.madcoin.backend.model.entities.impl.ServiceCategories;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequests;
import net.navasoft.madcoin.backend.services.rest.impl.IDataAccess;

import org.apache.commons.lang.NotImplementedException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * net.navasoft.madcoin.backend.model.controller.impl Class class
 * CategoryDataAccess. Description:
 * 
 * @author Juan Diego Navarre Gonzalez - (${authorMail})
 * @version 1.0
 * @since 2/09/2014 09:31:50 PM
 */
@Repository("categoryDAO")
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class CategoryDataAccess extends JPAHelper<ServiceCategories> implements IDataAccess<ServiceCategories> {

    /**
     * storage.
     * 
     * @since 2/09/2014, 09:31:50 PM
     */
    private Storage storage;

    /**
     * entity manager.
     * 
     * @since 2/09/2014, 09:31:50 PM
     */
    @PersistenceContext(unitName = "ClickNDone-PU")
    private EntityManager entityManager;

    /**
     * Instantiates a new category data access.
     * 
     * @since 2/09/2014, 09:31:50 PM
     */
    public CategoryDataAccess() {
        storage = StorageFactory.buildStorage();
    }

    /**
     * Creates the.
     * 
     * @param serviceCategories
     *            the service categories
     * @return the service categories
     * @since 2/09/2014, 09:31:50 PM
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public ServiceCategories create(ServiceCategories serviceCategories) {
        preConstruct(serviceCategories);
        entityManager.persist(serviceCategories);
        entityManager.flush();
        serviceCategories = findLast(entityManager, ServiceCategories.class, serviceCategories);
        postConstruct(serviceCategories);
        return serviceCategories;
    }

    /**
     * Edits the.
     * 
     * @param serviceCategories
     *            the service categories
     * @return the service categories
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws Exception
     *             the exception
     * @since 2/09/2014, 09:31:50 PM
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public ServiceCategories edit(ServiceCategories serviceCategories)
            throws IllegalOrphanException, NonexistentEntityException, Exception {
        preEdit(serviceCategories);
        serviceCategories = entityManager.merge(serviceCategories);
        entityManager.flush();
        postEdit(serviceCategories);
        return serviceCategories;
    }

    /**
     * Pre construct.
     * 
     * @param serviceCategories
     *            the service categories
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public void preConstruct(ServiceCategories serviceCategories) {
        if (serviceCategories.getWorkRequestsCollection() == null) {
            serviceCategories.setWorkRequestsCollection(new ArrayList<WorkRequests>());
        }
        try {
            BusinessLines parentLob = serviceCategories.getParentLob();
            if (parentLob != null) {
                parentLob = entityManager.getReference(parentLob.getClass(), parentLob.getIdbusinessLine());
                serviceCategories.setParentLob(parentLob);
                storage.storeReference(CategoryStorageKeys.LOB, ReferenceMode.NEW_REFERENCE, parentLob);
            }
            Collection<WorkRequests> orders = new ArrayList<WorkRequests>();
            for (WorkRequests order : serviceCategories.getWorkRequestsCollection()) {
                order = entityManager.getReference(order.getClass(), order.getWorkRequestsPK());
                orders.add(order);
            }
            serviceCategories.setWorkRequestsCollection(orders);
            storage.storeReference(CategoryStorageKeys.ORDERS, ReferenceMode.NEW_REFERENCE, orders);
        } catch (Exception ex) {
            if (findBySimpleId(entityManager, serviceCategories.getIdServiceCategory(),
                    ServiceCategories.class) != null) {
                throw new AlreadyOnSourceException(
                        "ServiceCategories " + serviceCategories.toString() + " already exists.");
            }
            throw ex;
        }
    }

    /**
     * Post construct.
     * 
     * @param serviceCategories
     *            the service categories
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public void postConstruct(ServiceCategories serviceCategories) {
        BusinessLines parentLob;
        if (storage.validateReference(CategoryStorageKeys.LOB, ReferenceMode.NEW_REFERENCE)) {
            parentLob = (BusinessLines) storage.extractReference(CategoryStorageKeys.LOB,
                    ReferenceMode.NEW_REFERENCE);
            parentLob.getServiceCategoriesCollection().add(serviceCategories);
            parentLob = entityManager.merge(parentLob);
        }
        for (WorkRequests workRequestsCollectionWorkRequests : serviceCategories.getWorkRequestsCollection()) {
            ServiceCategories oldServiceCategoriesOfWorkRequestsCollectionWorkRequests = workRequestsCollectionWorkRequests
                    .getServiceCategories();
            workRequestsCollectionWorkRequests.setServiceCategories(serviceCategories);
            workRequestsCollectionWorkRequests = entityManager.merge(workRequestsCollectionWorkRequests);
            if (oldServiceCategoriesOfWorkRequestsCollectionWorkRequests != null) {
                oldServiceCategoriesOfWorkRequestsCollectionWorkRequests.getWorkRequestsCollection()
                        .remove(workRequestsCollectionWorkRequests);
                oldServiceCategoriesOfWorkRequestsCollectionWorkRequests = entityManager
                        .merge(oldServiceCategoriesOfWorkRequestsCollectionWorkRequests);
            }
        }
        storage.clean();
    }

    /**
     * Pre delete.
     * 
     * @param toDelete
     *            the to delete
     * @return the service categories
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public ServiceCategories preDelete(Number toDelete) throws NonexistentEntityException, IllegalOrphanException {
        ServiceCategories serviceCategories;
        try {
            serviceCategories = entityManager.getReference(ServiceCategories.class, toDelete);
            serviceCategories.getIdServiceCategory();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException(
                    "The serviceCategories with id " + toDelete.toString() + " no longer exists.", enfe);
        }
        List<String> illegalOrphanMessages = null;
        Collection<WorkRequests> workRequestsCollectionOrphanCheck = serviceCategories.getWorkRequestsCollection();
        for (WorkRequests workRequestsCollectionOrphanCheckWorkRequests : workRequestsCollectionOrphanCheck) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add(
                    "This ServiceCategories (" + serviceCategories + ") cannot be destroyed since the WorkRequests "
                            + workRequestsCollectionOrphanCheckWorkRequests
                            + " in its workRequestsCollection field has a non-nullable serviceCategories field.");
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        BusinessLines parentLob = serviceCategories.getParentLob();
        if (parentLob != null) {
            parentLob.getServiceCategoriesCollection().remove(serviceCategories);
            parentLob = entityManager.merge(parentLob);
        }
        return serviceCategories;
    }

    /**
     * Pre delete.
     * 
     * @param toDelete
     *            the to delete
     * @return the service categories
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public ServiceCategories preDelete(ComplexId toDelete)
            throws NonexistentEntityException, IllegalOrphanException {
        throw new NotImplementedException();
    }

    /**
     * Pre edit.
     * 
     * @param serviceCategories
     *            the service categories
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public void preEdit(ServiceCategories serviceCategories)
            throws NonexistentEntityException, IllegalOrphanException {
        try {
            ServiceCategories persistentServiceCategories = entityManager.find(ServiceCategories.class,
                    serviceCategories.getIdServiceCategory());
            BusinessLines parentLobOld = persistentServiceCategories.getParentLob();
            storage.storeReference(CategoryStorageKeys.LOB, ReferenceMode.OLD_REFERENCE, parentLobOld);
            BusinessLines parentLobNew = serviceCategories.getParentLob();

            Collection<WorkRequests> workRequestsCollectionOld = persistentServiceCategories
                    .getWorkRequestsCollection();
            storage.storeReference(CategoryStorageKeys.ORDERS, ReferenceMode.OLD_REFERENCE,
                    workRequestsCollectionOld);
            Collection<WorkRequests> workRequestsCollectionNew = serviceCategories.getWorkRequestsCollection();

            List<String> illegalOrphanMessages = null;
            for (WorkRequests workRequestsCollectionOldWorkRequests : workRequestsCollectionOld) {
                if (!workRequestsCollectionNew.contains(workRequestsCollectionOldWorkRequests)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages
                            .add("You must retain WorkRequests " + workRequestsCollectionOldWorkRequests.toString()
                                    + " since its serviceCategories field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (parentLobNew != null) {
                parentLobNew = entityManager.getReference(parentLobNew.getClass(),
                        parentLobNew.getIdbusinessLine());
                serviceCategories.setParentLob(parentLobNew);
                storage.storeReference(CategoryStorageKeys.LOB, ReferenceMode.NEW_REFERENCE, parentLobNew);
            }
            Collection<WorkRequests> attachedWorkRequestsCollectionNew = new ArrayList<WorkRequests>();
            for (WorkRequests workRequestsCollectionNewWorkRequestsToAttach : workRequestsCollectionNew) {
                workRequestsCollectionNewWorkRequestsToAttach = entityManager.getReference(
                        workRequestsCollectionNewWorkRequestsToAttach.getClass(),
                        workRequestsCollectionNewWorkRequestsToAttach.getWorkRequestsPK());
                attachedWorkRequestsCollectionNew.add(workRequestsCollectionNewWorkRequestsToAttach);
            }
            workRequestsCollectionNew = attachedWorkRequestsCollectionNew;
            serviceCategories.setWorkRequestsCollection(workRequestsCollectionNew);
            storage.storeReference(CategoryStorageKeys.ORDERS, ReferenceMode.NEW_REFERENCE,
                    workRequestsCollectionNew);
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = serviceCategories.getIdServiceCategory();
                if (findBySimpleId(entityManager, id, ServiceCategories.class) == null) {
                    throw new NonexistentEntityException(
                            "The serviceCategories with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
    }

    /**
     * Post edit.
     * 
     * @param serviceCategories
     *            the service categories
     * @since 2/09/2014, 09:31:50 PM
     */
    @SuppressWarnings("unchecked")
    @Override
    public void postEdit(ServiceCategories serviceCategories) {
        BusinessLines parentLobOld, parentLobNew;

        if (storage.compareReferences(CategoryStorageKeys.LOB, ReferenceMode.OLD_REFERENCE)) {
            parentLobOld = (BusinessLines) storage.extractReference(CategoryStorageKeys.LOB,
                    ReferenceMode.OLD_REFERENCE);
            parentLobOld.getServiceCategoriesCollection().remove(serviceCategories);
            parentLobOld = entityManager.merge(parentLobOld);
        }

        if (storage.compareReferences(CategoryStorageKeys.LOB, ReferenceMode.NEW_REFERENCE)) {
            parentLobNew = (BusinessLines) storage.extractReference(CategoryStorageKeys.LOB,
                    ReferenceMode.NEW_REFERENCE);
            parentLobNew.getServiceCategoriesCollection().add(serviceCategories);
            parentLobNew = entityManager.merge(parentLobNew);
        }

        Collection<WorkRequests> workRequestsCollectionOld = (Collection<WorkRequests>) storage
                .extractReferences(CategoryStorageKeys.ORDERS, ReferenceMode.OLD_REFERENCE);
        Collection<WorkRequests> workRequestsCollectionNew = (Collection<WorkRequests>) storage
                .extractReferences(CategoryStorageKeys.ORDERS, ReferenceMode.NEW_REFERENCE);

        for (WorkRequests workRequestsCollectionNewWorkRequests : workRequestsCollectionNew) {
            if (!workRequestsCollectionOld.contains(workRequestsCollectionNewWorkRequests)) {
                ServiceCategories oldServiceCategoriesOfWorkRequestsCollectionNewWorkRequests = workRequestsCollectionNewWorkRequests
                        .getServiceCategories();
                workRequestsCollectionNewWorkRequests.setServiceCategories(serviceCategories);
                workRequestsCollectionNewWorkRequests = entityManager.merge(workRequestsCollectionNewWorkRequests);
                if (oldServiceCategoriesOfWorkRequestsCollectionNewWorkRequests != null
                        && !oldServiceCategoriesOfWorkRequestsCollectionNewWorkRequests.equals(serviceCategories)) {
                    oldServiceCategoriesOfWorkRequestsCollectionNewWorkRequests.getWorkRequestsCollection()
                            .remove(workRequestsCollectionNewWorkRequests);
                    oldServiceCategoriesOfWorkRequestsCollectionNewWorkRequests = entityManager
                            .merge(oldServiceCategoriesOfWorkRequestsCollectionNewWorkRequests);
                }
            }
        }

    }

    /**
     * Gets the all.
     * 
     * @return the all
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public List<ServiceCategories> getAll() {
        return getAllbyQuery(entityManager, ServiceCategories.class);
    }

    /**
     * Gets the by logical id.
     * 
     * @param idEntity
     *            the id entity
     * @return the by logical id
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public ServiceCategories getByLogicalId(Serializable idEntity) {
        TypedQuery<ServiceCategories> query = entityManager.createNamedQuery(
                ServiceCategories.class.getSimpleName() + ".findByCategoryPrefix", ServiceCategories.class);
        query.setParameter("categoryPrefix", (String) idEntity);
        return query.getSingleResult();
    }

    /**
     * Delete by id.
     * 
     * @param idEntity
     *            the id entity
     * @return the serializable
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public Serializable deleteById(Serializable idEntity)
            throws NonexistentEntityException, IllegalOrphanException {
        ServiceCategories deleted = preDelete((Number) idEntity);
        entityManager.remove(deleted);
        entityManager.flush();
        return deleted;
    }

    /**
     * Delete all.
     * 
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public void deleteAll() throws NonexistentEntityException, IllegalOrphanException {
        for (ServiceCategories cat : getAll()) {
            deleteById(cat.getNormalizedId());
        }

    }

    /**
     * net.navasoft.madcoin.backend.model.controller.impl Enum enum
     * CategoryStorageKeys. Description:
     * 
     * @author Juan Diego Navarre Gonzalez - (${authorMail})
     * @version 1.0
     * @since 2/09/2014 09:31:50 PM
     */
    private enum CategoryStorageKeys implements StorageKeys {

        /**
         * lob.
         * 
         * @since 2/09/2014, 09:31:50 PM
         */
        LOB("parentLob"),
        /**
         * orders.
         * 
         * @since 2/09/2014, 09:31:50 PM
         */
        ORDERS("orders");

        /**
         * key.
         * 
         * @since 2/09/2014, 09:31:50 PM
         */
        private String key;

        /**
         * Instantiates a new category storage keys.
         * 
         * @param finalKey
         *            the final key
         * @since 2/09/2014, 09:31:50 PM
         */
        private CategoryStorageKeys(String finalKey) {
            key = finalKey;
        }

        /**
         * Gets the key.
         * 
         * @return the key
         * @since 2/09/2014, 09:31:50 PM
         */
        @Override
        public String getKey() {
            return key;
        }
    }

    /**
     * Count.
     * 
     * @return the int
     * @since 2/09/2014, 09:31:50 PM
     */
    @Override
    public int count() {
        return super.getQuantity(entityManager, ServiceCategories.class);
    }

}