Example usage for javax.persistence EntityManager merge

List of usage examples for javax.persistence EntityManager merge

Introduction

In this page you can find the example usage for javax.persistence EntityManager merge.

Prototype

public <T> T merge(T entity);

Source Link

Document

Merge the state of the given entity into the current persistence context.

Usage

From source file:org.sigmah.server.servlet.exporter.models.OrgUnitModelHandler.java

/**
 * Save the flexible elements of imported organizational unit model
 * //from   w  w w.j  a v a 2s.co m
 * @param orgUnitModel
 *          the imported organizational unit model
 * @param em
 *          the entity manager
 */
private void saveOrgUnitFlexibleElement(OrgUnitModel orgUnitModel, EntityManager em) {
    // OrgUnitModel --> Banner --> Layout --> Groups --> Constraints
    if (orgUnitModel.getBanner() != null && orgUnitModel.getBanner().getLayout() != null) {
        List<LayoutGroup> bannerLayoutGroups = orgUnitModel.getBanner().getLayout().getGroups();
        if (bannerLayoutGroups != null) {
            for (LayoutGroup layoutGroup : bannerLayoutGroups) {
                List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints();
                if (layoutConstraints != null) {
                    for (LayoutConstraint layoutConstraint : layoutConstraints) {
                        if (layoutConstraint.getElement() != null) {
                            if (layoutConstraint.getElement() instanceof QuestionElement) {
                                List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
                                        .getElement()).getChoices();
                                CategoryType type = ((QuestionElement) layoutConstraint.getElement())
                                        .getCategoryType();
                                if (questionChoiceElements != null || type != null) {

                                    FlexibleElement parent = layoutConstraint.getElement();
                                    ((QuestionElement) parent).setChoices(null);
                                    ((QuestionElement) parent).setCategoryType(null);
                                    em.persist(parent);

                                    // Save QuestionChoiceElement with their QuestionElement parent(saved above)
                                    if (questionChoiceElements != null) {
                                        for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                            if (questionChoiceElement != null) {
                                                questionChoiceElement.setId(null);
                                                questionChoiceElement
                                                        .setParentQuestion((QuestionElement) parent);
                                                CategoryElement categoryElement = questionChoiceElement
                                                        .getCategoryElement();
                                                if (categoryElement != null) {
                                                    questionChoiceElement.setCategoryElement(null);

                                                    em.persist(questionChoiceElement);
                                                    saveOrgUnitModelCategoryElement(categoryElement, em);
                                                    questionChoiceElement.setCategoryElement(categoryElement);
                                                    em.merge(questionChoiceElement);
                                                } else {
                                                    em.persist(questionChoiceElement);
                                                }
                                            }
                                        }
                                        // Set saved QuestionChoiceElement to QuestionElement parent and update it
                                        ((QuestionElement) parent).setChoices(questionChoiceElements);
                                    }

                                    // Save the Category type of QuestionElement parent(saved above)
                                    if (type != null) {
                                        if (em.find(CategoryType.class, type.getId()) == null) {
                                            List<CategoryElement> typeElements = type.getElements();
                                            if (typeElements != null) {
                                                type.setElements(null);
                                                em.merge(type);
                                                for (CategoryElement element : typeElements) {
                                                    if (em.find(CategoryElement.class,
                                                            element.getId()) == null) {
                                                        element.setParentType(type);
                                                        saveOrgUnitModelCategoryElement(element, em);
                                                    }
                                                }
                                                type.setElements(typeElements);
                                                em.merge(type);
                                            }
                                        }
                                        // Set the saved CategoryType to QuestionElement parent and update it
                                        ((QuestionElement) parent).setCategoryType(type);
                                    }
                                    // Update the QuestionElement parent
                                    em.merge(parent);
                                } else {
                                    em.persist(layoutConstraint.getElement());
                                }
                            } else {
                                em.persist(layoutConstraint.getElement());
                            }
                        }
                    }
                }
            }
        }
    }
    // OrgUnitModel --> Detail --> Layout --> Groups --> Constraints
    if (orgUnitModel.getDetails() != null && orgUnitModel.getDetails().getLayout() != null) {
        List<LayoutGroup> detailLayoutGroups = orgUnitModel.getDetails().getLayout().getGroups();
        if (detailLayoutGroups != null) {
            for (LayoutGroup layoutGroup : detailLayoutGroups) {
                List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints();
                if (layoutConstraints != null) {
                    for (LayoutConstraint layoutConstraint : layoutConstraints) {
                        if (layoutConstraint.getElement() != null) {
                            if (layoutConstraint.getElement() instanceof QuestionElement) {
                                List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
                                        .getElement()).getChoices();
                                CategoryType type = ((QuestionElement) layoutConstraint.getElement())
                                        .getCategoryType();
                                if (questionChoiceElements != null || type != null) {

                                    FlexibleElement parent = layoutConstraint.getElement();
                                    ((QuestionElement) parent).setChoices(null);
                                    ((QuestionElement) parent).setCategoryType(null);
                                    em.persist(parent);

                                    // Save QuestionChoiceElement with their QuestionElement parent(saved above)
                                    if (questionChoiceElements != null) {
                                        for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                            if (questionChoiceElement != null) {
                                                questionChoiceElement.setId(null);
                                                questionChoiceElement
                                                        .setParentQuestion((QuestionElement) parent);
                                                CategoryElement categoryElement = questionChoiceElement
                                                        .getCategoryElement();
                                                if (categoryElement != null) {
                                                    questionChoiceElement.setCategoryElement(null);

                                                    em.persist(questionChoiceElement);
                                                    saveOrgUnitModelCategoryElement(categoryElement, em);
                                                    questionChoiceElement.setCategoryElement(categoryElement);
                                                    em.merge(questionChoiceElement);
                                                } else {
                                                    em.persist(questionChoiceElement);
                                                }
                                            }
                                        }
                                        // Set saved QuestionChoiceElement to QuestionElement parent and update it
                                        ((QuestionElement) parent).setChoices(questionChoiceElements);
                                    }

                                    // Save the Category type of QuestionElement parent(saved above)
                                    if (type != null) {
                                        if (em.find(CategoryType.class, type.getId()) == null) {
                                            List<CategoryElement> typeElements = type.getElements();
                                            if (typeElements != null) {
                                                type.setElements(null);
                                                em.merge(type);
                                                for (CategoryElement element : typeElements) {
                                                    if (em.find(CategoryElement.class,
                                                            element.getId()) == null) {
                                                        element.setParentType(type);
                                                        saveOrgUnitModelCategoryElement(element, em);
                                                    }
                                                }
                                                type.setElements(typeElements);
                                                em.merge(type);
                                            }
                                        }
                                        // Set the saved CategoryType to QuestionElement parent and update it
                                        ((QuestionElement) parent).setCategoryType(type);
                                    }
                                    // Update the QuestionElement parent
                                    em.merge(parent);
                                } else {
                                    em.persist(layoutConstraint.getElement());
                                }
                            } else {
                                em.persist(layoutConstraint.getElement());
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.OrgUnitModelHandler.java

/**
 * Save the flexible elements of imported organizational unit model
 * /*from   ww  w.j ava2  s .c  om*/
 * @param orgUnitModel
 *            the imported organizational unit model
 * @param em
 *            the entity manager
 */
private void saveOrgUnitFlexibleElement(OrgUnitModel orgUnitModel, EntityManager em) {
    // OrgUnitModel --> Banner --> Layout --> Groups --> Constraints
    if (orgUnitModel.getBanner() != null && orgUnitModel.getBanner().getLayout() != null) {
        List<LayoutGroup> bannerLayoutGroups = orgUnitModel.getBanner().getLayout().getGroups();
        if (bannerLayoutGroups != null) {
            for (LayoutGroup layoutGroup : bannerLayoutGroups) {
                List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints();
                if (layoutConstraints != null) {
                    for (LayoutConstraint layoutConstraint : layoutConstraints) {
                        if (layoutConstraint.getElement() != null) {
                            if (layoutConstraint.getElement() instanceof QuestionElement) {
                                List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
                                        .getElement()).getChoices();
                                CategoryType type = ((QuestionElement) layoutConstraint.getElement())
                                        .getCategoryType();
                                if (questionChoiceElements != null || type != null) {

                                    FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
                                    ((QuestionElement) parent).setChoices(null);
                                    ((QuestionElement) parent).setCategoryType(null);
                                    em.persist(parent);

                                    // Save QuestionChoiceElement with their QuestionElement parent(saved above)
                                    if (questionChoiceElements != null) {
                                        for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                            if (questionChoiceElement != null) {
                                                questionChoiceElement.setId(null);
                                                questionChoiceElement
                                                        .setParentQuestion((QuestionElement) parent);
                                                CategoryElement categoryElement = questionChoiceElement
                                                        .getCategoryElement();
                                                if (categoryElement != null) {
                                                    questionChoiceElement.setCategoryElement(null);

                                                    em.persist(questionChoiceElement);
                                                    saveOrgUnitModelCategoryElement(categoryElement, em);
                                                    questionChoiceElement.setCategoryElement(categoryElement);
                                                    em.merge(questionChoiceElement);
                                                } else {
                                                    em.persist(questionChoiceElement);
                                                }
                                            }
                                        }
                                        // Set saved QuestionChoiceElement to QuestionElement parent and update it
                                        ((QuestionElement) parent).setChoices(questionChoiceElements);
                                    }

                                    // Save the Category type of QuestionElement parent(saved above)
                                    if (type != null) {
                                        if (em.find(CategoryType.class, type.getId()) == null) {
                                            List<CategoryElement> typeElements = type.getElements();
                                            if (typeElements != null) {
                                                type.setElements(null);
                                                em.merge(type);
                                                for (CategoryElement element : typeElements) {
                                                    if (em.find(CategoryElement.class,
                                                            element.getId()) == null) {
                                                        element.setParentType(type);
                                                        saveOrgUnitModelCategoryElement(element, em);
                                                    }
                                                }
                                                type.setElements(typeElements);
                                                em.merge(type);
                                            }
                                        }
                                        //Set the saved CategoryType to QuestionElement parent and update it
                                        ((QuestionElement) parent).setCategoryType(type);
                                    }
                                    //Update the QuestionElement parent 
                                    em.merge(parent);
                                } else {
                                    em.persist(layoutConstraint.getElement());
                                }
                            } else {
                                em.persist(layoutConstraint.getElement());
                            }
                        }
                    }
                }
            }
        }
    }
    // OrgUnitModel --> Detail --> Layout --> Groups --> Constraints
    if (orgUnitModel.getDetails() != null && orgUnitModel.getDetails().getLayout() != null) {
        List<LayoutGroup> detailLayoutGroups = orgUnitModel.getDetails().getLayout().getGroups();
        if (detailLayoutGroups != null) {
            for (LayoutGroup layoutGroup : detailLayoutGroups) {
                List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints();
                if (layoutConstraints != null) {
                    for (LayoutConstraint layoutConstraint : layoutConstraints) {
                        if (layoutConstraint.getElement() != null) {
                            if (layoutConstraint.getElement() instanceof QuestionElement) {
                                List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
                                        .getElement()).getChoices();
                                CategoryType type = ((QuestionElement) layoutConstraint.getElement())
                                        .getCategoryType();
                                if (questionChoiceElements != null || type != null) {

                                    FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
                                    ((QuestionElement) parent).setChoices(null);
                                    ((QuestionElement) parent).setCategoryType(null);
                                    em.persist(parent);

                                    // Save QuestionChoiceElement with their QuestionElement parent(saved above)
                                    if (questionChoiceElements != null) {
                                        for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                            if (questionChoiceElement != null) {
                                                questionChoiceElement.setId(null);
                                                questionChoiceElement
                                                        .setParentQuestion((QuestionElement) parent);
                                                CategoryElement categoryElement = questionChoiceElement
                                                        .getCategoryElement();
                                                if (categoryElement != null) {
                                                    questionChoiceElement.setCategoryElement(null);

                                                    em.persist(questionChoiceElement);
                                                    saveOrgUnitModelCategoryElement(categoryElement, em);
                                                    questionChoiceElement.setCategoryElement(categoryElement);
                                                    em.merge(questionChoiceElement);
                                                } else {
                                                    em.persist(questionChoiceElement);
                                                }
                                            }
                                        }
                                        // Set saved QuestionChoiceElement to QuestionElement parent and update it
                                        ((QuestionElement) parent).setChoices(questionChoiceElements);
                                    }

                                    // Save the Category type of QuestionElement parent(saved above)
                                    if (type != null) {
                                        if (em.find(CategoryType.class, type.getId()) == null) {
                                            List<CategoryElement> typeElements = type.getElements();
                                            if (typeElements != null) {
                                                type.setElements(null);
                                                em.merge(type);
                                                for (CategoryElement element : typeElements) {
                                                    if (em.find(CategoryElement.class,
                                                            element.getId()) == null) {
                                                        element.setParentType(type);
                                                        saveOrgUnitModelCategoryElement(element, em);
                                                    }
                                                }
                                                type.setElements(typeElements);
                                                em.merge(type);
                                            }
                                        }
                                        //Set the saved CategoryType to QuestionElement parent and update it
                                        ((QuestionElement) parent).setCategoryType(type);
                                    }
                                    //Update the QuestionElement parent 
                                    em.merge(parent);
                                } else {
                                    em.persist(layoutConstraint.getElement());
                                }
                            } else {
                                em.persist(layoutConstraint.getElement());
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Find all running jobs on this service and set them to RESET or CANCELED.
 * //  w  ww.j  a v  a2  s.com
 * @param serviceType
 *          the service type
 * @param baseUrl
 *          the base url
 * @throws ServiceRegistryException
 *           if there is a problem communicating with the jobs database
 */
private void cleanRunningJobs(String serviceType, String baseUrl) throws ServiceRegistryException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query query = em.createNamedQuery("Job.processinghost.status");
        query.setParameter("status", Status.RUNNING);
        query.setParameter("host", baseUrl);
        query.setParameter("serviceType", serviceType);
        @SuppressWarnings("unchecked")
        List<JobJpaImpl> unregisteredJobs = query.getResultList();
        for (JobJpaImpl job : unregisteredJobs) {
            if (job.isDispatchable()) {
                em.refresh(job);
                // If this job has already been treated
                if (Status.CANCELED.equals(job.getStatus()) || Status.RESTART.equals(job.getStatus()))
                    continue;
                if (job.getRootJob() != null && Status.PAUSED.equals(job.getRootJob().getStatus())) {
                    JobJpaImpl rootJob = job.getRootJob();
                    cancelAllChildren(rootJob, em);
                    rootJob.setStatus(Status.RESTART);
                    rootJob.setOperation(START_OPERATION);
                    em.merge(rootJob);
                    continue;
                }

                logger.info("Marking child jobs from job {} as canceled", job);
                cancelAllChildren(job, em);
                logger.info("Rescheduling lost job {}", job);
                job.setStatus(Status.RESTART);
                job.setProcessorServiceRegistration(null);
            } else {
                logger.info("Marking lost job {} as failed", job);
                job.setStatus(Status.FAILED);
            }
            em.merge(job);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.sigmah.server.dao.impl.FileHibernateDAO.java

/**
 * Saves a new file./*from w ww  .j  a  v  a 2 s  . c  o m*/
 * 
 * @param properties
 *          The properties map of the uploaded file (see {@link FileUploadUtils}).
 * @param physicalName
 *          The uploaded file content.
 * @param size
 *          Size of the uploaded file.
 * @param authorId
 *          The author id.
 * @return The id of the just saved file.
 * @throws IOException
 */
@Transactional
protected Integer saveNewFile(Map<String, String> properties, String physicalName, int size, int authorId)
        throws IOException {

    final EntityManager em = em();

    LOGGER.debug("[saveNewFile] New file.");

    // --------------------------------------------------------------------
    // STEP 1 : saves the file.
    // --------------------------------------------------------------------
    LOGGER.debug("[saveNewFile] Saves the new file.");
    final File file = new File();

    // Gets the details of the name of the file.
    final String fullName = ValueResultUtils.normalizeFileName(properties.get(FileUploadUtils.DOCUMENT_NAME));
    final int index = fullName.indexOf('.');

    final String name = index > 0 ? fullName.substring(0, index) : fullName;
    final String extension = index > 0 && index < fullName.length() ? fullName.substring(index + 1) : null;

    file.setName(name);

    // Creates and adds the new version.
    file.addVersion(createVersion(1, name, extension, authorId, physicalName, size));

    em.persist(file);

    // --------------------------------------------------------------------
    // STEP 2 : gets the current value for this list of files.
    // --------------------------------------------------------------------

    // Element id.
    final int elementId = ClientUtils.asInt(properties.get(FileUploadUtils.DOCUMENT_FLEXIBLE_ELEMENT), 0);

    // Project id.
    final int projectId = ClientUtils.asInt(properties.get(FileUploadUtils.DOCUMENT_PROJECT), 0);

    // Retrieving the current value
    final TypedQuery<Value> query = em.createQuery(
            "SELECT v FROM Value v WHERE v.containerId = :projectId and v.element.id = :elementId",
            Value.class);
    query.setParameter("projectId", projectId);
    query.setParameter("elementId", elementId);

    Value currentValue = null;

    try {
        currentValue = query.getSingleResult();
    } catch (NoResultException nre) {
        // No current value
    }

    // --------------------------------------------------------------------
    // STEP 3 : creates or updates the value with the new file id.
    // --------------------------------------------------------------------

    // The value already exists, must update it.
    if (currentValue != null) {
        currentValue.setLastModificationAction('U');

        // Sets the value (adds a new file id).
        currentValue.setValue(currentValue.getValue() + ValueResultUtils.DEFAULT_VALUE_SEPARATOR
                + String.valueOf(file.getId()));
    }
    // The value for this list of files doesn't exist already, must
    // create it.
    else {
        currentValue = new Value();

        // Creation of the value
        currentValue.setLastModificationAction('C');

        // Parent element
        final FlexibleElement element = em.find(FlexibleElement.class, elementId);
        currentValue.setElement(element);

        // Container
        currentValue.setContainerId(projectId);

        // Sets the value (one file id).
        currentValue.setValue(String.valueOf(file.getId()));
    }

    // Modifier
    final User user = em.find(User.class, authorId);
    currentValue.setLastModificationUser(user);

    // Last update date
    currentValue.setLastModificationDate(new Date());

    // Saves or updates the new value.
    em.merge(currentValue);

    return file.getId();
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public String replaceFile(String fileClass, String fileNameField, String fileStorageField, String fileName,
        FileItem fileItem, String existingId) throws PersistenceException {
    String idField = getIdFieldFromFileStorageClass(fileClass);
    boolean error = false;
    TransactionContext tc = null;/*from  w ww. ja  v a 2 s.c o  m*/
    Object id = null;
    PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(fileClass);

    try {
        id = getFileId(existingId, idField, pds);
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Object o;
        Class<?> clazz = Class.forName(fileClass);
        o = em.find(clazz, id);
        for (PropertyDescriptor pd : pds) {
            if (fileNameField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileName);
            } else if (fileStorageField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileItem.get());
            }
        }
        em.merge(o);

        tx.commit();
        //idsByClassName.get(fileClass).iterator().next().getReadMethod().invoke(o, new Object[0]);
    } catch (Exception e) {
        error = true;
        logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
        try {
            if (tc != null)
                tc.rollback();
        } catch (Exception ee) {
        }
    } finally {
        if (tc != null) {
            if (!error)
                close(tc);
            else
                tc.close();
        }
    }
    if (error) {
        try {
            tc = createTransactionalContext();
            EntityManager em = tc.getEm();
            ITransaction tx = tc.getTx();
            tx.begin();
            Class<?> clazz = Class.forName(fileClass);
            em.createQuery("delete from " + fileClass + " o where o." + idField + " = :id")
                    .setParameter("id", id).executeUpdate();
            Object newDoc = clazz.newInstance();
            for (PropertyDescriptor pd : pds) {
                if (fileNameField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileName);
                } else if (fileStorageField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileItem.get());
                }
            }
            em.persist(newDoc);
            tx.commit();
            for (PropertyDescriptor pd : pds) {
                if (idField.equals(pd.getName())) {
                    existingId = pd.getReadMethod().invoke(newDoc, new String[0]).toString();
                    break;
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
            try {
                if (tc != null)
                    tc.rollback();
            } catch (Exception ee) {
            }
            throw new PersistenceException(e.getMessage(), e);
        } finally {
            if (tc != null)
                close(tc);
        }
    }

    return existingId;
}

From source file:org.sigmah.server.servlet.exporter.models.ProjectModelHandler.java

private void saveLayoutGroups(final List<LayoutGroup> layoutGroups, EntityManager em,
        HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, User user) {

    final HashSet<Integer> reportModelsId = new HashSet<Integer>();

    if (layoutGroups != null) {
        for (LayoutGroup layoutGroup : layoutGroups) {

            final List<LayoutConstraint> layoutConstraints;
            if (layoutGroup != null)
                layoutConstraints = layoutGroup.getConstraints();
            else//from w  ww.j  a  v  a  2  s. co  m
                layoutConstraints = null;

            if (layoutConstraints != null) {
                // Iterating over the constraints
                for (LayoutConstraint layoutConstraint : layoutConstraints) {
                    if (layoutConstraint != null && layoutConstraint.getElement() != null) {
                        final FlexibleElement element = layoutConstraint.getElement();

                        // Do not persist an element twice.
                        if (em.contains(element)) {
                            continue;
                        }

                        // Initialize export flags of flexible element
                        element.initializeExportFlags();

                        // If the current element is a QuestionElement
                        if (element instanceof QuestionElement) {
                            final QuestionElement questionElement = (QuestionElement) element;
                            List<QuestionChoiceElement> questionChoiceElements = questionElement.getChoices();
                            CategoryType type = questionElement.getCategoryType();
                            if (questionChoiceElements != null || type != null) {

                                questionElement.setChoices(null);
                                questionElement.setCategoryType(null);
                                em.persist(questionElement);

                                // Save QuestionChoiceElement with their
                                // QuestionElement parent(saved above)
                                if (questionChoiceElements != null) {
                                    for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                        if (questionChoiceElement != null) {
                                            questionChoiceElement.setId(null);
                                            questionChoiceElement.setParentQuestion(questionElement);
                                            CategoryElement categoryElement = questionChoiceElement
                                                    .getCategoryElement();
                                            if (categoryElement != null) {
                                                questionChoiceElement.setCategoryElement(null);

                                                em.persist(questionChoiceElement);
                                                saveProjectModelCategoryElement(categoryElement, em,
                                                        modelesReset, modelesImport);
                                                questionChoiceElement.setCategoryElement(categoryElement);
                                                em.merge(questionChoiceElement);
                                            } else {
                                                em.persist(questionChoiceElement);
                                            }
                                        }
                                    }
                                    // Set saved QuestionChoiceElement to
                                    // QuestionElement parent and update it
                                    questionElement.setChoices(questionChoiceElements);
                                }

                                // Save the Category type of QuestionElement
                                // parent(saved above)
                                if (type != null) {
                                    if (em.find(CategoryType.class, type.getId()) == null) {
                                        List<CategoryElement> typeElements = type.getElements();
                                        if (typeElements != null) {
                                            type.setElements(null);
                                            em.merge(type);
                                            for (CategoryElement categoryElement : typeElements) {
                                                if (em.find(CategoryElement.class,
                                                        categoryElement.getId()) == null) {
                                                    categoryElement.setParentType(type);
                                                    saveProjectModelCategoryElement(categoryElement, em,
                                                            modelesReset, modelesImport);
                                                }
                                            }
                                            type.setElements(typeElements);
                                            em.merge(type);
                                        }
                                    }
                                    // Set the saved CategoryType to
                                    // QuestionElement parent and update it
                                    questionElement.setCategoryType(type);
                                }
                                // Update the QuestionElement parent
                                em.merge(questionElement);

                            } else {
                                em.persist(element);
                            }
                        }
                        // Report element
                        else if (element instanceof ReportElement) {
                            final ReportElement reportElement = (ReportElement) element;
                            final ProjectReportModel oldModel = reportElement.getModel();

                            if (oldModel != null) {
                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(user.getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    reportElement.setModel(newModel);
                                    em.persist(reportElement);
                                    reportModelsId.add(reportElement.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    reportElement.setModel(newModel);
                                    em.persist(reportElement);
                                }

                            }

                        }
                        // Reports list element
                        else if (element instanceof ReportListElement) {
                            final ReportListElement reportListElement = (ReportListElement) element;
                            final ProjectReportModel oldModel = reportListElement.getModel();

                            if (oldModel != null) {
                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(user.getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    reportListElement.setModel(newModel);
                                    em.persist(reportListElement);
                                    reportModelsId.add(reportListElement.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    reportListElement.setModel(newModel);
                                    em.persist(reportListElement);
                                }
                            }
                        }
                        // Budget element
                        else if (element instanceof BudgetElement) {
                            final BudgetElement budgetElement = (BudgetElement) element;

                            final List<BudgetSubField> subFields = budgetElement.getBudgetSubFields();
                            final BudgetSubField ratioDividend = budgetElement.getRatioDividend();
                            final BudgetSubField ratioDivisor = budgetElement.getRatioDivisor();

                            budgetElement.setBudgetSubFields(null);
                            budgetElement.setRatioDividend(null);
                            budgetElement.setRatioDivisor(null);

                            em.persist(budgetElement);

                            final ArrayList<BudgetSubField> allSubFields = new ArrayList<BudgetSubField>(
                                    subFields);
                            allSubFields.add(ratioDividend);
                            allSubFields.add(ratioDivisor);

                            for (final BudgetSubField subField : allSubFields) {
                                subField.setBudgetElement(budgetElement);
                                em.persist(budgetElement);
                            }
                            budgetElement.setBudgetSubFields(subFields);
                            budgetElement.setRatioDividend(ratioDividend);
                            budgetElement.setRatioDivisor(ratioDivisor);
                            em.merge(budgetElement);
                        }
                        // Others elements
                        else {
                            em.persist(layoutConstraint.getElement());
                        }
                    }
                }
            }
        }
    }

}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectModelHandler.java

private void saveLayoutGroups(final List<LayoutGroup> layoutGroups, EntityManager em,
        HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, Authentication authentication) {

    final HashSet<Integer> reportModelsId = new HashSet<Integer>();

    if (layoutGroups != null) {
        for (LayoutGroup layoutGroup : layoutGroups) {

            final List<LayoutConstraint> layoutConstraints;
            if (layoutGroup != null)
                layoutConstraints = layoutGroup.getConstraints();
            else/*  w  w w . j a v  a2  s  . com*/
                layoutConstraints = null;

            if (layoutConstraints != null) {
                // Iterating over the constraints
                for (LayoutConstraint layoutConstraint : layoutConstraints) {
                    if (layoutConstraint != null && layoutConstraint.getElement() != null) {

                        // Do not persist an element twice.
                        if (em.contains(layoutConstraint.getElement())) {
                            continue;
                        }

                        //Initialize export flags of flexible element
                        layoutConstraint.getElement().initializeExportFlags();

                        // If the current element is a QuestionElement
                        if (layoutConstraint.getElement() instanceof QuestionElement) {
                            List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
                                    .getElement()).getChoices();
                            CategoryType type = ((QuestionElement) layoutConstraint.getElement())
                                    .getCategoryType();
                            if (questionChoiceElements != null || type != null) {

                                FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
                                ((QuestionElement) parent).setChoices(null);
                                ((QuestionElement) parent).setCategoryType(null);
                                em.persist(parent);

                                // Save QuestionChoiceElement with their
                                // QuestionElement parent(saved above)
                                if (questionChoiceElements != null) {
                                    for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
                                        if (questionChoiceElement != null) {
                                            questionChoiceElement.setId(null);
                                            questionChoiceElement.setParentQuestion((QuestionElement) parent);
                                            CategoryElement categoryElement = questionChoiceElement
                                                    .getCategoryElement();
                                            if (categoryElement != null) {
                                                questionChoiceElement.setCategoryElement(null);

                                                em.persist(questionChoiceElement);
                                                saveProjectModelCategoryElement(categoryElement, em,
                                                        modelesReset, modelesImport);
                                                questionChoiceElement.setCategoryElement(categoryElement);
                                                em.merge(questionChoiceElement);
                                            } else {
                                                em.persist(questionChoiceElement);
                                            }
                                        }
                                    }
                                    // Set saved QuestionChoiceElement to
                                    // QuestionElement parent and update it
                                    ((QuestionElement) parent).setChoices(questionChoiceElements);
                                }

                                // Save the Category type of QuestionElement
                                // parent(saved above)
                                if (type != null) {
                                    if (em.find(CategoryType.class, type.getId()) == null) {
                                        List<CategoryElement> typeElements = type.getElements();
                                        if (typeElements != null) {
                                            type.setElements(null);
                                            em.merge(type);
                                            for (CategoryElement element : typeElements) {
                                                if (em.find(CategoryElement.class, element.getId()) == null) {
                                                    element.setParentType(type);
                                                    saveProjectModelCategoryElement(element, em, modelesReset,
                                                            modelesImport);
                                                }
                                            }
                                            type.setElements(typeElements);
                                            em.merge(type);
                                        }
                                    }
                                    // Set the saved CategoryType to
                                    // QuestionElement parent and update it
                                    ((QuestionElement) parent).setCategoryType(type);
                                }
                                // Update the QuestionElement parent
                                em.merge(parent);
                            } else {
                                em.persist(layoutConstraint.getElement());
                            }
                        }
                        // Report element
                        else if (layoutConstraint.getElement() instanceof ReportElement) {

                            final ReportElement element = (ReportElement) layoutConstraint.getElement();
                            final ProjectReportModel oldModel = element.getModel();

                            if (oldModel != null) {

                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(authentication.getUser().getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    element.setModel(newModel);
                                    em.persist(element);
                                    reportModelsId.add(element.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    element.setModel(newModel);
                                    em.persist(element);
                                }

                            }

                        }
                        // Reports list element
                        else if (layoutConstraint.getElement() instanceof ReportListElement) {

                            final ReportListElement element = (ReportListElement) layoutConstraint.getElement();
                            final ProjectReportModel oldModel = element.getModel();

                            if (oldModel != null) {

                                final int oldModelId = oldModel.getId();
                                final ProjectReportModel newModel;

                                if (!reportModelsId.contains(oldModelId)) {
                                    oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>());
                                    oldModel.setOrganization(authentication.getUser().getOrganization());
                                    newModel = oldModel;
                                    ProjectReportModelHandler.saveProjectReportModelElement(newModel, em);
                                    em.persist(newModel);
                                    element.setModel(newModel);
                                    em.persist(element);
                                    reportModelsId.add(element.getModel().getId());
                                }
                                // If the report model has been already
                                // saved, it is re-used.
                                else {
                                    newModel = em.find(ProjectReportModel.class, oldModelId);
                                    element.setModel(newModel);
                                    em.persist(element);
                                }

                            }

                        }
                        // Others elements
                        else {
                            em.persist(layoutConstraint.getElement());
                        }
                    }
                }
            }
        }
    }

}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.RuleFieldPersistenceProvider.java

protected boolean updateQuantityRule(EntityManager em, DataDTOToMVELTranslator translator, String entityKey,
        String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList,
        Class<?> memberType, Object parent, String mappedBy, Property property) {
    boolean dirty = false;
    if (!StringUtils.isEmpty(jsonPropertyValue)) {
        //avoid lazy init exception on the criteria list for criteria created during an add
        criteriaList.size();/*  ww w  .  j  a va  2  s. co  m*/
        DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue);
        if (dw != null && StringUtils.isEmpty(dw.getError())) {
            List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>();
            for (DataDTO dto : dw.getData()) {
                if (dto.getId() != null && !CollectionUtils.isEmpty(criteriaList)) {
                    checkId: {
                        //updates are comprehensive, even data that was not changed
                        //is submitted here
                        //Update Existing Criteria
                        for (QuantityBasedRule quantityBasedRule : criteriaList) {
                            //make compatible with enterprise module
                            Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
                            boolean isMatch = dto.getId().equals(id)
                                    || dto.getId().equals(quantityBasedRule.getId());
                            if (isMatch) {
                                String mvel;
                                //don't update if the data has not changed
                                if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) {
                                    dirty = true;
                                }
                                try {
                                    mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator,
                                            entityKey, dto, fieldService);
                                    if (!quantityBasedRule.getMatchRule().equals(mvel)) {
                                        dirty = true;
                                    }
                                } catch (MVELTranslationException e) {
                                    throw new RuntimeException(e);
                                }
                                if (!dirty && extensionManager != null) {
                                    ExtensionResultHolder<Boolean> resultHolder = new ExtensionResultHolder<Boolean>();
                                    ExtensionResultStatusType result = extensionManager.getProxy()
                                            .establishDirtyState(quantityBasedRule, resultHolder);
                                    if (ExtensionResultStatusType.NOT_HANDLED != result
                                            && resultHolder.getResult() != null) {
                                        dirty = resultHolder.getResult();
                                    }
                                }
                                if (dirty) {
                                    quantityBasedRule.setQuantity(dto.getQuantity());
                                    quantityBasedRule.setMatchRule(mvel);
                                    quantityBasedRule = em.merge(quantityBasedRule);
                                }
                                updatedRules.add(quantityBasedRule);
                                break checkId;
                            }
                        }
                        throw new IllegalArgumentException("Unable to update the rule of type ("
                                + memberType.getName() + ") because an update was requested for id ("
                                + dto.getId() + "), which does not exist.");
                    }
                } else {
                    //Create a new Criteria
                    QuantityBasedRule quantityBasedRule;
                    try {
                        quantityBasedRule = (QuantityBasedRule) memberType.newInstance();
                        quantityBasedRule.setQuantity(dto.getQuantity());
                        quantityBasedRule.setMatchRule(ruleFieldExtractionUtility
                                .convertDTOToMvelString(translator, entityKey, dto, fieldService));
                        if (StringUtils.isEmpty(quantityBasedRule.getMatchRule())
                                && !StringUtils.isEmpty(dw.getRawMvel())) {
                            quantityBasedRule.setMatchRule(dw.getRawMvel());
                        }
                        PropertyUtils.setNestedProperty(quantityBasedRule, mappedBy, parent);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    em.persist(quantityBasedRule);
                    dto.setId(quantityBasedRule.getId());
                    if (extensionManager != null) {
                        ExtensionResultHolder resultHolder = new ExtensionResultHolder();
                        extensionManager.getProxy().postAdd(quantityBasedRule, resultHolder);
                        if (resultHolder.getResult() != null) {
                            quantityBasedRule = (QuantityBasedRule) resultHolder.getResult();
                        }
                    }
                    updatedRules.add(quantityBasedRule);
                    dirty = true;
                }
            }
            //if an item was not included in the comprehensive submit from the client, we can assume that the
            //listing was deleted, so we remove it here.
            Iterator<QuantityBasedRule> itr = criteriaList.iterator();
            while (itr.hasNext()) {
                checkForRemove: {
                    QuantityBasedRule original = itr.next();
                    for (QuantityBasedRule quantityBasedRule : updatedRules) {
                        Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
                        boolean isMatch = original.getId().equals(id)
                                || original.getId().equals(quantityBasedRule.getId());
                        if (isMatch) {
                            break checkForRemove;
                        }
                    }
                    em.remove(original);
                    itr.remove();
                    dirty = true;
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json;
            try {
                json = mapper.writeValueAsString(dw);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            property.setValue(json);
        }
    }
    return dirty;
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Sets the online status of a service registration.
 * // ww  w . j a v a 2 s  .c o  m
 * @param serviceType
 *          The job type
 * @param baseUrl
 *          the host URL
 * @param online
 *          whether the service is online or off
 * @param jobProducer
 *          whether this service produces jobs for long running operations
 * @return the service registration
 */
protected ServiceRegistration setOnlineStatus(String serviceType, String baseUrl, String path, boolean online,
        Boolean jobProducer) throws ServiceRegistryException {
    if (isBlank(serviceType) || isBlank(baseUrl)) {
        throw new IllegalArgumentException("serviceType and baseUrl must not be blank");
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        HostRegistrationJpaImpl hostRegistration = fetchHostRegistration(em, baseUrl);
        if (hostRegistration == null) {
            throw new IllegalStateException(
                    "A service registration can not be updated when it has no associated host registration");
        }
        ServiceRegistrationJpaImpl registration = getServiceRegistration(em, serviceType, baseUrl);
        if (registration == null) {
            if (isBlank(path)) {
                // we can not create a new registration without a path
                throw new IllegalArgumentException("path must not be blank when registering new services");
            }
            if (jobProducer == null) { // if we are not provided a value, consider it to be false
                registration = new ServiceRegistrationJpaImpl(hostRegistration, serviceType, path, false);

            } else {
                registration = new ServiceRegistrationJpaImpl(hostRegistration, serviceType, path, jobProducer);
            }
            em.persist(registration);
        } else {
            if (StringUtils.isNotBlank(path))
                registration.setPath(path);
            registration.setOnline(online);
            if (jobProducer != null) { // if we are not provided a value, don't update the persistent value
                registration.setJobProducer(jobProducer);
            }
            em.merge(registration);
        }
        tx.commit();
        hostsStatistics.updateHost(hostRegistration);
        servicesStatistics.updateService(registration);
        return registration;
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:op.care.values.PnlValues.java

private JPanel createContentPanel4Year(final ResValueTypes vtype, final int year) {
    final String keyYears = vtype.getID() + ".xtypes." + Integer.toString(year) + ".year";

    java.util.List<ResValue> myValues;
    synchronized (mapType2Values) {
        if (!mapType2Values.containsKey(keyYears)) {
            mapType2Values.put(keyYears, ResValueTools.getResValues(resident, vtype, year));
        }/*from  w  w w.j a  va 2  s .c  o m*/
        if (mapType2Values.get(keyYears).isEmpty()) {
            JLabel lbl = new JLabel(SYSTools.xx("misc.msg.novalue"));
            JPanel pnl = new JPanel();
            pnl.add(lbl);
            return pnl;
        }
        myValues = mapType2Values.get(keyYears);
    }

    JPanel pnlYear = new JPanel(new VerticalLayout());

    pnlYear.setOpaque(false);

    for (final ResValue resValue : myValues) {
        String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"200\" align=\"left\">"
                + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT).format(resValue.getPit())
                + " [" + resValue.getID() + "]</td>" + "<td width=\"340\" align=\"left\">"
                + ResValueTools.getValueAsHTML(resValue) + "</td>" + "<td width=\"200\" align=\"left\">"
                + resValue.getUser().getFullname() + "</td>" + "</tr>" + "</table>" + "</html>";

        final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null);

        pnlTitle.getMain().setBackground(GUITools.blend(vtype.getColor(), Color.WHITE, 0.1f));
        pnlTitle.getMain().setOpaque(true);

        if (resValue.isObsolete()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22eraser));
        }
        if (resValue.isReplacement()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22edited));
        }
        if (!resValue.getText().trim().isEmpty()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22info));
        }
        if (pnlTitle.getAdditionalIconPanel().getComponentCount() > 0) {
            pnlTitle.getButton().addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    GUITools.showPopup(
                            GUITools.getHTMLPopup(pnlTitle.getButton(), ResValueTools.getInfoAsHTML(resValue)),
                            SwingConstants.NORTH);
                }
            });
        }

        if (!resValue.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(
                    Integer.toString(resValue.getAttachedFilesConnections().size()), SYSConst.icon22greenStar);
            btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
            btnFiles.setForeground(Color.BLUE);
            btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnFiles.setFont(SYSConst.ARIAL18BOLD);
            btnFiles.setPressedIcon(SYSConst.icon22Pressed);
            btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
            btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnFiles.setContentAreaFilled(false);
            btnFiles.setBorder(null);

            btnFiles.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgFiles(resValue, new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final ResValue myValue = em.find(ResValue.class, resValue.getID());
                            em.close();

                            synchronized (mapType2Values) {
                                mapType2Values.get(keyYears).remove(resValue);
                                mapType2Values.get(keyYears).add(myValue);
                                Collections.sort(mapType2Values.get(keyYears));
                            }

                            createCP4Year(vtype, year);
                            buildPanel();
                        }
                    });
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            pnlTitle.getRight().add(btnFiles);
        }

        if (!resValue.getAttachedProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(
                    Integer.toString(resValue.getAttachedProcessConnections().size()), SYSConst.icon22redStar);
            btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
            btnProcess.setForeground(Color.YELLOW);
            btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnProcess.setFont(SYSConst.ARIAL18BOLD);
            btnProcess.setPressedIcon(SYSConst.icon22Pressed);
            btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
            btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnProcess.setContentAreaFilled(false);
            btnProcess.setBorder(null);
            btnProcess.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgProcessAssign(resValue, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o == null) {
                                return;
                            }
                            Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                            ArrayList<QProcess> assigned = result.getFirst();
                            ArrayList<QProcess> unassigned = result.getSecond();

                            EntityManager em = OPDE.createEM();

                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                ResValue myValue = em.merge(resValue);
                                em.lock(myValue, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSVAL2PROCESS> attached = new ArrayList<SYSVAL2PROCESS>(
                                        resValue.getAttachedProcessConnections());
                                for (SYSVAL2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getResValue().getAttachedProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.getID(),
                                                PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                                linkObject.getQProcess()));
                                        em.remove(linkObject);
                                    }
                                }
                                attached.clear();

                                for (QProcess qProcess : assigned) {
                                    java.util.List<QProcessElement> listElements = qProcess.getElements();
                                    if (!listElements.contains(myValue)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSVAL2PROCESS myLinkObject = em
                                                .merge(new SYSVAL2PROCESS(myQProcess, myValue));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedResValueConnections().add(myLinkObject);
                                        myValue.getAttachedProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                synchronized (mapType2Values) {
                                    mapType2Values.get(keyYears).remove(resValue);
                                    mapType2Values.get(keyYears).add(myValue);
                                    Collections.sort(mapType2Values.get(keyYears));
                                }
                                createCP4Year(vtype, year);

                                buildPanel();

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (RollbackException ole) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    });
                }
            });
            btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
            pnlTitle.getRight().add(btnProcess);
        }
        /***
         *      __  __
         *     |  \/  | ___ _ __  _   _
         *     | |\/| |/ _ \ '_ \| | | |
         *     | |  | |  __/ | | | |_| |
         *     |_|  |_|\___|_| |_|\__,_|
         *
         */
        final JButton btnMenu = new JButton(SYSConst.icon22menu);
        btnMenu.setPressedIcon(SYSConst.icon22Pressed);
        btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
        btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnMenu.setContentAreaFilled(false);
        btnMenu.setBorder(null);
        btnMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JidePopup popup = new JidePopup();
                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnMenu);
                popup.removeExcludedComponent(btnMenu);
                JPanel pnl = getMenu(resValue);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });
        btnMenu.setEnabled(!resValue.isObsolete());
        pnlTitle.getRight().add(btnMenu);

        pnlYear.add(pnlTitle.getMain());
        synchronized (linemap) {
            linemap.put(resValue, pnlTitle.getMain());
        }
    }
    return pnlYear;
}