Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

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

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java

public User getUser(String username, String password) {
    EntityManager em = getHibernateEntityManager();
    User user;// ww w  .  j ava 2 s. co  m
    try {
        user = (User) em.createNativeQuery(
                "SELECT * FROM users WHERE username = :usr AND password = SHA2(CONCAT(:pwd,(SELECT salt FROM users WHERE username = :usr)),512)",
                User.class).setParameter("usr", username).setParameter("pwd", password).getSingleResult();
        em.close();
        return user;
    } catch (Exception e) {
        em.close();
        logger.error("Login Failed for " + username + ": " + e.getMessage());
        return null;
    }
}

From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java

public void updateExerciseInstanceUsedHints(ExerciseInstance ei, FlagQuestionHint hint) {
    EntityManager em = getHibernateEntityManager();
    EntityTransaction et = em.getTransaction();
    et.begin();/*from   w w  w .j av  a2 s. c  om*/
    try {
        em.createNativeQuery("INSERT INTO exerciseInstances_flagQuestionHints "
                + "(ExerciseInstance_idExerciseInstance,usedHints_idFlagQuestionHint) " + "VALUES (?,?)")
                .setParameter(1, ei.getIdExerciseInstance()).setParameter(2, hint.getId()).executeUpdate();
        et.commit();
        em.close();
    } catch (Exception e) {
        et.rollback();
        em.close();
        logger.error("Failed adding hint " + hint.getId() + " to exercise instance "
                + ei.getIdExerciseInstance() + " because of: \n" + e.getMessage());
    }

}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

private void initExampleData() throws Exception {
    EntityManager em = emf.createEntityManager();
    try {/*  ww w. j  ava  2s.c  o m*/
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        User player1 = new User("student@busimu.com", "ssssss", "s", User.Type.STUDENT);
        player1.setStatus(User.Status.ACTIVE);
        User player2 = new User("zhangsan@busimu.com", "123456", "", User.Type.STUDENT);
        player2.setStatus(User.Status.ACTIVE);
        User player3 = new User("lisi@busimu.com", "123456", "?", User.Type.STUDENT);
        player3.setStatus(User.Status.ACTIVE);
        User teacher = new User("teacher@busimu.com", "tttttt", "t", User.Type.TEACHER);
        teacher.setStatus(User.Status.ACTIVE);
        em.persist(player1);
        em.persist(player2);
        em.persist(player3);
        em.persist(teacher);

        Campaign campaign = teacher.createCampagin("", Campaign.Type.COURSE);
        SimMarket south = campaign.addMarket("??");
        SimMarket central = campaign.addMarket("?");
        SimMarket north = campaign.addMarket("?");
        SimMarket east = campaign.addMarket("?");
        SimMarket west = campaign.addMarket("");
        SimCorporation ibm = south.addCorporation("IBM", new Color(128, 128, 255));
        SimCorporation ericsson = south.addCorporation("Ericsson", Color.BLUE);
        SimCorporation oracle = south.addCorporation("Oracle", Color.RED);
        for (int i = 0; i < 8; i++) {
            campaign.addRound();
        }

        player2.addCampaign(campaign);
        player3.addCampaign(campaign);
        em.persist(campaign);

        Team t1 = new Team("anoym1");
        Team t2 = new Team("anoym2");
        Team t3 = new Team("anoym3");
        t1.addCorporation(ibm);
        t2.addCorporation(ericsson);
        t3.addCorporation(oracle);
        em.persist(t1);
        em.persist(t2);
        em.persist(t3);

        Campaign runningCampaign = teacher.createCampagin("", Campaign.Type.COURSE);
        SimMarket m1 = runningCampaign.addMarket("");
        SimMarket m2 = runningCampaign.addMarket("");
        SimMarket m3 = runningCampaign.addMarket("");
        SimCorporation corp1 = m1.addCorporation("", Color.ORANGE);
        for (int i = 0; i < 3; i++) {
            runningCampaign.addRound();
        }
        player1.addCampaign(runningCampaign);
        player2.addCampaign(runningCampaign);
        player3.addCampaign(runningCampaign);
        runningCampaign.setStatus(Campaign.Status.ONGOING);

        Team t11 = new Team("anoym11");
        t11.addCorporation(corp1);
        t11.addUser(player1);
        t11.addUser(player2);
        t11.addUser(player3);
        em.persist(t11);

        tx.commit();
    } finally {
        em.close();
    }
}

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

@Override
public void close(EntityManager em) {
    emByThread.remove();
    em.close();
}

From source file:gov.osti.services.Metadata.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from   w w w . ja va 2 s  . c o  m*/
@Path("/reindex")
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response reindex() throws IOException {
    EntityManager em = DoeServletContextListener.createEntityManager();

    try {
        TypedQuery<MetadataSnapshot> query = em
                .createNamedQuery("MetadataSnapshot.findAllByStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);
        List<MetadataSnapshot> results = query.getResultList();
        int records = 0;

        for (MetadataSnapshot amd : results) {
            DOECodeMetadata md = DOECodeMetadata.parseJson(new StringReader(amd.getJson()));

            sendToIndex(em, md);
            ++records;
        }

        return Response.ok()
                .entity(mapper.createObjectNode().put("indexed", String.valueOf(records)).toString()).build();
    } finally {
        em.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.CommandITCase.java

/**
 * Test cleanup./*ww  w.j a  v  a  2 s .c o m*/
 *
 * @throws Exception the exception
 */
@Test
public void testCleanup() throws Exception {

    assertEquals("DB not empty", 0, countArticles());

    EntityManager em = emf.createEntityManager();

    String[] ids = new String[] { "128", "130", "131", "132", "256", "704" };
    int numberOfArticles = ids.length;

    // insert all items
    for (String id : ids) {
        // item should not be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString());
        assertEquals(0, query.getResultList().size());

        // load content
        String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml",
                "hibernate");
        // patch content - add createTime
        content = content.replace("<uxb_entity ",
                "<uxb_entity createTime=\"" + System.currentTimeMillis() + "\" ");
        // send content to jms broker
        template.sendBody("jms:topic:BUS_OUT", content);
    }
    // wait
    Thread.sleep(TimeOuts.LONG);

    assertEquals("not all items are present", numberOfArticles, countArticles());

    // Save the current time as expiredate
    long expiredate = System.currentTimeMillis();

    ids = new String[] { "128", "130", "131" };
    int numberOfNewArticles = ids.length;

    // insert new items
    for (String id : ids) {
        // item should be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString());
        assertEquals(1, query.getResultList().size());

        // load content
        String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml",
                "hibernate");
        // patch content - add createTime
        content = content.replace("<uxb_entity ",
                "<uxb_entity createTime=\"" + System.currentTimeMillis() + "\" ");
        // send content to jms broker
        template.sendBody("jms:topic:BUS_OUT", content);
    }
    // wait
    Thread.sleep(TimeOuts.LONG);

    assertEquals("not all items are present", numberOfArticles, countArticles());

    // now check, that old items are cleaned up
    for (String id : ids) {
        // load content
        String content = getContent("src/test/resources/inbox/cleanup/pressreleasesdetails.xml", "hibernate");
        // patch content - add createTime
        content = content.replace("<uxb_entity ", "<uxb_entity createTime=\"" + expiredate + "\" ");
        // send content to jms broker
        template.sendBody("jms:topic:BUS_OUT", content);
    }
    // wait
    Thread.sleep(TimeOuts.LONG);

    // Check number of articles
    assertEquals("ups, there are too many items left in the db", numberOfNewArticles, countArticles());

    // Check article ids
    for (String id : ids) {
        // item should be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString());
        assertEquals(1, query.getResultList().size());
    }

    em.close();
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

public Persona findPersona(Long id, int incluir) {
    //public Persona findPersona(Long id, boolean incluirArticulos, boolean incluirContratos, boolean incluirTitulos, boolean incluirTesis, boolean incluirPasantias, boolean incluirFirmas) {
    EntityManager em = null;
    try {/*from   w w  w .  jav  a  2s.  co  m*/
        em = getEntityManager();
        //String incluir = "";
        ArrayList<String> listaFetchs = new ArrayList<>();
        /*int totalFetchs = 0;
        if (incluirContratos) {
        listaFetchs.add(" left join fetch p.contratosCollection ");
        totalFetchs++;
        }            
        if (incluirArticulos) {
        listaFetchs.add(" left join fetch p.personaArticulosCollection ");
        totalFetchs++;
        }            
        if (incluirTitulos) {
        listaFetchs.add(" left join fetch p.personaTitulosCollection ");
        totalFetchs++;
        }
        if (incluirTesis) {
        listaFetchs.add(" left join fetch p.tesisCollection ");
        totalFetchs++;                
        }
        if (incluirPasantias) {
        listaFetchs.add(" left join fetch p.tesisCollection ");
        totalFetchs++;                
        }
        if (incluirFirmas) {
        listaFetchs.add(" left join fetch p.personaFirmasCollection ");
        totalFetchs++;                
        }            
        if (listaFetchs.size() > 1) {
        incluir = listaFetchs.get(0);
        }*/

        TypedQuery<Persona> q = em.createQuery("select p from Persona p where p.id=:id", Persona.class);
        q.setParameter("id", id);
        Persona p = q.getSingleResult();

        if ((incluir & Incluir.INC_CONTRATOS.value()) != 0) {
            for (Contrato contrato : p.getContratosCollection()) {
                Hibernate.initialize(contrato.getProyectosCollection());
            }
        }
        if ((incluir & Incluir.INC_ARTICULOS.value()) != 0) {
            //if (incluirArticulos) {
            //Hibernate.initialize(p.getPersonaArticulosCollection());
            //Hibernate.initialize(p.getPersonaArticulosCollection());
            p.getListaPersonaArticulos().clear();
            for (PersonaFirma perFirma : p.getPersonaFirmasCollection()) {
                for (PersonaArticulo perArticulo : perFirma.getPersonasArticulosCollection()) {
                    p.getListaPersonaArticulos().add(perArticulo);
                }
            }
        }
        if ((incluir & Incluir.INC_TITULOS.value()) != 0) {
            //if (incluirTitulos) {
            Hibernate.initialize(p.getPersonaTitulosCollection());
        }
        if ((incluir & Incluir.INC_TESIS.value()) != 0) {
            //if (incluirTesis) {
            Hibernate.initialize(p.getTesisCollection());
        }
        if ((incluir & Incluir.INC_PASANTIAS.value()) != 0) {
            //if (incluirPasantias) {
            Hibernate.initialize(p.getPasantiasCollection());
        }
        if ((incluir & Incluir.INC_FIRMAS.value()) != 0) {
            //if (incluirFirmas) {
            Hibernate.initialize(p.getPersonaFirmasCollection());
        }
        return p;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

protected ActionForward process(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response, String name) {
    ActionForward forward = null;/*w  w  w.jav  a 2s  .com*/

    AdminBean adminBean = getAdminBean(request);
    if (adminBean == null) {
        Cookie cookies[] = request.getCookies();
        if (cookies == null) {
            return actionMapping.findForward("sessionexpire");
        }
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(Constants.SESSION_COOKIE_USER)) {
                return actionMapping.findForward("sessionexpire");
            }
        }
        return actionMapping.findForward("login");
    }

    EntityManager em = null;
    try {
        em = JpaConnection.getInstance().getCurrentEntityManager();
        em.getTransaction().begin();

        if (actionMapping instanceof AdminActionMapping) {
            AdminActionMapping adminMapping = (AdminActionMapping) actionMapping;
            String userTypes = adminMapping.getUserTypes();
            String tokens[] = userTypes.split(",");
            User user = adminBean.getUser();
            String userType = user.getUserType();
            boolean found = false;
            for (int i = 0; i < tokens.length; i++) {
                if (userType.equals(tokens[i])) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new com.jada.admin.SecurityException(
                        "user " + user.getUserId() + " is blocked from accessing " + actionMapping.getPath());
            }
        }

        logger.debug("RequestURL  > " + request.getRequestURL());
        logger.debug("QueryString > " + request.getQueryString());
        if (Utility.getLogLevel(logger).equals(Level.DEBUG)) {
            logger.debug("Request Information ...");
            Enumeration<?> enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String key = (String) enumeration.nextElement();
                String line = "";
                line += "key=" + key + " value=";
                String values[] = request.getParameterValues(key);
                for (int i = 0; i < values.length; i++) {
                    if (i > 0) {
                        line += ",";
                    }
                    line += "[" + values[i] + "]";
                }
                logger.debug(line);
            }
        }
        AdminMaintActionForm form = (AdminMaintActionForm) actionForm;
        forward = customProcess(actionMapping, form, request, response, name);

        em = JpaConnection.getInstance().getCurrentEntityManager();
        if (em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().commit();
            }
        }
        if (form != null) {
            if (form.isStream) {
                streamWebService(response, form.getStreamData());
            } else {
                encodeForm(form);
            }
        }

    } catch (Throwable e) {
        logger.error("Exception encountered in " + actionMapping.getName());
        logger.error("Exception", e);
        if (e instanceof com.jada.admin.SecurityException) {
            forward = actionMapping.findForward("securityException");
        } else {
            forward = actionMapping.findForward("exception");
        }
    } finally {
        try {
            em = JpaConnection.getInstance().getCurrentEntityManager();
            if (em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
            }
            em.close();
        } catch (Throwable e1) {
            logger.error("Could not rollback transaction after exception!", e1);
        }
    }
    return forward;
}

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

private void save() {
    EntityManager em = OPDE.createEM();

    try {/*from   w ww  . j a v  a  2 s .  co  m*/
        em.getTransaction().begin();

        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

        // Wenn die aPackage null ist, dann ist eine Sonderpackung
        if (aPackage != null) {
            aPackage = em.merge(aPackage);
            if (amount == null) {
                amount = aPackage.getContent();
            }
        }

        tradeForm = em.merge(tradeForm);
        inventory = em.merge(inventory);

        if (inventory.getID() == null) { // create a new MedInvetory.
            inventory.setText(TradeFormTools.toPrettyString(tradeForm) + "; "
                    + ACMETools.toPrettyStringShort(tradeForm.getMedProduct().getACME()));
        }

        BigDecimal estimatedUPR = MedStockTools.getEstimatedUPR(tradeForm);
        int dummyMode = tradeForm.getDosageForm().isUPRn() && MedStockTools.isNoStockYetForThis(tradeForm)
                ? MedStockTools.REPLACE_WITH_EFFECTIVE_UPR_WHEN_CLOSING
                : MedStockTools.ADD_TO_AVERAGES_UPR_WHEN_CLOSING;

        MedStock newStock = em.merge(
                new MedStock(inventory, tradeForm, aPackage, txtBemerkung.getText(), estimatedUPR, dummyMode));
        newStock.setExpires(expiry);
        MedStockTransaction tx = em.merge(new MedStockTransaction(newStock, amount));
        tx.setWeight(weight);

        em.getTransaction().commit();
        amount = null;
        aPackage = null;
        tradeForm = null;
        inventory = null;
        expiry = null;
        weight = null;

        if (btnPrint.isSelected()) {
            OPDE.getPrintProcessor().addPrintJob(new PrintListElement(newStock, logicalPrinter, printForm,
                    OPDE.getProps().getProperty(SYSPropsTools.KEY_PHYSICAL_PRINTER)));
        }

        // if the label printer is not used, the new number is shown until the next message, so the user has time to write the number down manually.
        OPDE.getDisplayManager()
                .addSubMessage(new DisplayMessage(
                        SYSTools.xx("newstocks.registration.success.1") + " <b>" + newStock.getID() + "</b> "
                                + SYSTools.xx("newstocks.registration.success.2"),
                        btnPrint.isSelected() ? 2 : 0));
    } 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 (Exception ex) {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        OPDE.fatal(ex);
    } finally {
        em.close();
    }
}

From source file:op.care.dfn.PnlDFN.java

private CollapsiblePane createCP4(final DFN dfn) {
    final CollapsiblePane dfnPane = new CollapsiblePane();

    ActionListener applyActionListener = new ActionListener() {
        @Override// w  ww.  j a  v a2 s . com
        public void actionPerformed(ActionEvent actionEvent) {
            if (dfn.getState() == DFNTools.STATE_DONE) {
                return;
            }
            if (!dfn.isOnDemand() && dfn.getNursingProcess().isClosed()) {
                return;
            }

            if (DFNTools.isChangeable(dfn)) {
                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();

                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                    DFN myDFN = em.merge(dfn);
                    em.lock(myDFN, LockModeType.OPTIMISTIC);
                    if (!myDFN.isOnDemand()) {
                        em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                    }

                    myDFN.setState(DFNTools.STATE_DONE);
                    myDFN.setUser(em.merge(OPDE.getLogin().getUser()));
                    myDFN.setIst(new Date());
                    myDFN.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                    myDFN.setMdate(new Date());

                    em.getTransaction().commit();

                    CollapsiblePane cp1 = createCP4(myDFN);

                    synchronized (mapDFN2Pane) {
                        mapDFN2Pane.put(myDFN, cp1);
                    }
                    synchronized (mapShift2DFN) {
                        int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                        mapShift2DFN.get(myDFN.getShift()).remove(position);
                        mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                    }

                    CollapsiblePane cp2 = createCP4(myDFN.getShift());
                    synchronized (mapShift2Pane) {
                        mapShift2Pane.put(myDFN.getShift(), cp2);
                    }

                    buildPanel(false);

                } 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 (Exception e) {
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    OPDE.fatal(e);
                } finally {
                    em.close();
                }

            } else {
                OPDE.getDisplayManager()
                        .addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.dfn.notchangeable")));
            }
        }
    };

    String title = "<html><font size=+1>" +
    //                (dfn.isFloating() ? (dfn.isActive() ? "(!) " : "(OK) ") : "") +
            SYSTools.left(dfn.getIntervention().getBezeichnung(), MAX_TEXT_LENGTH)
            + DFNTools.getScheduleText(dfn, " [", "]") + ", " + dfn.getMinutes() + " "
            + SYSTools.xx("misc.msg.Minute(s)")
            + (dfn.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(dfn.getUser().getUID()) + "</i>" : "")
            + "</font></html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title,
            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID) ? applyActionListener
                    : null);
    dfnPane.setCollapseOnTitleClick(false);
    //        cptitle.getTitleButton().setIcon(DFNTools.getIcon(dfn));
    JLabel icon1 = new JLabel(DFNTools.getIcon(dfn));
    icon1.setOpaque(false);
    JLabel icon2 = new JLabel(DFNTools.getFloatingIcon(dfn));
    icon2.setOpaque(false);
    cptitle.getAdditionalIconPanel().add(icon1);
    cptitle.getAdditionalIconPanel().add(icon2);

    if (dfn.isFloating()) {
        cptitle.getButton().setToolTipText(SYSTools.xx("nursingrecords.dfn.enforced.tooltip") + ": "
                + DateFormat.getDateInstance().format(dfn.getStDatum()));
    }

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)
            && (dfn.isOnDemand() || !dfn.getNursingProcess().isClosed())) {
        /***
         *      _     _            _                _
         *     | |__ | |_ _ __    / \   _ __  _ __ | |_   _
         *     | '_ \| __| '_ \  / _ \ | '_ \| '_ \| | | | |
         *     | |_) | |_| | | |/ ___ \| |_) | |_) | | |_| |
         *     |_.__/ \__|_| |_/_/   \_\ .__/| .__/|_|\__, |
         *                             |_|   |_|      |___/
         */
        JButton btnApply = new JButton(SYSConst.icon22apply);
        btnApply.setPressedIcon(SYSConst.icon22applyPressed);
        btnApply.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnApply.setContentAreaFilled(false);
        btnApply.setBorder(null);
        btnApply.addActionListener(applyActionListener);
        btnApply.setEnabled(!dfn.isOnDemand() && dfn.isOpen());
        cptitle.getRight().add(btnApply);
        //            JPanel spacer = new JPanel();
        //            spacer.setOpaque(false);
        //            cptitle.getRight().add(spacer);
        /***
         *      _     _          ____                     _
         *     | |__ | |_ _ __  / ___|__ _ _ __   ___ ___| |
         *     | '_ \| __| '_ \| |   / _` | '_ \ / __/ _ \ |
         *     | |_) | |_| | | | |__| (_| | | | | (_|  __/ |
         *     |_.__/ \__|_| |_|\____\__,_|_| |_|\___\___|_|
         *
         */
        final JButton btnCancel = new JButton(SYSConst.icon22cancel);
        btnCancel.setPressedIcon(SYSConst.icon22cancelPressed);
        btnCancel.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnCancel.setContentAreaFilled(false);
        btnCancel.setBorder(null);
        //            btnCancel.setToolTipText(SYSTools.xx("nursingrecords.dfn.btneval.tooltip"));
        btnCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (dfn.getState() == DFNTools.STATE_REFUSED) {
                    return;
                }

                if (DFNTools.isChangeable(dfn)) {
                    EntityManager em = OPDE.createEM();
                    try {
                        em.getTransaction().begin();

                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                        DFN myDFN = em.merge(dfn);
                        em.lock(myDFN, LockModeType.OPTIMISTIC);
                        if (!myDFN.isOnDemand()) {
                            em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                        }

                        myDFN.setState(DFNTools.STATE_REFUSED);
                        myDFN.setUser(em.merge(OPDE.getLogin().getUser()));
                        myDFN.setIst(new Date());
                        myDFN.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                        myDFN.setMdate(new Date());

                        em.getTransaction().commit();

                        CollapsiblePane cp1 = createCP4(myDFN);
                        synchronized (mapDFN2Pane) {
                            mapDFN2Pane.put(myDFN, cp1);
                        }
                        synchronized (mapShift2DFN) {
                            int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                            mapShift2DFN.get(myDFN.getShift()).remove(position);
                            mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                        }
                        CollapsiblePane cp2 = createCP4(myDFN.getShift());
                        synchronized (mapShift2Pane) {
                            mapShift2Pane.put(myDFN.getShift(), cp2);
                        }
                        buildPanel(false);
                    } 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 (Exception e) {
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        OPDE.fatal(e);
                    } finally {
                        em.close();
                    }

                } else {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.dfn.notchangeable")));
                }
            }
        });
        btnCancel.setEnabled(!dfn.isOnDemand() && dfn.isOpen());
        cptitle.getRight().add(btnCancel);

        /***
         *      _     _         _____                 _
         *     | |__ | |_ _ __ | ____|_ __ ___  _ __ | |_ _   _
         *     | '_ \| __| '_ \|  _| | '_ ` _ \| '_ \| __| | | |
         *     | |_) | |_| | | | |___| | | | | | |_) | |_| |_| |
         *     |_.__/ \__|_| |_|_____|_| |_| |_| .__/ \__|\__, |
         *                                     |_|        |___/
         */
        final JButton btnEmpty = new JButton(SYSConst.icon22empty);
        btnEmpty.setPressedIcon(SYSConst.icon22emptyPressed);
        btnEmpty.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEmpty.setContentAreaFilled(false);
        btnEmpty.setBorder(null);
        //            btnCancel.setToolTipText(SYSTools.xx("nursingrecords.dfn.btneval.tooltip"));
        btnEmpty.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (dfn.getState() == DFNTools.STATE_OPEN) {
                    return;
                }

                if (DFNTools.isChangeable(dfn)) {
                    EntityManager em = OPDE.createEM();
                    try {
                        em.getTransaction().begin();

                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                        DFN myDFN = em.merge(dfn);
                        em.lock(myDFN, LockModeType.OPTIMISTIC);
                        if (!myDFN.isOnDemand()) {
                            em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                        }

                        // on demand DFNs are deleted if they not wanted anymore
                        if (myDFN.isOnDemand()) {
                            em.remove(myDFN);
                            synchronized (mapDFN2Pane) {
                                mapDFN2Pane.remove(myDFN);
                            }
                            synchronized (mapShift2DFN) {
                                mapShift2DFN.get(myDFN.getShift()).remove(myDFN);
                            }
                        } else {
                            // the normal DFNs (those assigned to a NursingProcess) are reset to the OPEN state.
                            myDFN.setState(DFNTools.STATE_OPEN);
                            myDFN.setUser(null);
                            myDFN.setIst(null);
                            myDFN.setiZeit(null);
                            myDFN.setMdate(new Date());
                            CollapsiblePane cp1 = createCP4(myDFN);
                            synchronized (mapDFN2Pane) {
                                mapDFN2Pane.put(myDFN, cp1);
                            }
                            synchronized (mapShift2DFN) {
                                int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                                mapShift2DFN.get(myDFN.getShift()).remove(position);
                                mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                            }
                        }
                        em.getTransaction().commit();

                        CollapsiblePane cp2 = createCP4(myDFN.getShift());
                        synchronized (mapShift2Pane) {
                            mapShift2Pane.put(myDFN.getShift(), cp2);
                        }
                        buildPanel(false);
                    } 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 (Exception e) {
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        OPDE.fatal(e);
                    } finally {
                        em.close();
                    }

                } else {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.dfn.notchangeable")));
                }
            }
        });
        btnEmpty.setEnabled(!dfn.isOpen());
        cptitle.getRight().add(btnEmpty);

        /***
         *      _     _         __  __ _             _
         *     | |__ | |_ _ __ |  \/  (_)_ __  _   _| |_ ___  ___
         *     | '_ \| __| '_ \| |\/| | | '_ \| | | | __/ _ \/ __|
         *     | |_) | |_| | | | |  | | | | | | |_| | ||  __/\__ \
         *     |_.__/ \__|_| |_|_|  |_|_|_| |_|\__,_|\__\___||___/
         *
         */
        final JButton btnMinutes = new JButton(SYSConst.icon22clock);
        btnMinutes.setPressedIcon(SYSConst.icon22clockPressed);
        btnMinutes.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMinutes.setContentAreaFilled(false);
        btnMinutes.setBorder(null);
        //            btnCancel.setToolTipText(SYSTools.xx("nursingrecords.dfn.btneval.tooltip"));
        btnMinutes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (!DFNTools.isChangeable(dfn)) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.dfn.notchangeable")));
                    return;
                }
                final JPopupMenu menu = SYSCalendar.getMinutesMenu(
                        new int[] { 1, 2, 3, 4, 5, 10, 15, 20, 30, 45, 60, 120, 240, 360 }, new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();

                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    DFN myDFN = em.merge(dfn);
                                    em.lock(myDFN, LockModeType.OPTIMISTIC);
                                    if (!myDFN.isOnDemand()) {
                                        em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                                    }

                                    myDFN.setMinutes(new BigDecimal((Integer) o));
                                    myDFN.setUser(em.merge(OPDE.getLogin().getUser()));
                                    myDFN.setMdate(new Date());
                                    em.getTransaction().commit();

                                    CollapsiblePane cp1 = createCP4(myDFN);
                                    synchronized (mapDFN2Pane) {
                                        mapDFN2Pane.put(myDFN, cp1);
                                    }
                                    synchronized (mapShift2DFN) {
                                        int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                                        mapShift2DFN.get(myDFN.getShift()).remove(position);
                                        mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                                    }
                                    CollapsiblePane cp2 = createCP4(myDFN.getShift());
                                    synchronized (mapShift2Pane) {
                                        mapShift2Pane.put(myDFN.getShift(), cp2);
                                    }

                                    buildPanel(false);
                                } 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 (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                            }
                        });

                menu.show(btnMinutes, 0, btnMinutes.getHeight());
            }
        });
        btnMinutes.setEnabled(dfn.getState() != DFNTools.STATE_OPEN);
        cptitle.getRight().add(btnMinutes);
    }

    /***
     *      _     _         ___        __
     *     | |__ | |_ _ __ |_ _|_ __  / _| ___
     *     | '_ \| __| '_ \ | || '_ \| |_ / _ \
     *     | |_) | |_| | | || || | | |  _| (_) |
     *     |_.__/ \__|_| |_|___|_| |_|_|  \___/
     *
     */
    final JButton btnInfo = new JButton(SYSConst.icon22info);
    final JidePopup popupInfo = new JidePopup();
    btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
    btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnInfo.setContentAreaFilled(false);
    btnInfo.setBorder(null);
    final JTextPane txt = new JTextPane();
    txt.setContentType("text/html");
    txt.setEditable(false);

    popupInfo.setMovable(false);
    popupInfo.getContentPane().setLayout(new BoxLayout(popupInfo.getContentPane(), BoxLayout.LINE_AXIS));
    popupInfo.getContentPane().add(new JScrollPane(txt));
    popupInfo.removeExcludedComponent(txt);
    popupInfo.setDefaultFocusComponent(txt);

    btnInfo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            popupInfo.setOwner(btnInfo);
            txt.setText(SYSTools.toHTML(SYSConst.html_div(dfn.getInterventionSchedule().getBemerkung())));
            GUITools.showPopup(popupInfo, SwingConstants.WEST);
        }
    });

    btnInfo.setEnabled(
            !dfn.isOnDemand() && !SYSTools.catchNull(dfn.getInterventionSchedule().getBemerkung()).isEmpty());
    cptitle.getRight().add(btnInfo);

    dfnPane.setTitleLabelComponent(cptitle.getMain());

    dfnPane.setBackground(dfn.getBG());
    dfnPane.setForeground(dfn.getFG());
    try {
        dfnPane.setCollapsed(true);
    } catch (PropertyVetoException e) {
        OPDE.error(e);
    }
    dfnPane.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            JTextPane contentPane = new JTextPane();
            contentPane.setContentType("text/html");
            contentPane.setEditable(false);
            contentPane.setText(SYSTools
                    .toHTML(NursingProcessTools.getAsHTML(dfn.getNursingProcess(), false, true, false, false)));
            dfnPane.setContentPane(contentPane);
        }
    });
    dfnPane.setCollapsible(dfn.getNursingProcess() != null);
    dfnPane.setHorizontalAlignment(SwingConstants.LEADING);
    dfnPane.setOpaque(false);
    return dfnPane;
}