Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward resequence(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Throwable {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;

    JSONEscapeObject jsonResult = new JSONEscapeObject();
    jsonResult.put("status", Constants.WEBSERVICE_STATUS_SUCCESS);

    MessageResources resources = this.getResources(request);
    Vector<JSONEscapeObject> errors = new Vector<JSONEscapeObject>();
    String seqNums[] = form.getSeqNums();
    if (seqNums != null) {
        String customAttribDetailIds[] = form.getCustomAttribDetailIds();
        for (int i = 0; i < seqNums.length; i++) {
            if (!Format.isInt(seqNums[i])) {
                JSONEscapeObject object = new JSONEscapeObject();
                object.put("customAttribDetailId", customAttribDetailIds[i]);
                object.put("error", resources.getMessage("error.int.invalid"));
                errors.add(object);/*  w  w w .  j a  v  a 2 s  .co m*/
            }
        }
        if (errors.size() > 0) {
            jsonResult.put("validations", errors);
            streamWebService(response, jsonResult.toHtmlString());
            return null;
        }

        for (int i = 0; i < customAttribDetailIds.length; i++) {
            CustomAttributeDetail customAttributeDetail = (CustomAttributeDetail) em
                    .find(CustomAttributeDetail.class, Format.getLong(customAttribDetailIds[i]));
            customAttributeDetail.setSeqNum(Format.getInt(seqNums[i]));
            em.persist(customAttributeDetail);
        }
    }

    streamWebService(response, jsonResult.toHtmlString());
    return null;
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an Annotation/*from w w w  . j av  a2  s. c  o  m*/
 * @param label
 * @param context_creation
 * @param hTMLContent
 * @param access
 * @param representsResource
 * @param status
 * @param added
 * @param annotated
 * @return
 */
public boolean createAnnotation(String label, String context_creation, URI access, URI representsResource,
        AnnotationStatus status, Collection<Resource> added, Collection<Resource> annotated,
        Collection<URI> annotatedURIs, Agent _creator) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        Annotation _annotation = new Annotation();
        _annotation.setContextCreation(context_creation);
        _annotation.setCreation(new Date());
        _annotation.setLabel(label);
        _annotation.setAccess(access);
        _annotation.setRepresentsResource(representsResource);
        _annotation.setStatus(status);
        _annotation.setCreator(_creator);
        //_annotation.setAdded(added);
        //_annotation.setAnnotated(annotated);
        //_annotation.setAnnotatedURIs(annotatedURIs);
        //EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (representsResource.getId() != null) {
                URI _synchro_represents_resource = em.find(URI.class, representsResource.getId());
                if (_synchro_represents_resource != null)
                    _annotation.setRepresentsResource(_synchro_represents_resource);
            }
            if (access.getId() != null) {
                URI _synchro_access = em.find(URI.class, access.getId());
                if (_synchro_access != null)
                    _annotation.setAccess(_synchro_access);
            }
            if (status.getId() != null) {
                AnnotationStatus _synchro_status = em.find(AnnotationStatus.class, status.getId());
                if (_synchro_status != null)
                    _annotation.setStatus(_synchro_status);
            }
            if (_creator != null && _creator.getId() != null) {
                Agent _synchro_agent = em.find(_creator.getClass(), _creator.getId());
                if (_synchro_agent != null)
                    _annotation.setCreator(_synchro_agent);
            }
            Collection<Resource> _synchro_added = new ArrayList<Resource>();
            for (Resource _to_add : added) {
                if (_to_add.getId() != null) {
                    Resource _synchro_to_add = em.find(_to_add.getClass(), _to_add.getId());
                    if (_synchro_to_add != null)
                        _synchro_added.add(_synchro_to_add);
                } else
                    _synchro_added.add(_to_add);
            }
            _annotation.setAdded(_synchro_added);
            Collection<Resource> _synchro_annotated = new ArrayList<Resource>();
            for (Resource _to_annotate : annotated) {
                if (_to_annotate.getId() != null) {
                    Resource _synchro_to_annotate = em.find(_to_annotate.getClass(), _to_annotate.getId());
                    if (_synchro_to_annotate != null)
                        _synchro_annotated.add(_synchro_to_annotate);
                } else
                    _synchro_annotated.add(_to_annotate);
            }
            _annotation.setAnnotated(_synchro_annotated);
            Collection<URI> synchro_annotatedURIs = new ArrayList<URI>();
            for (URI _to_annotate : annotatedURIs) {
                if (_to_annotate.getId() != null) {
                    URI _synchro_to_annotate = em.find(_to_annotate.getClass(), _to_annotate.getId());
                    if (_synchro_to_annotate != null) {
                        //empcher qu'une mme URI soit ajoute plusieurs fois  une mme annotation
                        if (!synchro_annotatedURIs.contains(_synchro_to_annotate))
                            synchro_annotatedURIs.add(_synchro_to_annotate);
                    }
                } else
                    synchro_annotatedURIs.add(_to_annotate);
            }
            _annotation.setAnnotatedURIs(synchro_annotatedURIs);
            em.persist(_annotation);
            tx.commit();
            em.close();
            return true;
        } catch (Exception e) {
            System.out.println(
                    "[CreateAnnotation.createAnnotation] fails to create annotation" + " context creation : "
                            + context_creation + " label : " + label + " cause : " + e.getMessage());
            tx.rollback();
            //em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotation.createAnnotation] unable to persist annotation"
                + " not a valid label : " + label);
        return false;
    }
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Adds client subscription information. This effectively links a server to
 * serverr subscription to clerk/*ww  w.j  a  v  a  2s  . co  m*/
 * Administrative privilege required.
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public ClientSubscriptionInfoDetail saveClientSubscriptionInfo(SaveClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateClientSubscriptionInfo(publisher).validateSaveClientSubscriptionInfo(em, body);

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<org.apache.juddi.api_v3.ClientSubscriptionInfo> apiClientSubscriptionInfoList = body
                .getClientSubscriptionInfo();
        for (org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo : apiClientSubscriptionInfoList) {

            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = new org.apache.juddi.model.ClientSubscriptionInfo();

            MappingApiToModel.mapClientSubscriptionInfo(apiClientSubscriptionInfo, modelClientSubscriptionInfo);

            Object existingUddiEntity = em.find(modelClientSubscriptionInfo.getClass(),
                    modelClientSubscriptionInfo.getSubscriptionKey());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void setJobQueue(int idJob, int idQueue) {
    EntityManager em = null;
    JobInstance ji = null;//from  w w  w .  ja  va  2s .  c  o  m
    Queue q = null;

    try {
        em = getEm();
        q = em.find(Queue.class, idQueue);
    } catch (NoResultException e) {
        closeQuietly(em);
        throw new JqmClientException("Queue does not exist");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("Cannot retrieve queue", e);
    }

    try {
        em.getTransaction().begin();
        ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE);
        if (ji == null || !ji.getState().equals(State.SUBMITTED)) {
            throw new NoResultException();
        }
        ji.setQueue(q);
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmClientException("Job instance does not exist or has already started");
    } catch (Exception e) {
        throw new JqmClientException("could not change the queue of a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

private InputStream getDeliverableContent(Deliverable deliverable) {
    EntityManager em = getEm();
    URL url = null;//w  w w.  jav  a 2s.  c  om
    String dns, protocol;
    int port;

    try {
        History h = em.find(History.class, deliverable.getJobId());
        if (h == null) {
            JobInstance ji = em.find(JobInstance.class, deliverable.getJobId());
            if (ji == null) {
                throw new JqmInvalidRequestException("No ended or running job instance found for this file");
            }
            dns = ji.getNode().getDns();
            port = ji.getNode().getPort();
        } else {
            if (h.getNode() == null) {
                throw new JqmInvalidRequestException("cannot retrieve a file from a deleted node");
            }
            dns = h.getNode().getDns();
            port = h.getNode().getPort();
        }

        protocol = getFileProtocol(em);
    } catch (Exception e) {
        throw new JqmClientException("Could not process request", e);
    } finally {
        closeQuietly(em);
    }

    try {
        url = new URL(protocol + dns + ":" + port + "/ws/simple/file?id=" + deliverable.getRandomId());
        jqmlogger.trace("URL: " + url.toString());
    } catch (MalformedURLException e) {
        throw new JqmClientException("URL is not valid " + url, e);
    }

    return getFile(url.toString());
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void deleteJob(int idJob) {
    jqmlogger.trace("Job status number " + idJob + " will be deleted");
    EntityManager em = null;

    try {/*from w ww.j  ava  2 s. c  o  m*/
        em = getEm();

        // Two transactions against deadlock.
        JobInstance job = em.find(JobInstance.class, idJob);
        em.getTransaction().begin();
        em.refresh(job, LockModeType.PESSIMISTIC_WRITE);
        if (job.getState().equals(State.SUBMITTED)) {
            job.setState(State.CANCELLED);
        }
        em.getTransaction().commit();

        if (!job.getState().equals(State.CANCELLED)) {
            // Job is not in queue anymore - just return.
            return;
        }

        em.getTransaction().begin();
        em.createQuery("DELETE FROM Message WHERE ji = :i").setParameter("i", job.getId()).executeUpdate();
        em.createQuery("DELETE FROM RuntimeParameter WHERE ji = :i").setParameter("i", job.getId())
                .executeUpdate();
        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", job.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException(
                "An attempt was made to delete a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("could not delete a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

public void addPublisherAssertions(AddPublisherAssertions body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//ww w  .j  a  va  2 s  .  c o  m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateAddPublisherAssertions(em, body);

        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = body.getPublisherAssertion();
        for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) {

            org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion();

            MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion);

            org.apache.juddi.model.PublisherAssertion existingPubAssertion = em
                    .find(modelPubAssertion.getClass(), modelPubAssertion.getId());
            boolean persistNewAssertion = true;
            if (existingPubAssertion != null) {
                if (modelPubAssertion.getTmodelKey().equalsIgnoreCase(existingPubAssertion.getTmodelKey())
                        && modelPubAssertion.getKeyName().equalsIgnoreCase(existingPubAssertion.getKeyName())
                        && modelPubAssertion.getKeyValue()
                                .equalsIgnoreCase(existingPubAssertion.getKeyValue())) {
                    // This pub assertion is already been "asserted".  Simply need to set the "check" value on the existing (and persistent) assertion
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByFromKey()))
                        existingPubAssertion.setFromCheck("true");
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByToKey()))
                        existingPubAssertion.setToCheck("true");

                    persistNewAssertion = false;
                } else {
                    // Otherwise, it is a new relationship between these entities.  Remove the old one so the new one can be added.
                    // TODO: the model only seems to allow one assertion per two business (primary key is fromKey and toKey). Spec seems to imply as 
                    // many relationships as desired (the differentiator would be the keyedRef values).
                    em.remove(existingPubAssertion);
                }
            }

            if (persistNewAssertion) {
                org.apache.juddi.model.BusinessEntity beFrom = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey());
                org.apache.juddi.model.BusinessEntity beTo = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey());
                modelPubAssertion.setBusinessEntityByFromKey(beFrom);
                modelPubAssertion.setBusinessEntityByToKey(beTo);

                modelPubAssertion.setFromCheck("false");
                modelPubAssertion.setToCheck("false");

                em.persist(modelPubAssertion);

                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey()))
                    modelPubAssertion.setFromCheck("true");
                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey()))
                    modelPubAssertion.setToCheck("true");
            }

        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

public int restartCrashedJob(int idJob) {
    EntityManager em = null;

    // History and Job ID have the same ID.
    History h = null;/*from www  .j a  v  a2  s .co m*/
    try {
        em = getEm();
        h = em.find(History.class, idJob);
    } catch (NoResultException e) {
        closeQuietly(em);
        throw new JqmClientException(
                "You cannot restart a job that is not done or which was purged from history");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("could not restart a job (internal error)", e);
    }

    if (!h.getState().equals(State.CRASHED)) {
        closeQuietly(em);
        throw new JqmClientException("You cannot restart a job that has not crashed");
    }

    if (!h.getJd().isCanBeRestarted()) {
        closeQuietly(em);
        throw new JqmClientException("This type of job was configured to prevent being restarded");
    }

    try {
        em.getTransaction().begin();
        em.remove(h);
        em.getTransaction().commit();
        return enqueue(getJobRequest(h, em));
    } catch (Exception e) {
        throw new JqmClientException("could not purge & restart a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:op.care.med.inventory.PnlInventory.java

private void txtSucheActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSucheActionPerformed

    JXSearchField search = (JXSearchField) evt.getSource();
    if (!search.getText().isEmpty() && search.getText().matches("\\d*")) {
        // numbers only !
        long id = Long.parseLong(search.getText());
        EntityManager em = OPDE.createEM();
        final MedStock stock = em.find(MedStock.class, id);
        em.close();//ww w .j  a v a  2 s . c o  m

        if (stock != null) {
            final String key = stock.getInventory().getID() + ".xinventory";
            if (!resident.equals(stock.getInventory().getResident())) {
                if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.ARCHIVE, "nursingrecords.info")) {
                    switchResident(stock.getInventory().getResident(), stock.getInventory(), new Closure() {
                        @Override
                        public void execute(Object o) {
                            synchronized (mapKey2ClosedToggleButton) {
                                mapKey2ClosedToggleButton.get(key).setSelected(true);
                            }
                        }
                    });
                } else {
                    OPDE.getDisplayManager().addSubMessage(new DisplayMessage("misc.msg.noarchiveaccess"));
                }

            } else {
                synchronized (mapKey2ClosedToggleButton) {
                    //                    CollapsiblePane myCP = cpMap.get(key);

                    if (cpMap.get(key).isCollapsed()) {
                        try {
                            cpMap.get(key).setCollapsed(false);
                        } catch (PropertyVetoException e) {
                            // bah!
                        }
                    }

                }
            }

        } else {
            OPDE.getDisplayManager().addSubMessage(new DisplayMessage("misc.msg.notfound"));
        }

    }
}

From source file:op.care.nursingprocess.PnlNursingProcess.java

private JPanel createNPPanel(final NursingProcess np) {
    /***//from   w ww.  j  a va  2 s .  c o  m
     *                          _        ____ ____  _  _     _   _ ____
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |   | \ | |  _ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_  |  \| | |_) |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| | |\  |  __/
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_|   |_| \_|_|
     *
     */
    if (!contenPanelMap.containsKey(np)) {
        String title = "<html><table border=\"0\">";

        if (!np.getCommontags().isEmpty()) {
            title += "<tr>" + "    <td colspan=\"2\">"
                    + CommontagsTools.getAsHTML(np.getCommontags(), SYSConst.html_16x16_tagPurple_internal)
                    + "</td>" + "  </tr>";
        }

        title += "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">" + np.getPITAsHTML() + "</td>"
                + "<td width=\"500\" align=\"left\">" + (np.isClosed() ? "<s>" : "") + np.getContentAsHTML()
                + (np.isClosed() ? "</s>" : "") + "</td></tr>";
        title += "</table>" + "</html>";

        DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
        cptitle.getButton().setVerticalTextPosition(SwingConstants.TOP);

        if (!np.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(Integer.toString(np.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) {
                    Closure fileHandleClosure = np.isClosed() ? null : new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final NursingProcess myNP = em.find(NursingProcess.class, np.getID());
                            em.close();
                            // Refresh Display
                            valuecache.get(np.getCategory()).remove(np);
                            contenPanelMap.remove(np);
                            valuecache.get(myNP.getCategory()).add(myNP);
                            Collections.sort(valuecache.get(myNP.getCategory()));

                            createCP4(myNP.getCategory());
                            buildPanel();
                        }
                    };
                    new DlgFiles(np, fileHandleClosure);
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            cptitle.getRight().add(btnFiles);
        }

        if (!np.getAttachedQProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(Integer.toString(np.getAttachedQProcessConnections().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(np, 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);
                                final NursingProcess myNP = em.merge(np);
                                em.lock(myNP, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSNP2PROCESS> attached = new ArrayList<SYSNP2PROCESS>(
                                        myNP.getAttachedQProcessConnections());
                                for (SYSNP2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getNursingProcess().getAttachedQProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.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(myNP)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSNP2PROCESS myLinkObject = em
                                                .merge(new SYSNP2PROCESS(myQProcess, myNP));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedNursingProcessesConnections().add(myLinkObject);
                                        myNP.getAttachedQProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(myNP.getCategory()).add(myNP);
                                Collections.sort(valuecache.get(myNP.getCategory()));

                                createCP4(myNP.getCategory());
                                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();
                                } else {
                                    reloadDisplay();
                                }
                            } 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));
            cptitle.getRight().add(btnProcess);
        }

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.PRINT, internalClassID)) {
            /***
             *      _     _         ____       _       _
             *     | |__ | |_ _ __ |  _ \ _ __(_)_ __ | |_
             *     | '_ \| __| '_ \| |_) | '__| | '_ \| __|
             *     | |_) | |_| | | |  __/| |  | | | | | |_
             *     |_.__/ \__|_| |_|_|   |_|  |_|_| |_|\__|
             *
             */
            JButton btnPrint = new JButton(SYSConst.icon22print2);
            btnPrint.setContentAreaFilled(false);
            btnPrint.setBorder(null);
            btnPrint.setPressedIcon(SYSConst.icon22print2Pressed);
            btnPrint.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnPrint.setAlignmentY(Component.TOP_ALIGNMENT);
            btnPrint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    SYSFilesTools.print(NursingProcessTools.getAsHTML(np, true, true, true, true), true);
                }
            });

            cptitle.getRight().add(btnPrint);
            //                cptitle.getTitleButton().setVerticalTextPosition(SwingConstants.TOP);
        }

        /***
         *      __  __
         *     |  \/  | ___ _ __  _   _
         *     | |\/| |/ _ \ '_ \| | | |
         *     | |  | |  __/ | | | |_| |
         *     |_|  |_|\___|_| |_|\__,_|
         *
         */
        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(np);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });

        btnMenu.setEnabled(!np.isClosed());
        cptitle.getButton().setIcon(getIcon(np));

        cptitle.getRight().add(btnMenu);
        cptitle.getMain().setBackground(getColor(np.getCategory())[SYSConst.light2]);
        cptitle.getMain().setOpaque(true);
        contenPanelMap.put(np, cptitle.getMain());
    }

    return contenPanelMap.get(np);
}