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

Java tutorial

Introduction

Here is the source code for net.navasoft.madcoin.backend.model.controller.impl.LocationsDataAccess.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.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.NormalizedEntity;
import net.navasoft.madcoin.backend.model.entities.ReferenceMode;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestLocations;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestLocationsPK;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequests;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsPK;
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
 * LocationsDataAccess. Description:
 * 
 * @author Juan Diego Navarre Gonzalez - (${authorMail})
 * @version 1.0
 * @since 2/09/2014 09:31:42 PM
 */
@Repository("locationsDAO")
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class LocationsDataAccess extends JPAHelper<WorkRequestLocations>
        implements IDataAccess<WorkRequestLocations> {

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

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

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

    /**
     * Creates the.
     * 
     * @param workRequestLocations
     *            the work request locations
     * @return the work request locations
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public WorkRequestLocations create(WorkRequestLocations workRequestLocations) {
        preConstruct(workRequestLocations);
        entityManager.persist(workRequestLocations);
        entityManager.flush();
        workRequestLocations = getByLogicalId(workRequestLocations.getNormalizedId());
        postConstruct(workRequestLocations);
        return workRequestLocations;
    }

    /**
     * Pre construct.
     * 
     * @param entity
     *            the entity
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    public void preConstruct(WorkRequestLocations entity) {
        if (entity.getWorkRequestLocationsPK() == null) {
            entity.setWorkRequestLocationsPK(new WorkRequestsPK());
        }
        entity.getWorkRequestLocationsPK()
                .setIdWorkRequests(entity.getWorkRequests().getWorkRequestsPK().getIdWorkRequests());
        entity.getWorkRequestLocationsPK()
                .setCategoryId(entity.getWorkRequests().getWorkRequestsPK().getCategoryId());
        List<String> illegalOrphanMessages = null;
        WorkRequests workRequestsOrphanCheck = entity.getWorkRequests();
        if (workRequestsOrphanCheck != null) {
            WorkRequestLocations oldWorkRequestLocationsOfWorkRequests = workRequestsOrphanCheck
                    .getWorkRequestLocations();
            if (oldWorkRequestLocationsOfWorkRequests != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The WorkRequests " + workRequestsOrphanCheck
                        + " already has an item of type WorkRequestLocations whose workRequests column cannot be null. Please make another selection for the workRequests field.");
            }
        }
        if (illegalOrphanMessages != null) {
            String finalMessage = "";
            for (String msg : illegalOrphanMessages) {
                finalMessage += msg + " ";
            }
            throw new AlreadyOnSourceException(finalMessage);
        }
        WorkRequests workRequests = entity.getWorkRequests();
        if (workRequests != null) {
            workRequests = entityManager.getReference(workRequests.getClass(), workRequests.getWorkRequestsPK());
            entity.setWorkRequests(workRequests);
            storage.storeReference(LocationsStorageKeys.ORDER, ReferenceMode.NEW_REFERENCE, workRequests);
        }
    }

    /**
     * Post construct.
     * 
     * @param location
     *            the location
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    public void postConstruct(WorkRequestLocations location) {
        WorkRequests workRequests;
        if (storage.validateReference(LocationsStorageKeys.ORDER, ReferenceMode.NEW_REFERENCE)) {
            workRequests = (WorkRequests) storage.extractReference(LocationsStorageKeys.ORDER,
                    ReferenceMode.NEW_REFERENCE);
            workRequests.setWorkRequestLocations(location);
            workRequests = entityManager.merge(workRequests);
        }

    }

    /**
     * Edits the.
     * 
     * @param workRequestLocations
     *            the work request locations
     * @return the work request locations
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws Exception
     *             the exception
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    public WorkRequestLocations edit(WorkRequestLocations workRequestLocations)
            throws IllegalOrphanException, NonexistentEntityException, Exception {
        preEdit(workRequestLocations);
        workRequestLocations = entityManager.merge(workRequestLocations);
        entityManager.flush();
        postEdit(workRequestLocations);
        return workRequestLocations;
    }

    /**
     * Delete by id.
     * 
     * @param id
     *            the id
     * @return the work request locations
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public WorkRequestLocations deleteById(Serializable id)
            throws NonexistentEntityException, IllegalOrphanException {
        WorkRequestLocations deleted = preDelete((WorkRequestLocationsPK) id);
        entityManager.remove(deleted);
        return deleted;
    }

    /**
     * Pre delete.
     * 
     * @param toDelete
     *            the to delete
     * @return the work request locations
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    public WorkRequestLocations preDelete(Number toDelete)
            throws NonexistentEntityException, IllegalOrphanException {
        throw new NotImplementedException();
    }

    /**
     * Pre delete.
     * 
     * @param toDelete
     *            the to delete
     * @return the work request locations
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    public WorkRequestLocations preDelete(ComplexId toDelete)
            throws NonexistentEntityException, IllegalOrphanException {
        WorkRequestLocations workRequestLocations;
        try {
            workRequestLocations = entityManager.getReference(WorkRequestLocations.class, toDelete);
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException(
                    "The workRequestLocations with id " + toDelete.resume() + " no longer exists.", enfe);
        }
        WorkRequests workRequests = workRequestLocations.getWorkRequests();
        if (workRequests != null) {
            workRequests.setWorkRequestLocations(null);
            workRequests = entityManager.merge(workRequests);
        }
        return workRequestLocations;
    }

    /**
     * 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:42 PM
     */
    @Override
    public void preEdit(WorkRequestLocations toEdit) throws NonexistentEntityException, IllegalOrphanException {
        toEdit.getWorkRequestLocationsPK()
                .setIdWorkRequests(toEdit.getWorkRequests().getWorkRequestsPK().getIdWorkRequests());
        toEdit.getWorkRequestLocationsPK()
                .setCategoryId(toEdit.getWorkRequests().getWorkRequestsPK().getCategoryId());
        try {
            WorkRequestLocations persistentWorkRequestLocations = entityManager.find(WorkRequestLocations.class,
                    toEdit.getWorkRequestLocationsPK());
            WorkRequests workRequestsOld = persistentWorkRequestLocations.getWorkRequests();
            WorkRequests workRequestsNew = toEdit.getWorkRequests();
            List<String> illegalOrphanMessages = null;
            if (workRequestsNew != null && !workRequestsNew.equals(workRequestsOld)) {
                WorkRequestLocations oldWorkRequestLocationsOfWorkRequests = workRequestsNew
                        .getWorkRequestLocations();
                if (oldWorkRequestLocationsOfWorkRequests != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The WorkRequests " + workRequestsNew
                            + " already has an item of type WorkRequestLocations whose workRequests column cannot be null. Please make another selection for the workRequests field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (workRequestsNew != null) {
                workRequestsNew = entityManager.getReference(workRequestsNew.getClass(),
                        workRequestsNew.getWorkRequestsPK());
                toEdit.setWorkRequests(workRequestsNew);
            }
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                WorkRequestsPK id = toEdit.getWorkRequestLocationsPK();
                if (findByComplexId(entityManager, id, WorkRequestLocations.class) == null) {
                    throw new NonexistentEntityException(
                            "The workRequestLocations with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
    }

    /**
     * Post edit.
     * 
     * @param entity
     *            the entity
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    public void postEdit(WorkRequestLocations entity) {
        WorkRequests workRequestsOld, workRequestsNew;

        if (storage.compareReferences(LocationsStorageKeys.ORDER, ReferenceMode.OLD_REFERENCE)) {
            workRequestsOld = (WorkRequests) storage.extractReference(LocationsStorageKeys.ORDER,
                    ReferenceMode.OLD_REFERENCE);
            workRequestsOld.setWorkRequestLocations(null);
            workRequestsOld = entityManager.merge(workRequestsOld);
        }
        if (storage.compareReferences(LocationsStorageKeys.ORDER, ReferenceMode.NEW_REFERENCE)) {
            workRequestsNew = (WorkRequests) storage.extractReference(LocationsStorageKeys.ORDER,
                    ReferenceMode.NEW_REFERENCE);
            workRequestsNew.setWorkRequestLocations(entity);
            workRequestsNew = entityManager.merge(workRequestsNew);
        }
        storage.clean();
    }

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

    /**
     * Gets the by logical id.
     * 
     * @param idEntity
     *            the id entity
     * @return the by logical id
     * @since 2/09/2014, 09:31:42 PM
     */
    @Override
    public WorkRequestLocations getByLogicalId(Serializable idEntity) {
        TypedQuery<WorkRequestLocations> query = entityManager.createNamedQuery(
                "WorkRequestLocations." + NormalizedEntity.NAMED_QUERY_ID, WorkRequestLocations.class);
        query.setParameter("idService", ((WorkRequestsPK) idEntity).getIdWorkRequests());
        query.setParameter("categoryPrefix", ((WorkRequestsPK) idEntity).getCategoryId());
        return query.getSingleResult();
    }

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

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

        /**
         * order.
         * 
         * @since 2/09/2014, 09:31:42 PM
         */
        ORDER("workRequests");

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

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

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

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