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

Java tutorial

Introduction

Here is the source code for net.navasoft.madcoin.backend.model.controller.impl.ApplicationUserDataAccess.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.IllegalOrphanException;
import net.navasoft.madcoin.backend.model.controller.exceptions.NonexistentEntityException;
import net.navasoft.madcoin.backend.model.controller.exceptions.PreexistingEntityException;
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.AppUserXStatus;
import net.navasoft.madcoin.backend.model.entities.impl.AppUsers;
import net.navasoft.madcoin.backend.model.entities.impl.EndUsers;
import net.navasoft.madcoin.backend.services.rest.impl.IDataAccess;

import org.apache.commons.lang.NotImplementedException;
import org.hibernate.exception.ConstraintViolationException;
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
 * ApplicationUserDataAccess. Description:
 * 
 * @author Juan Diego Navarre Gonzalez - (${authorMail})
 * @version 1.0
 * @since 2/09/2014 09:31:39 PM
 */
@Repository("appUsersDao")
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class ApplicationUserDataAccess extends JPAHelper<AppUsers> implements IDataAccess<AppUsers> {

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

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

    /**
     * Instantiates a new application user data access.
     * 
     * @since 2/09/2014, 09:31:39 PM
     */
    public ApplicationUserDataAccess() {
        storage = StorageFactory.buildStorage();
    }

    /**
     * Pre construct.
     * 
     * @param toInsert
     *            the to insert
     * @since 2/09/2014, 09:31:39 PM
     */
    @Override
    public void preConstruct(AppUsers toInsert) {
        if (toInsert.getAppUserXStatusCollection() == null) {
            toInsert.setAppUserXStatusCollection(new ArrayList<AppUserXStatus>());
        }
        if (toInsert.getEndUsersCollection() == null) {
            toInsert.setEndUsersCollection(new ArrayList<EndUsers>());
        }
        Collection<AppUserXStatus> statusToAdd = new ArrayList<AppUserXStatus>();
        for (AppUserXStatus statuses : toInsert.getAppUserXStatusCollection()) {
            statuses = entityManager.getReference(statuses.getClass(), statuses.getIdUserXStatus());
            statusToAdd.add(statuses);
        }
        toInsert.setAppUserXStatusCollection(statusToAdd);
        Collection<EndUsers> endUsers = new ArrayList<EndUsers>();
        for (EndUsers endUser : toInsert.getEndUsersCollection()) {
            endUser = entityManager.getReference(endUser.getClass(), endUser.getEndUsersPK());
            endUsers.add(endUser);
        }
        toInsert.setEndUsersCollection(endUsers);
    }

    /**
     * Post construct.
     * 
     * @param inserted
     *            the inserted
     * @since 2/09/2014, 09:31:39 PM
     */
    @Override
    public void postConstruct(AppUsers inserted) {
        for (AppUserXStatus newstatus : inserted.getAppUserXStatusCollection()) {
            AppUsers oldStatusUser = newstatus.getIdUser();
            newstatus.setIdUser(inserted);
            newstatus = entityManager.merge(newstatus);
            if (oldStatusUser != null) {
                oldStatusUser.getAppUserXStatusCollection().remove(newstatus);
                oldStatusUser = entityManager.merge(oldStatusUser);
            }
        }
        for (EndUsers userReference : inserted.getEndUsersCollection()) {
            AppUsers oldUserRef = userReference.getAppUsers();
            userReference.setAppUsers(inserted);
            userReference = entityManager.merge(userReference);
            if (oldUserRef != null) {
                oldUserRef.getEndUsersCollection().remove(userReference);
                oldUserRef = entityManager.merge(oldUserRef);
            }
        }
    }

    /**
     * Pre delete.
     * 
     * @param toDelete
     *            the to delete
     * @return the app users
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:39 PM
     */
    @Override
    public AppUsers preDelete(Number toDelete) throws NonexistentEntityException, IllegalOrphanException {
        AppUsers appUsers;
        try {
            appUsers = entityManager.getReference(AppUsers.class, toDelete);
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException(
                    "The appUsers with id " + toDelete.toString() + " no longer exists.", enfe);
        }
        List<String> illegalOrphanMessages = null;

        Collection<AppUserXStatus> statiRef = appUsers.getAppUserXStatusCollection();
        for (AppUserXStatus statRef : statiRef) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This AppUsers (" + appUsers.toString()
                    + ") cannot be destroyed since the AppUserXStatus " + statRef.toString()
                    + " in its appUserXStatusCollection field has a non-nullable idUser field.");
        }
        Collection<EndUsers> endUsersRef = appUsers.getEndUsersCollection();
        for (EndUsers endUserRef : endUsersRef) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This AppUsers (" + appUsers.toString()
                    + ") cannot be destroyed since the EndUsers " + endUserRef.toString()
                    + " in its endUsersCollection field has a non-nullable appUsers field.");
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        return appUsers;
    }

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

    /**
     * Pre edit.
     * 
     * @param toEdit
     *            the to edit
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public void preEdit(AppUsers toEdit) throws NonexistentEntityException, IllegalOrphanException {
        AppUsers existent = entityManager.getReference(AppUsers.class, toEdit.getIdApplicationUsers());

        Collection<AppUserXStatus> oldStatus = existent.getAppUserXStatusCollection();
        storage.storeReference(AppUserStorageKeys.STATUS, ReferenceMode.OLD_REFERENCE, oldStatus);

        Collection<AppUserXStatus> newStatus = toEdit.getAppUserXStatusCollection();

        Collection<EndUsers> oldEndUsers = existent.getEndUsersCollection();
        storage.storeReference(AppUserStorageKeys.END_USERS, ReferenceMode.OLD_REFERENCE, oldEndUsers);
        Collection<EndUsers> newEndUsers = toEdit.getEndUsersCollection();

        List<String> illegalOrphanMessages = null;
        for (AppUserXStatus oldStat : oldStatus) {
            if (!newStatus.contains(oldStat)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain AppUserXStatus " + oldStat.toString()
                        + " since its idUser field is not nullable.");
            }
        }
        for (EndUsers oldEndUser : oldEndUsers) {
            if (!newEndUsers.contains(oldEndUser)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain EndUsers " + oldEndUser.toString()
                        + " since its appUsers field is not nullable.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        Collection<AppUserXStatus> assocStatus = new ArrayList<AppUserXStatus>();
        for (AppUserXStatus newStat : newStatus) {
            newStat = entityManager.getReference(newStat.getClass(), newStat.getIdUserXStatus());
            assocStatus.add(newStat);
        }
        newStatus = assocStatus;
        toEdit.setAppUserXStatusCollection(newStatus);
        storage.storeReference(AppUserStorageKeys.STATUS, ReferenceMode.NEW_REFERENCE, newStatus);

        Collection<EndUsers> newChildren = new ArrayList<EndUsers>();
        for (EndUsers newEndUser : newEndUsers) {
            newEndUser = entityManager.getReference(newEndUser.getClass(), newEndUser.getEndUsersPK());
            newChildren.add(newEndUser);
        }
        newEndUsers = newChildren;
        toEdit.setEndUsersCollection(newEndUsers);
        storage.storeReference(AppUserStorageKeys.END_USERS, ReferenceMode.NEW_REFERENCE, newEndUsers);
    }

    /**
     * Post edit.
     * 
     * @param entity
     *            the entity
     * @since 2/09/2014, 09:31:40 PM
     */
    @SuppressWarnings("unchecked")
    @Override
    public void postEdit(AppUsers entity) {
        Collection<AppUserXStatus> oldStatus = (Collection<AppUserXStatus>) storage
                .extractReferences(AppUserStorageKeys.STATUS, ReferenceMode.OLD_REFERENCE);
        Collection<AppUserXStatus> newStatus = (Collection<AppUserXStatus>) storage
                .extractReferences(AppUserStorageKeys.STATUS, ReferenceMode.NEW_REFERENCE);

        Collection<EndUsers> oldEndUsers = (Collection<EndUsers>) storage
                .extractReferences(AppUserStorageKeys.END_USERS, ReferenceMode.OLD_REFERENCE);
        Collection<EndUsers> newEndUsers = (Collection<EndUsers>) storage
                .extractReferences(AppUserStorageKeys.END_USERS, ReferenceMode.NEW_REFERENCE);

        for (AppUserXStatus newStat : newStatus) {
            if (!oldStatus.contains(newStat)) {
                AppUsers newAppUserRef = newStat.getIdUser();
                newStat.setIdUser(entity);
                newStat = entityManager.merge(newStat);
                if (newAppUserRef != null && !newAppUserRef.equals(entity)) {
                    newAppUserRef.getAppUserXStatusCollection().remove(newStat);
                    newAppUserRef = entityManager.merge(newAppUserRef);
                }
            }
        }

        for (EndUsers newEndUser : newEndUsers) {
            if (!oldEndUsers.contains(newEndUser)) {
                AppUsers oldAppUser = newEndUser.getAppUsers();
                newEndUser.setAppUsers(entity);
                newEndUser = entityManager.merge(newEndUser);
                if (oldAppUser != null && !oldAppUser.equals(entity)) {
                    oldAppUser.getEndUsersCollection().remove(newEndUser);
                    oldAppUser = entityManager.merge(oldAppUser);
                }
            }
        }
    }

    /**
     * Creates the.
     * 
     * @param newRecord
     *            the new record
     * @return the app users
     * @throws PreexistingEntityException
     *             the preexisting entity exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public AppUsers create(AppUsers newRecord) throws PreexistingEntityException {
        try {
            preConstruct(newRecord);
            entityManager.persist(newRecord);
            entityManager.flush();
            newRecord = findLast(entityManager, AppUsers.class, newRecord);
            postConstruct(newRecord);
            return newRecord;
        } catch (ConstraintViolationException duplicate) {
            throw new PreexistingEntityException(duplicate.getMessage(), duplicate.getCause());
        }
    }

    /**
     * Edits the.
     * 
     * @param updatedRecord
     *            the updated record
     * @return the app users
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws Exception
     *             the exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public AppUsers edit(AppUsers updatedRecord) throws NonexistentEntityException, Exception {
        preEdit(updatedRecord);
        updatedRecord = entityManager.merge(updatedRecord);
        postEdit(updatedRecord);
        return updatedRecord;
    }

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

    /**
     * Gets the by logical id.
     * 
     * @param idEntity
     *            the id entity
     * @return the by logical id
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public AppUsers getByLogicalId(Serializable idEntity) {
        TypedQuery<AppUsers> query = entityManager.createNamedQuery("AppUsers.findByIdApplicationUsers",
                AppUsers.class);
        query.setParameter("idApplicationUsers", ((Long) idEntity));
        return query.getSingleResult();
    }

    /**
     * Delete by id.
     * 
     * @param idEntity
     *            the id entity
     * @return the app users
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public AppUsers deleteById(Serializable idEntity) throws NonexistentEntityException, IllegalOrphanException {
        AppUsers 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:40 PM
     */
    @Override
    public void deleteAll() throws NonexistentEntityException, IllegalOrphanException {
        for (AppUsers user : getAll()) {
            deleteById(user.getNormalizedId());
        }
    }

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

        /**
         * status.
         * 
         * @since 2/09/2014, 09:31:40 PM
         */
        STATUS("appUserXStatusCollection"),

        /**
         * end users.
         * 
         * @since 2/09/2014, 09:31:40 PM
         */
        END_USERS("endUsersCollection");

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

        /**
         * Instantiates a new app user storage keys.
         * 
         * @param realKey
         *            the real key
         * @since 2/09/2014, 09:31:40 PM
         */
        private AppUserStorageKeys(String realKey) {
            key = realKey;
        }

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

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

}