Example usage for javax.persistence LockModeType OPTIMISTIC

List of usage examples for javax.persistence LockModeType OPTIMISTIC

Introduction

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

Prototype

LockModeType OPTIMISTIC

To view the source code for javax.persistence LockModeType OPTIMISTIC.

Click Source Link

Document

Optimistic lock.

Usage

From source file:op.allowance.PnlAllowance.java

private JPanel createContentPanel4(final Resident resident, LocalDate month) {
    final String key = getKey(resident, month);

    if (!contentmap.containsKey(key)) {

        JPanel pnlMonth = new JPanel(new VerticalLayout());

        pnlMonth.setBackground(getBG(resident, 11));
        pnlMonth.setOpaque(false);/*  w w  w . j  a  va  2  s .  c  o m*/

        //            final String prevKey = resident.getRID() + "-" + SYSCalendar.eom(month.minusMonths(1)).getYear() + "-" + SYSCalendar.eom(month.minusMonths(1)).getMonthOfYear();
        if (!carrySums.containsKey(key)) {
            carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month.minusMonths(1))));
        }

        BigDecimal rowsum = carrySums.get(key);

        if (!cashmap.containsKey(key)) {
            cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
        }

        JLabel lblEOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMaximumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.endofmonth") + "</td>"
                + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        pnlMonth.add(lblEOM);

        for (final Allowance allowance : cashmap.get(key)) {

            String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                    + DateFormat.getDateInstance().format(allowance.getPit()) + "</td>"
                    + "<td width=\"400\" align=\"left\">" + allowance.getText() + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                    + cf.format(allowance.getAmount())
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>"
                    +

                    "</font></html>";

            DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                }
            });
            cptitle.getButton().setIcon(
                    allowance.isReplaced() || allowance.isReplacement() ? SYSConst.icon22eraser : null);

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
                /***
                 *      _____    _ _ _
                 *     | ____|__| (_) |_
                 *     |  _| / _` | | __|
                 *     | |__| (_| | | |_
                 *     |_____\__,_|_|\__|
                 *
                 */
                final JButton btnEdit = new JButton(SYSConst.icon22edit3);
                btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
                btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnEdit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnEdit.setContentAreaFilled(false);
                btnEdit.setBorder(null);
                btnEdit.setToolTipText(SYSTools.xx("admin.residents.cash.btnedit.tooltip"));
                btnEdit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        final JidePopup popupTX = new JidePopup();
                        popupTX.setMovable(false);
                        PnlTX pnlTX = getPnlTX(resident, allowance);
                        popupTX.setContentPane(pnlTX);
                        popupTX.removeExcludedComponent(pnlTX);
                        popupTX.setDefaultFocusComponent(pnlTX);

                        popupTX.setOwner(btnEdit);
                        GUITools.showPopup(popupTX, SwingConstants.WEST);

                    }
                });
                cptitle.getRight().add(btnEdit);
                // you can edit your own entries or you are a manager. once they are replaced or a replacement record, its over.
                btnEdit.setEnabled((OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, internalClassID)
                        || allowance.getUser().equals(OPDE.getLogin().getUser())) && !allowance.isReplaced()
                        && !allowance.isReplacement());

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("admin.residents.cash.btnundotx.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>" + "<br/><i>"
                                        + allowance.getText() + "&nbsp;" + cf.format(allowance.getAmount())
                                        + "</i><br/>" + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();

                                                Allowance myOldAllowance = em.merge(allowance);
                                                Allowance myCancelAllowance = em
                                                        .merge(new Allowance(myOldAllowance));
                                                em.lock(em.merge(myOldAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myOldAllowance, LockModeType.OPTIMISTIC);
                                                myOldAllowance.setReplacedBy(myCancelAllowance,
                                                        em.merge(OPDE.getLogin().getUser()));

                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myCancelAllowance.getPit());

                                                final String keyMonth = myCancelAllowance.getResident().getRID()
                                                        + "-" + txDate.getYear() + "-"
                                                        + txDate.getMonthOfYear();
                                                contentmap.remove(keyMonth);
                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(allowance);
                                                cashmap.get(keyMonth).add(myOldAllowance);
                                                cashmap.get(keyMonth).add(myCancelAllowance);
                                                Collections.sort(cashmap.get(keyMonth));

                                                updateCarrySums(myCancelAllowance);

                                                createCP4(myCancelAllowance.getResident());

                                                try {
                                                    cpMap.get(keyMonth).setCollapsed(false);
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                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 (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnUndoTX);
                btnUndoTX.setEnabled(!allowance.isReplaced() && !allowance.isReplacement());
            }

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
                /***
                 *      ____       _      _
                 *     |  _ \  ___| | ___| |_ ___
                 *     | | | |/ _ \ |/ _ \ __/ _ \
                 *     | |_| |  __/ |  __/ ||  __/
                 *     |____/ \___|_|\___|\__\___|
                 *
                 */
                final JButton btnDelete = new JButton(SYSConst.icon22delete);
                btnDelete.setPressedIcon(SYSConst.icon22deletePressed);
                btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnDelete.setContentAreaFilled(false);
                btnDelete.setBorder(null);
                btnDelete.setToolTipText(SYSTools.xx("admin.residents.cash.btndelete.tooltip"));
                btnDelete.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.delete1") + "<br/><i>" + allowance.getText()
                                        + "&nbsp;" + cf.format(allowance.getAmount()) + "</i><br/>"
                                        + SYSTools.xx("misc.questions.delete2"),
                                SYSConst.icon48delete, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                Allowance myAllowance = em.merge(allowance);
                                                em.lock(em.merge(myAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);

                                                Allowance theOtherOne = null;
                                                // Check for special cases
                                                if (myAllowance.isReplacement()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacementFor());
                                                    theOtherOne.setReplacedBy(null);
                                                    theOtherOne.setEditedBy(null);
                                                    myAllowance.setEditPit(null);
                                                }
                                                if (myAllowance.isReplaced()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacedBy());
                                                    theOtherOne.setReplacementFor(null);
                                                }

                                                em.remove(myAllowance);
                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myAllowance.getPit());
                                                final String keyMonth = myAllowance.getResident().getRID() + "-"
                                                        + txDate.getYear() + "-" + txDate.getMonthOfYear();

                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(myAllowance);
                                                if (theOtherOne != null) {
                                                    cashmap.get(keyMonth).remove(theOtherOne);
                                                    cashmap.get(keyMonth).add(theOtherOne);
                                                    Collections.sort(cashmap.get(keyMonth));
                                                }

                                                // only to update the carrysums. myAllowance will be discarded soon.
                                                myAllowance.setAmount(myAllowance.getAmount().negate());
                                                updateCarrySums(myAllowance);

                                                createCP4(myAllowance.getResident());

                                                try {
                                                    if (cpMap.containsKey(keyMonth)) {
                                                        cpMap.get(keyMonth).setCollapsed(false);
                                                    }
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                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 (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnDelete);
            }
            pnlMonth.add(cptitle.getMain());
            linemap.put(allowance, cptitle.getMain());

            rowsum = rowsum.subtract(allowance.getAmount());
        }

        JLabel lblBOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMinimumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.startofmonth")
                + "</td>" + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        lblBOM.setBackground(getBG(resident, 11));
        pnlMonth.add(lblBOM);
        contentmap.put(key, pnlMonth);
    }

    return contentmap.get(key);
}

From source file:op.care.prescription.PnlPrescription.java

private JPanel getMenu(final Prescription prescription) {

    JPanel pnlMenu = new JPanel(new VerticalLayout());
    long numBHPs = BHPTools.getConfirmedBHPs(prescription);
    final MedInventory inventory = prescription.shouldBeCalculated()
            ? TradeFormTools.getInventory4TradeForm(prescription.getResident(), prescription.getTradeForm())
            : null;// w  ww.  ja  v a2 s .co  m
    final MedStock stockInUse = MedStockTools.getStockInUse(inventory);

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***
         *       ____ _
         *      / ___| |__   __ _ _ __   __ _  ___
         *     | |   | '_ \ / _` | '_ \ / _` |/ _ \
         *     | |___| | | | (_| | | | | (_| |  __/
         *      \____|_| |_|\__,_|_| |_|\__, |\___|
         *                              |___/
         */
        final JButton btnChange = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.btnChange.tooltip", SYSConst.icon22playerPlay, null);
        btnChange.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnChange.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgRegular(prescription.clone(), DlgRegular.MODE_CHANGE, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {

                            Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o;

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                // Fetch the new prescription from the PAIR
                                Prescription newPrescription = em.merge(returnPackage.getFirst());
                                Prescription oldPrescription = em.merge(prescription);
                                em.lock(oldPrescription, LockModeType.OPTIMISTIC);

                                // First close the old prescription
                                DateTime now = new DateTime();
                                oldPrescription.setTo(now.toDate());
                                oldPrescription.setUserOFF(em.merge(OPDE.getLogin().getUser()));
                                oldPrescription.setDocOFF(newPrescription.getDocON() == null ? null
                                        : em.merge(newPrescription.getDocON()));
                                oldPrescription.setHospitalOFF(newPrescription.getHospitalON() == null ? null
                                        : em.merge(newPrescription.getHospitalON()));

                                // the new prescription starts 1 second after the old one closes
                                newPrescription.setFrom(now.plusSeconds(1).toDate());

                                // create new BHPs according to the prescription
                                BHPTools.generate(em, newPrescription.getPrescriptionSchedule(),
                                        new LocalDate(), true);
                                em.getTransaction().commit();

                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(oldPrescription);
                                lstPrescriptions.add(newPrescription);
                                Collections.sort(lstPrescriptions);

                                // Refresh Display
                                createCP4(oldPrescription);
                                final CollapsiblePane myNewCP = createCP4(newPrescription);
                                buildPanel();
                                GUITools.flashBackground(myNewCP, Color.YELLOW, 2);
                            } 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();
                            }
                            //                                buildPanel();
                        }
                    }
                });
            }
        });
        btnChange.setEnabled(!prescription.isClosed() && !prescription.isOnDemand() && numBHPs != 0);
        pnlMenu.add(btnChange);

        /***
         *      ____  _
         *     / ___|| |_ ___  _ __
         *     \___ \| __/ _ \| '_ \
         *      ___) | || (_) | |_) |
         *     |____/ \__\___/| .__/
         *                    |_|
         */
        final JButton btnStop = GUITools.createHyperlinkButton("nursingrecords.prescription.btnStop.tooltip",
                SYSConst.icon22playerStop, null);
        btnStop.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnStop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgDiscontinue(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                Prescription myPrescription = (Prescription) em.merge(o);
                                em.lock(myPrescription.getResident(), LockModeType.OPTIMISTIC);
                                em.lock(myPrescription, LockModeType.OPTIMISTIC);
                                myPrescription.setTo(new Date());
                                em.getTransaction().commit();

                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);

                                buildPanel();

                                SwingUtilities.invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                new Closure() {
                                                    @Override
                                                    public void execute(Object o) {
                                                        GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                    }
                                                });
                                    }
                                });

                            } 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) {
                                em.getTransaction().rollback();
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                });
            }
        });
        btnStop.setEnabled(!prescription.isClosed()); //  && numBHPs != 0
        pnlMenu.add(btnStop);

        /***
         *      _____    _ _ _
         *     | ____|__| (_) |_
         *     |  _| / _` | | __|
         *     | |__| (_| | | |_
         *     |_____\__,_|_|\__/
         *
         */
        final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.prescription.btnEdit.tooltip",
                SYSConst.icon22edit3, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (prescription.isOnDemand()) {
                    new DlgOnDemand(prescription, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {

                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    Prescription myPrescription = em.merge((Prescription) o);
                                    em.lock(myPrescription, LockModeType.OPTIMISTIC);

                                    Query queryDELBHP = em.createQuery(
                                            "DELETE FROM BHP bhp WHERE bhp.prescription = :prescription");
                                    queryDELBHP.setParameter("prescription", myPrescription);
                                    queryDELBHP.executeUpdate();

                                    em.getTransaction().commit();

                                    lstPrescriptions.remove(prescription);
                                    lstPrescriptions.add(myPrescription);
                                    Collections.sort(lstPrescriptions);
                                    final CollapsiblePane myCP = createCP4(myPrescription);
                                    buildPanel();

                                    synchronized (listUsedCommontags) {
                                        boolean reloadSearch = false;
                                        for (Commontags ctag : myPrescription.getCommontags()) {
                                            if (!listUsedCommontags.contains(ctag)) {
                                                listUsedCommontags.add(ctag);
                                                reloadSearch = true;
                                            }
                                        }
                                        if (reloadSearch) {
                                            prepareSearchArea();
                                        }
                                    }
                                    SwingUtilities.invokeLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                    new Closure() {
                                                        @Override
                                                        public void execute(Object o) {
                                                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                        }
                                                    });
                                        }
                                    });

                                } 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();
                                }
                                //                                    buildPanel();
                            }
                        }
                    });
                } else {
                    new DlgRegular(prescription, DlgRegular.MODE_EDIT, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {

                                Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o;

                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    Prescription myPrescription = em.merge(returnPackage.getFirst());
                                    em.lock(myPrescription, LockModeType.OPTIMISTIC);

                                    // delete whats not in the new prescription anymore
                                    for (PrescriptionSchedule schedule : returnPackage.getSecond()) {
                                        em.remove(em.merge(schedule));
                                    }

                                    Query queryDELBHP = em.createQuery(
                                            "DELETE FROM BHP bhp WHERE bhp.prescription = :prescription");
                                    queryDELBHP.setParameter("prescription", myPrescription);
                                    queryDELBHP.executeUpdate();

                                    BHPTools.generate(em, myPrescription.getPrescriptionSchedule(),
                                            new LocalDate(), true);

                                    em.getTransaction().commit();

                                    lstPrescriptions.remove(prescription);
                                    lstPrescriptions.add(myPrescription);
                                    Collections.sort(lstPrescriptions);
                                    final CollapsiblePane myCP = createCP4(myPrescription);
                                    buildPanel();

                                    synchronized (listUsedCommontags) {
                                        boolean reloadSearch = false;
                                        for (Commontags ctag : myPrescription.getCommontags()) {
                                            if (!listUsedCommontags.contains(ctag)) {
                                                listUsedCommontags.add(ctag);
                                                reloadSearch = true;
                                            }
                                        }
                                        if (reloadSearch) {
                                            prepareSearchArea();
                                        }
                                    }

                                    SwingUtilities.invokeLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                    new Closure() {
                                                        @Override
                                                        public void execute(Object o) {
                                                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                        }
                                                    });
                                        }
                                    });

                                } 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();
                                }
                                //                                    buildPanel();
                            }
                        }
                    });
                }
            }

        });
        btnEdit.setEnabled(!prescription.isClosed() && numBHPs == 0);
        pnlMenu.add(btnEdit);

        /***
         *      _     _       _____  _    ____
         *     | |__ | |_ _ _|_   _|/ \  / ___|___
         *     | '_ \| __| '_ \| | / _ \| |  _/ __|
         *     | |_) | |_| | | | |/ ___ \ |_| \__ \
         *     |_.__/ \__|_| |_|_/_/   \_\____|___/
         *
         */
        final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple,
                null);
        btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnTAGs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                final JPanel pnl = new JPanel(new BorderLayout(5, 5));
                final PnlCommonTags pnlCommonTags = new PnlCommonTags(prescription.getCommontags(), true, 3);
                pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER);
                JButton btnApply = new JButton(SYSConst.icon22apply);
                pnl.add(btnApply, BorderLayout.SOUTH);
                btnApply.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        EntityManager em = OPDE.createEM();
                        try {

                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            Prescription myPrescription = em.merge(prescription);
                            em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            // merging is important, hence no addAll() for this one
                            ArrayList<Commontags> listTags2Add = new ArrayList<Commontags>();
                            for (Commontags tag2add : pnlCommonTags.getListSelectedTags()) {
                                listTags2Add.add(em.merge(tag2add));
                            }

                            // Annotations need to be added, tooo
                            // these are the remaining tags, that need to be disconnected
                            myPrescription.getCommontags().addAll(listTags2Add);
                            ArrayList<Commontags> listTags2Remove = new ArrayList<Commontags>(
                                    myPrescription.getCommontags());
                            listTags2Remove.removeAll(listTags2Add);

                            myPrescription.getCommontags().removeAll(listTags2Remove);

                            ArrayList<ResInfo> annotations2remove = new ArrayList<ResInfo>();
                            for (Commontags commontag : listTags2Remove) {
                                for (ResInfo annotation : myPrescription.getAnnotations()) {
                                    if (CommontagsTools.getTagForAnnotation(annotation).equals(commontag)) {
                                        annotations2remove.add(annotation);
                                        em.remove(annotation);
                                    }
                                }
                            }
                            myPrescription.getAnnotations().removeAll(annotations2remove);

                            em.getTransaction().commit();

                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();

                            synchronized (listUsedCommontags) {
                                boolean reloadSearch = false;
                                for (Commontags ctag : myPrescription.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }
                            }

                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                            new Closure() {
                                                @Override
                                                public void execute(Object o) {
                                                    GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                }
                                            });
                                }
                            });

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            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 (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnTAGs);
                popup.removeExcludedComponent(btnTAGs);
                pnl.setPreferredSize(new Dimension(350, 150));
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);

            }
        });
        btnTAGs.setEnabled(!prescription.isClosed());
        pnlMenu.add(btnTAGs);

        /***
         *                              _        _
         *       __ _ _ __  _ __   ___ | |_ __ _| |_ ___
         *      / _` | '_ \| '_ \ / _ \| __/ _` | __/ _ \
         *     | (_| | | | | | | | (_) | || (_| | ||  __/
         *      \__,_|_| |_|_| |_|\___/ \__\__,_|\__\___|
         *
         */

        final JButton btnAnnotation = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.edit.annotations", SYSConst.icon22annotate, null);
        btnAnnotation.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnAnnotation.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                DlgAnnotations dlg = new DlgAnnotations(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                ResInfo annotation = em.merge((ResInfo) o);

                                annotation.setHtml(ResInfoTools.getContentAsHTML(annotation));

                                Prescription myPrescription = em.merge(prescription);
                                em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                myPrescription.getAnnotations().remove(annotation); // just in case, it was an EDIT rather than an ADD
                                myPrescription.getAnnotations().add(annotation);

                                em.lock(annotation, LockModeType.OPTIMISTIC);
                                em.getTransaction().commit();

                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);

                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                                buildPanel();

                                SwingUtilities.invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                new Closure() {
                                                    @Override
                                                    public void execute(Object o) {
                                                        GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                    }
                                                });
                                    }
                                });

                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                });

                OPDE.debug(lstPrescriptions);

                dlg.setVisible(true);

            }
        });
        btnAnnotation.setEnabled(!prescription.isClosed() && prescription.hasMed()
                && PrescriptionTools.isAnnotationNecessary(prescription));
        pnlMenu.add(btnAnnotation);
    }

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
        /***
         *      ____       _      _
         *     |  _ \  ___| | ___| |_ ___
         *     | | | |/ _ \ |/ _ \ __/ _ \
         *     | |_| |  __/ |  __/ ||  __/
         *     |____/ \___|_|\___|\__\___|
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.btnDelete.tooltip", SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {

                new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/>"
                        + PrescriptionTools.toPrettyString(prescription) + "</br>"
                        + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object answer) {
                                if (answer.equals(JOptionPane.YES_OPTION)) {

                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        Prescription myverordnung = em.merge(prescription);
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        em.lock(myverordnung, LockModeType.OPTIMISTIC);
                                        em.remove(myverordnung);

                                        Query delQuery = em.createQuery(
                                                "DELETE FROM BHP b WHERE b.prescription = :prescription");
                                        delQuery.setParameter("prescription", myverordnung);
                                        delQuery.executeUpdate();
                                        em.getTransaction().commit();

                                        OPDE.getDisplayManager().addSubMessage(
                                                new DisplayMessage(SYSTools.xx("misc.msg.Deleted") + ": "
                                                        + PrescriptionTools.toPrettyString(myverordnung)));
                                        lstPrescriptions.remove(prescription);
                                        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 (Exception e) {
                                        em.getTransaction().rollback();
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });
            }

        });
        btnDelete.setEnabled(numBHPs == 0 && !prescription.isClosed());
        pnlMenu.add(btnDelete);
    }
    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        pnlMenu.add(new JSeparator());

        /***
         *      ____       _   _____            _            ____        _
         *     / ___|  ___| |_| ____|_  ___ __ (_)_ __ _   _|  _ \  __ _| |_ ___
         *     \___ \ / _ \ __|  _| \ \/ / '_ \| | '__| | | | | | |/ _` | __/ _ \
         *      ___) |  __/ |_| |___ >  <| |_) | | |  | |_| | |_| | (_| | ||  __/
         *     |____/ \___|\__|_____/_/\_\ .__/|_|_|   \__, |____/ \__,_|\__\___|
         *                               |_|           |___/
         */
        final JButton btnExpiry = GUITools.createHyperlinkButton(
                "nursingrecords.inventory.tooltip.btnSetExpiry", SYSConst.icon22gotoEnd, null);
        btnExpiry.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();
                popup.setMovable(false);

                PnlExpiry pnlExpiry = new PnlExpiry(stockInUse.getExpires(),
                        SYSTools.xx("nursingrecords.inventory.pnlExpiry.title") + ": " + stockInUse.getID(),
                        new Closure() {
                            @Override
                            public void execute(Object o) {
                                popup.hidePopup();

                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    MedStock myStock = em.merge(stockInUse);
                                    em.lock(em.merge(myStock.getInventory().getResident()),
                                            LockModeType.OPTIMISTIC);
                                    em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC);
                                    myStock.setExpires((Date) o);
                                    em.getTransaction().commit();
                                    createCP4(prescription);
                                    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 (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }

                            }
                        });
                popup.setOwner(btnExpiry);
                popup.setContentPane(pnlExpiry);
                popup.removeExcludedComponent(pnlExpiry);
                popup.setDefaultFocusComponent(pnlExpiry);
                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });
        btnExpiry.setEnabled(inventory != null && stockInUse != null);
        pnlMenu.add(btnExpiry);

        /***
         *       ____ _                ____  _             _
         *      / ___| | ___  ___  ___/ ___|| |_ ___   ___| | __
         *     | |   | |/ _ \/ __|/ _ \___ \| __/ _ \ / __| |/ /
         *     | |___| | (_) \__ \  __/___) | || (_) | (__|   <
         *      \____|_|\___/|___/\___|____/ \__\___/ \___|_|\_\
         *
         */
        final JButton btnCloseStock = GUITools.createHyperlinkButton(
                "nursingrecords.inventory.stock.btnout.tooltip", SYSConst.icon22ledRedOn, null);
        btnCloseStock.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnCloseStock.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgCloseStock(stockInUse, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            // The prescription itself is not changed, but the stock in question.
                            // this information is requested by a single DB request every time
                            // the CP is created for that particular prescription.
                            // A new call to the createCP4 method will reuse the old
                            // CollapsiblePane and set a new TextContent to it.
                            // Now with the MedStock information.

                            // If this current stock was valid until the end of package
                            // it needs to be reread here.
                            if (prescription.isUntilEndOfPackage()) {
                                EntityManager em = OPDE.createEM();
                                Prescription myPrescription = em.merge(prescription);
                                em.refresh(myPrescription);
                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                            } else {
                                final CollapsiblePane myCP = createCP4(prescription);
                                GUITools.flashBackground(myCP, Color.YELLOW, 2);
                            }
                            buildPanel();
                        }
                    }
                });
            }
        });
        btnCloseStock.setEnabled(inventory != null && stockInUse != null && !stockInUse.isToBeClosedSoon());
        pnlMenu.add(btnCloseStock);

        /***
         *       ___                   ____  _             _
         *      / _ \ _ __   ___ _ __ / ___|| |_ ___   ___| | __
         *     | | | | '_ \ / _ \ '_ \\___ \| __/ _ \ / __| |/ /
         *     | |_| | |_) |  __/ | | |___) | || (_) | (__|   <
         *      \___/| .__/ \___|_| |_|____/ \__\___/ \___|_|\_\
         *           |_|
         */
        final JButton btnOpenStock = GUITools.createHyperlinkButton(
                "nursingrecords.inventory.stock.btnopen.tooltip", SYSConst.icon22ledGreenOn, null);
        btnOpenStock.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnOpenStock.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgOpenStock(prescription.getTradeForm(), resident, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            final CollapsiblePane myCP = createCP4(prescription);
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                        }
                    }
                });
            }
        });
        btnOpenStock.setEnabled(inventory != null && stockInUse == null && !prescription.isClosed());
        pnlMenu.add(btnOpenStock);

        /***
         *      ____  _     _      _____  __  __           _
         *     / ___|(_) __| | ___| ____|/ _|/ _| ___  ___| |_ ___
         *     \___ \| |/ _` |/ _ \  _| | |_| |_ / _ \/ __| __/ __|
         *      ___) | | (_| |  __/ |___|  _|  _|  __/ (__| |_\__ \
         *     |____/|_|\__,_|\___|_____|_| |_|  \___|\___|\__|___/
         *
         */
        final JButton btnEditSideEffects = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.edit.sideeffects", SYSConst.icon22sideeffects, null);
        btnEditSideEffects.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEditSideEffects.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(SYSConst.icon48sideeffects, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                MedProducts myProduct = em.merge(prescription.getTradeForm().getMedProduct());
                                myProduct.setSideEffects(o.toString().trim());
                                for (TradeForm tf : myProduct.getTradeforms()) {
                                    em.lock(em.merge(tf), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                                    for (MedPackage mp : tf.getPackages()) {
                                        em.lock(em.merge(mp), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                                    }
                                }
                                em.lock(myProduct, LockModeType.OPTIMISTIC);
                                em.getTransaction().commit();
                                reload();
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                }, "nursingrecords.prescription.edit.sideeffects",
                        prescription.getTradeForm().getMedProduct().getSideEffects(), null);
            }
        });
        // checked for acls
        btnEditSideEffects.setEnabled(prescription.hasMed()
                && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, "opde.medication"));
        pnlMenu.add(btnEditSideEffects);

        pnlMenu.add(new JSeparator());

        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */

        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Closure closure = null;
                if (!prescription.isClosed()) {
                    closure = new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final Prescription myPrescription = em.find(Prescription.class,
                                    prescription.getID());
                            em.close();
                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                        }
                    };
                }
                btnFiles.setEnabled(OPDE.isFTPworking());
                new DlgFiles(prescription, closure);
            }
        });

        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(prescription, 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);
                            Prescription myPrescription = em.merge(prescription);
                            em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

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

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

                            em.getTransaction().commit();

                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);

                        } 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(!prescription.isClosed());

        //            if (!prescription.getAttachedProcessConnections().isEmpty()) {
        //                JLabel lblNum = new JLabel(Integer.toString(prescription.getAttachedProcessConnections().size()), SYSConst.icon16redStar, SwingConstants.CENTER);
        //                lblNum.setFont(SYSConst.ARIAL10BOLD);
        //                lblNum.setForeground(Color.YELLOW);
        //                lblNum.setHorizontalTextPosition(SwingConstants.CENTER);
        //                DefaultOverlayable overlayableBtn = new DefaultOverlayable(btnProcess, lblNum, DefaultOverlayable.SOUTH_EAST);
        //                overlayableBtn.setOpaque(false);
        //                pnlMenu.add(overlayableBtn);
        //            } else {
        pnlMenu.add(btnProcess);
        //            }
    }
    return pnlMenu;
}

From source file:op.care.reports.PnlReport.java

private JPanel createContentPanel4Day(LocalDate day) {
    //        OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage("misc.msg.wait", progress, progressMax));
    //        progress++;

    final String key = DateFormat.getDateInstance().format(day.toDate());
    synchronized (contentmap) {
        if (contentmap.containsKey(key)) {
            return contentmap.get(key);
        }//  www . j  a v  a 2 s.  co  m
    }
    final JPanel dayPanel = new JPanel(new VerticalLayout());
    dayPanel.setOpaque(false);
    synchronized (valuecache) {
        if (!valuecache.containsKey(key)) {
            valuecache.put(key, NReportTools.getNReports4Day(resident, day));
        }

        int i = 0; // for zebra pattern
        for (final NReport nreport : valuecache.get(key)) {

            if (tbShowReplaced.isSelected() || !nreport.isObsolete()) {

                String title = SYSTools.toHTMLForScreen(SYSConst.html_table(SYSConst
                        .html_table_tr("<td width=\"800\" align=\"left\">" + "<b><p>"
                                + (nreport.isObsolete() ? SYSConst.html_16x16_Eraser_internal : "")
                                + (nreport.isReplacement() ? SYSConst.html_16x16_Edited_internal : "")
                                + DateFormat.getTimeInstance(DateFormat.SHORT).format(nreport.getPit()) + " "
                                + SYSTools.xx("misc.msg.Time.short") + ", " + nreport.getMinutes() + " "
                                + SYSTools.xx("misc.msg.Minute(s)") + ", " + nreport.getUser().getFullname()
                                + (nreport.getCommontags().isEmpty() ? ""
                                        : " " + CommontagsTools.getAsHTML(nreport.getCommontags(),
                                                SYSConst.html_16x16_tagPurple_internal))
                                + "</p></b></td>")
                        + SYSConst.html_table_tr("<td width=\"800\" align=\"left\">"
                                + SYSTools.replace(nreport.getText(), "\n", "<br/>", false) + "</td>"),
                        "0"));

                final DefaultCPTitle pnlSingle = new DefaultCPTitle(SYSTools.toHTMLForScreen(title), null);
                pnlSingle.getButton().addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        GUITools.showPopup(GUITools.getHTMLPopup(pnlSingle.getButton(),
                                NReportTools.getInfoAsHTML(nreport)), SwingConstants.NORTH);
                    }
                });

                if (!nreport.getAttachedFilesConnections().isEmpty()) {
                    /***
                     *      _     _         _____ _ _
                     *     | |__ | |_ _ __ |  ___(_) | ___  ___
                     *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
                     *     | |_) | |_| | | |  _| | | |  __/\__ \
                     *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
                     *
                     */
                    final JButton btnFiles = new JButton(
                            Integer.toString(nreport.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 = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                                    internalClassID) ? null : new Closure() {
                                        @Override
                                        public void execute(Object o) {
                                            EntityManager em = OPDE.createEM();
                                            final NReport myReport = em.find(NReport.class, nreport.getID());
                                            em.close();

                                            final String keyNewDay = DateFormat.getDateInstance()
                                                    .format(myReport.getPit());

                                            synchronized (contentmap) {
                                                contentmap.remove(keyNewDay);
                                            }
                                            synchronized (linemap) {
                                                linemap.remove(nreport);
                                            }

                                            synchronized (valuecache) {
                                                valuecache.get(keyNewDay).remove(nreport);
                                                valuecache.get(keyNewDay).add(myReport);
                                                Collections.sort(valuecache.get(keyNewDay));
                                            }

                                            createCP4Day(new LocalDate(myReport.getPit()));

                                            buildPanel();
                                            GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                                        }
                                    };
                            new DlgFiles(nreport, fileHandleClosure);
                        }
                    });
                    btnFiles.setEnabled(OPDE.isFTPworking());
                    pnlSingle.getRight().add(btnFiles);
                }

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

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

                                        em.getTransaction().commit();

                                        final String keyNewDay = DateFormat.getDateInstance()
                                                .format(myReport.getPit());

                                        synchronized (contentmap) {
                                            contentmap.remove(keyNewDay);
                                        }
                                        synchronized (linemap) {
                                            linemap.remove(nreport);
                                        }

                                        synchronized (valuecache) {
                                            valuecache.get(keyNewDay).remove(nreport);
                                            valuecache.get(keyNewDay).add(myReport);
                                            Collections.sort(valuecache.get(keyNewDay));
                                        }

                                        createCP4Day(new LocalDate(myReport.getPit()));

                                        buildPanel();
                                        GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                                    } 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(true);
                                        }
                                    } 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));
                    pnlSingle.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(nreport);
                        popup.getContentPane().add(pnl);
                        popup.setDefaultFocusComponent(pnl);

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

                JPanel zebra = new JPanel();
                zebra.setLayout(new BoxLayout(zebra, BoxLayout.LINE_AXIS));
                zebra.setOpaque(true);
                if (i % 2 == 0) {
                    zebra.setBackground(SYSConst.orange1[SYSConst.light2]);
                } else {
                    zebra.setBackground(Color.WHITE);
                }
                zebra.add(pnlSingle.getMain());
                i++;

                dayPanel.add(zebra);
                linemap.put(nreport, pnlSingle.getMain());
            }
        }
    }
    synchronized (contentmap) {
        contentmap.put(key, dayPanel);
    }
    return dayPanel;
}

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

private JPanel getMenu(final NursingProcess np) {

    final JPanel pnlMenu = new JPanel(new VerticalLayout());
    long numDFNs = DFNTools.getNumDFNs(np);

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***//from w  w w  .  j  a v  a 2 s . co m
         *       ____ _
         *      / ___| |__   __ _ _ __   __ _  ___
         *     | |   | '_ \ / _` | '_ \ / _` |/ _ \
         *     | |___| | | | (_| | | | | (_| |  __/
         *      \____|_| |_|\__,_|_| |_|\__, |\___|
         *                              |___/
         */
        JButton btnChange = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btnchange.tooltip",
                SYSConst.icon22playerPlay, null);
        btnChange.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnChange.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                NursingProcess template = np.clone();
                template.setTo(SYSConst.DATE_UNTIL_FURTHER_NOTICE);
                template.setUserOFF(null);
                template.setUserON(OPDE.getLogin().getUser());
                template.setNextEval(new DateTime().plusWeeks(4).toDate());
                new DlgNursingProcess(template, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                // Fetch the new Plan from the PAIR
                                NursingProcess myNewNP = em.merge(
                                        ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) o).getFirst());
                                NursingProcess myOldNP = em.merge(np);
                                em.lock(myOldNP, LockModeType.OPTIMISTIC);

                                // Close old NP
                                myOldNP.setUserOFF(em.merge(OPDE.getLogin().getUser()));
                                myOldNP.setTo(new DateTime().minusSeconds(1).toDate());
                                NPControl lastValidation = em
                                        .merge(new NPControl(myNewNP.getSituation(), myOldNP));
                                lastValidation.setLastValidation(true);
                                myOldNP.getEvaluations().add(lastValidation);

                                // Starts 1 second after the old one stopped
                                myNewNP.setFrom(new DateTime(myOldNP.getTo()).plusSeconds(1).toDate());

                                // Create new DFNs according to plan
                                DFNTools.generate(em, myNewNP.getInterventionSchedule(), new LocalDate(), true);
                                em.getTransaction().commit();

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

                                boolean reloadSearch = false;
                                for (Commontags ctag : myNewNP.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }

                                buildPanel();
                                GUITools.flashBackground(contenPanelMap.get(myNewNP), Color.YELLOW, 2);
                            } 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();
                            }
                            //                                reloadTable();
                        }
                    }
                });

            }
        });
        btnChange.setEnabled(!np.isClosed() && numDFNs != 0);
        pnlMenu.add(btnChange);

        /***
         *      ____        _   _                ____  _
         *     | __ ) _   _| |_| |_ ___  _ __   / ___|| |_ ___  _ __
         *     |  _ \| | | | __| __/ _ \| '_ \  \___ \| __/ _ \| '_ \
         *     | |_) | |_| | |_| || (_) | | | |  ___) | || (_) | |_) |
         *     |____/ \__,_|\__|\__\___/|_| |_| |____/ \__\___/| .__/
         *                                                     |_|
         */

        final JButton btnStop = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btnstop.tooltip",
                SYSConst.icon22stop, null);
        btnStop.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnStop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                JPanel dlg = new PnlEval(np, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            popup.hidePopup();

                            Pair<NursingProcess, String> result = (Pair<NursingProcess, String>) o;

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                NursingProcess myOldNP = em.merge(np);
                                em.lock(myOldNP, LockModeType.OPTIMISTIC);

                                myOldNP.setUserOFF(em.merge(OPDE.getLogin().getUser()));
                                myOldNP.setTo(new Date());
                                NPControl lastValidation = em.merge(new NPControl(result.getSecond(), myOldNP));
                                lastValidation.setLastValidation(true);
                                myOldNP.getEvaluations().add(lastValidation);

                                em.getTransaction().commit();

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

                                createCP4(myOldNP.getCategory());
                                buildPanel();
                                //                                    GUITools.flashBackground(contenPanelMap.get(myOldNP), Color.YELLOW, 2);

                            } 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();
                            }

                            OPDE.getDisplayManager()
                                    .addSubMessage(DisplayManager.getSuccessMessage(np.getTopic(), "closed"));
                            reloadDisplay();
                        }
                    }
                }, true);

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.getContentPane().add(dlg);
                popup.setOwner(btnStop);
                popup.removeExcludedComponent(btnStop);
                popup.setDefaultFocusComponent(dlg);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });
        btnStop.setEnabled(!np.isClosed() && numDFNs != 0);
        pnlMenu.add(btnStop);

        /***
         *      ____        _   _                _____    _ _ _
         *     | __ ) _   _| |_| |_ ___  _ __   | ____|__| (_) |_
         *     |  _ \| | | | __| __/ _ \| '_ \  |  _| / _` | | __|
         *     | |_) | |_| | |_| || (_) | | | | | |__| (_| | | |_
         *     |____/ \__,_|\__|\__\___/|_| |_| |_____\__,_|_|\__|
         *
         */

        JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btnedit.tooltip",
                SYSConst.icon22edit, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgNursingProcess(np, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                NursingProcess mynp = em.merge(
                                        ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) o).getFirst());
                                em.lock(mynp, LockModeType.OPTIMISTIC);
                                // Schedules to delete
                                for (InterventionSchedule is : ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) o)
                                        .getSecond()) {
                                    em.remove(em.merge(is));
                                }
                                // No unused DFNs to delete
                                Query delQuery = em.createQuery(
                                        "DELETE FROM DFN dfn WHERE dfn.nursingProcess = :nursingprocess ");
                                delQuery.setParameter("nursingprocess", mynp);
                                delQuery.executeUpdate();
                                // Create new DFNs according to plan
                                DFNTools.generate(em, mynp.getInterventionSchedule(), new LocalDate(), true);
                                em.getTransaction().commit();

                                boolean reloadSearch = false;
                                for (Commontags ctag : mynp.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }

                                // 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();
                                GUITools.flashBackground(contenPanelMap.get(mynp), Color.YELLOW, 2);

                            } 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();
                            }
                            //                                reloadTable();
                        }
                    }
                });
            }
        });
        btnEdit.setEnabled(!np.isClosed() && numDFNs == 0);
        pnlMenu.add(btnEdit);
    }

    /***
     *      ____        _   _                ____       _      _
     *     | __ ) _   _| |_| |_ ___  _ __   |  _ \  ___| | ___| |_ ___
     *     |  _ \| | | | __| __/ _ \| '_ \  | | | |/ _ \ |/ _ \ __/ _ \
     *     | |_) | |_| | |_| || (_) | | | | | |_| |  __/ |  __/ ||  __/
     *     |____/ \__,_|\__|\__\___/|_| |_| |____/ \___|_|\___|\__\___|
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) { // => ACL_MATRIX
        JButton btnDelete = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btndelete.tooltip",
                SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><b>" + np.getTopic() + "</b><br/>"
                        + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o.equals(JOptionPane.YES_OPTION)) {
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        NursingProcess myOldNP = em.merge(np);
                                        em.lock(myOldNP, LockModeType.OPTIMISTIC);

                                        // DFNs to delete
                                        Query delQuery = em.createQuery(
                                                "DELETE FROM DFN dfn WHERE dfn.nursingProcess = :nursingprocess ");
                                        delQuery.setParameter("nursingprocess", myOldNP);
                                        //                                    delQuery.setParameter("status", DFNTools.STATE_OPEN);
                                        delQuery.executeUpdate();

                                        em.remove(myOldNP);
                                        em.getTransaction().commit();

                                        // Refresh Display
                                        valuecache.get(np.getCategory()).remove(np);
                                        contenPanelMap.remove(np);

                                        createCP4(myOldNP.getCategory());
                                        buildPanel();

                                        OPDE.getDisplayManager().addSubMessage(
                                                DisplayManager.getSuccessMessage(np.getTopic(), "deleted"));

                                    } 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();
                                    }
                                }
                            }
                        });
            }
        });
        btnDelete.setEnabled(!np.isClosed() && numDFNs == 0);
        pnlMenu.add(btnDelete);
    }

    /***
     *      ____  _         _____            _
     *     | __ )| |_ _ __ | ____|_   ____ _| |
     *     |  _ \| __| '_ \|  _| \ \ / / _` | |
     *     | |_) | |_| | | | |___ \ V / (_| | |
     *     |____/ \__|_| |_|_____| \_/ \__,_|_|
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        final JButton btnEval = GUITools.createHyperlinkButton("nursingrecords.nursingprocess.btneval.tooltip",
                SYSConst.icon22redo, null);
        btnEval.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEval.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                JPanel dlg = new PnlEval(np, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            popup.hidePopup();

                            Pair<NursingProcess, String> result = (Pair<NursingProcess, String>) o;

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                NursingProcess evaluatedNP = em.merge(result.getFirst());
                                em.lock(evaluatedNP, LockModeType.OPTIMISTIC);

                                NPControl newEvaluation = em
                                        .merge(new NPControl(result.getSecond(), evaluatedNP));
                                evaluatedNP.getEvaluations().add(newEvaluation);

                                em.getTransaction().commit();

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

                                createCP4(evaluatedNP.getCategory());
                                buildPanel();
                                GUITools.flashBackground(contenPanelMap.get(evaluatedNP), Color.YELLOW, 2);

                            } 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();
                            }

                            OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                                    SYSTools.xx("nursingrecords.nursingprocess.success.neweval")));
                            reloadDisplay();
                        }
                    }
                }, false);

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.getContentPane().add(dlg);
                popup.setOwner(btnEval);
                popup.removeExcludedComponent(btnEval);
                popup.setDefaultFocusComponent(dlg);

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

        btnEval.setEnabled(!np.isClosed());
        pnlMenu.add(btnEval);

        /***
         *      _     _       _____  _    ____
         *     | |__ | |_ _ _|_   _|/ \  / ___|___
         *     | '_ \| __| '_ \| | / _ \| |  _/ __|
         *     | |_) | |_| | | | |/ ___ \ |_| \__ \
         *     |_.__/ \__|_| |_|_/_/   \_\____|___/
         *
         */
        final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple,
                null);
        btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnTAGs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                final JPanel pnl = new JPanel(new BorderLayout(5, 5));
                final PnlCommonTags pnlCommonTags = new PnlCommonTags(np.getCommontags(), true, 3);
                pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER);
                JButton btnApply = new JButton(SYSConst.icon22apply);
                pnl.add(btnApply, BorderLayout.SOUTH);
                btnApply.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        EntityManager em = OPDE.createEM();
                        try {

                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            NursingProcess myNP = em.merge(np);
                            em.lock(myNP, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            myNP.getCommontags().clear();
                            for (Commontags commontag : pnlCommonTags.getListSelectedTags()) {
                                myNP.getCommontags().add(em.merge(commontag));
                            }

                            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()));

                            boolean reloadSearch = false;
                            for (Commontags ctag : myNP.getCommontags()) {
                                if (!listUsedCommontags.contains(ctag)) {
                                    listUsedCommontags.add(ctag);
                                    reloadSearch = true;
                                }
                            }
                            if (reloadSearch) {
                                prepareSearchArea();
                            }

                            createCP4(myNP.getCategory());
                            buildPanel();
                            GUITools.flashBackground(contenPanelMap.get(myNP), Color.YELLOW, 2);

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            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 (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnTAGs);
                popup.removeExcludedComponent(btnTAGs);
                pnl.setPreferredSize(new Dimension(350, 150));
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);

            }
        });
        btnTAGs.setEnabled(!np.isClosed());
        pnlMenu.add(btnTAGs);

        pnlMenu.add(new JSeparator());

        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        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());
        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        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(!np.isClosed());
        pnlMenu.add(btnProcess);

    }
    return pnlMenu;
}

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

private java.util.List<Component> addCommands() {

    java.util.List<Component> list = new ArrayList<Component>();

    /***//from w  w w .j  a va2 s  .c o  m
     *      _     _            _       _     _
     *     | |__ | |_ _ __    / \   __| | __| |
     *     | '_ \| __| '_ \  / _ \ / _` |/ _` |
     *     | |_) | |_| | | |/ ___ \ (_| | (_| |
     *     |_.__/ \__|_| |_/_/   \_\__,_|\__,_|
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {

        final JideButton btnAdd = GUITools.createHyperlinkButton(SYSTools.xx("nursingrecords.dfn.btnadd"),
                SYSConst.icon22add, null);
        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (!resident.isActive()) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                    return;
                }

                final JidePopup popup = new JidePopup();
                popup.setMovable(false);
                PnlSelectIntervention pnl = new PnlSelectIntervention(new Closure() {
                    @Override
                    public void execute(Object o) {
                        popup.hidePopup();
                        if (o != null) {
                            Object[] objects = (Object[]) o;
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                for (Object obj : objects) {
                                    Intervention intervention = em.merge((Intervention) obj);
                                    DFN dfn = em.merge(new DFN(resident, intervention));

                                    // Set Target and Actual according to the setting of JDCDate
                                    DateTime now = new DateTime();
                                    DateMidnight onDemandPIT = new DateMidnight(jdcDate.getDate());
                                    DateTime newDateTime = onDemandPIT.toDateTime()
                                            .plusHours(now.getHourOfDay()).plusMinutes(now.getMinuteOfHour())
                                            .plusSeconds(now.getSecondOfMinute());
                                    dfn.setSoll(newDateTime.toDate());
                                    dfn.setIst(newDateTime.toDate());

                                    CollapsiblePane cp1 = createCP4(dfn);
                                    synchronized (mapDFN2Pane) {
                                        mapDFN2Pane.put(dfn, cp1);
                                    }
                                    synchronized (mapShift2DFN) {
                                        mapShift2DFN.get(dfn.getShift()).add(dfn);
                                    }
                                }

                                em.getTransaction().commit();

                                CollapsiblePane cp2 = createCP4(DFNTools.SHIFT_ON_DEMAND);
                                synchronized (mapShift2Pane) {
                                    mapShift2Pane.put(DFNTools.SHIFT_ON_DEMAND, cp2);
                                }
                                buildPanel(false);
                                try {
                                    synchronized (mapShift2Pane) {
                                        mapShift2Pane.get(DFNTools.SHIFT_ON_DEMAND).setCollapsed(false);
                                    }
                                } catch (PropertyVetoException e) {
                                    OPDE.debug(e);
                                }

                            } 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();
                            }
                        }
                    }
                });
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.getContentPane().add(pnl);
                popup.setOwner(btnAdd);
                popup.removeExcludedComponent(pnl);
                popup.setDefaultFocusComponent(pnl);
                GUITools.showPopup(popup, SwingConstants.NORTH);
            }
        });
        list.add(btnAdd);

    }

    final JideButton printPrescription = GUITools.createHyperlinkButton("nursingrecords.dfn.print",
            SYSConst.icon22print2, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {

                    String html = "";

                    synchronized (mapShift2DFN) {
                        html += "<h1 id=\"fonth1\" >" + ResidentTools.getFullName(resident) + "</h1>";
                        html += SYSConst.html_h2(SYSTools.xx("nursingrecords.bhp") + ": "
                                + SYSConst.html_bold(DateFormat.getDateInstance().format(jdcDate.getDate())));

                        for (Byte shift : new Byte[] { DFNTools.SHIFT_ON_DEMAND, DFNTools.SHIFT_VERY_EARLY,
                                DFNTools.SHIFT_EARLY, DFNTools.SHIFT_LATE, DFNTools.SHIFT_VERY_LATE }) {
                            html += DFNTools.getDFNsAsHTMLtable(mapShift2DFN.get(shift));
                        }
                    }

                    SYSFilesTools.print(html, true);
                }
            });
    list.add(printPrescription);
    return list;
}

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

private void addValue(final ResValueTypes vtype) {

    final String keyType = vtype.getID() + ".xtypes";

    new DlgValue(new ResValue(resident, vtype), DlgValue.MODE_NEW, new Closure() {
        @Override//from  w w w .j a v a  2s .  c  o  m
        public void execute(Object o) {
            ResValue myValue = null;

            if (o != null) {

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();
                    myValue = em.merge((ResValue) o);
                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                    em.getTransaction().commit();

                } 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();
                }

                if (myValue != null) {

                    DateTime dt = new DateTime(myValue.getPit());

                    //                        final String keyDay = vtype.getID() + ".xtypes." + dt.toLocalDate() + ".day";
                    final String keyYear = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                            + ".year";
                    //                        final LocalDate week = SYSCalendar.max(SYSCalendar.bow(dt.toLocalDate()), new LocalDate(dt.getYear(), 1, 1));
                    //                        final String keyWeek = vtype.getID() + ".xtypes." + week + ".week";

                    synchronized (mapType2Values) {

                        if (!mapType2Values.containsKey(keyYear)) {
                            mapType2Values.put(keyYear,
                                    ResValueTools.getResValues(resident, vtype, dt.getYear()));
                        }

                        if (!mapType2Values.get(keyYear).contains(myValue)) {
                            mapType2Values.get(keyYear).add(myValue);
                            Collections.sort(mapType2Values.get(keyYear));
                        }
                        //                            }
                    }

                    try {
                        // eh ?
                        synchronized (cpMap) {
                            cpMap.get(keyType).setCollapsible(true);

                            if (cpMap.get(keyType).isCollapsed()) {
                                cpMap.get(keyType).setCollapsed(false);
                            }
                            if (cpMap.containsKey(keyYear) && cpMap.get(keyYear).isCollapsed()) {
                                cpMap.get(keyYear).setCollapsed(false);
                            }

                        }
                    } catch (PropertyVetoException e) {
                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                    }

                    createCP4Type(vtype);

                    buildPanel();

                    final ResValue myValueCopy = myValue;
                    synchronized (linemap) {
                        GUITools.scroll2show(jspValues, linemap.get(myValueCopy), cpsValues, new Closure() {
                            @Override
                            public void execute(Object o) {
                                GUITools.flashBackground(linemap.get(myValueCopy), Color.YELLOW, 2);
                            }
                        });
                    }

                }
            }

        }
    });
}

From source file:op.allowance.PnlAllowance.java

private PnlTX getPnlTX(Resident resident, final Allowance allowance) {
    final BigDecimal editAmount = allowance != null ? allowance.getAmount() : null;
    final Allowance allow = (allowance == null ? new Allowance(resident) : allowance);

    return new PnlTX(allow, new Closure() {
        @Override/*from   w  w  w  . j a  v  a 2s .com*/
        public void execute(Object o) {
            if (o != null) {

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();
                    final Allowance myAllowance = em.merge((Allowance) o);
                    em.lock(em.merge(myAllowance.getResident()), LockModeType.OPTIMISTIC);
                    em.getTransaction().commit();

                    DateTime txDate = new DateTime(myAllowance.getPit());

                    final String keyResident = myAllowance.getResident().getRID();
                    final String keyYear = myAllowance.getResident().getRID() + "-" + txDate.getYear();
                    final String keyMonth = myAllowance.getResident().getRID() + "-" + txDate.getYear() + "-"
                            + txDate.getMonthOfYear();

                    if (!lstResidents.contains(myAllowance.getResident())) {
                        lstResidents.add(myAllowance.getResident());
                        Collections.sort(lstResidents);
                    }

                    if (!cashmap.containsKey(keyMonth)) {
                        cashmap.put(keyMonth,
                                AllowanceTools.getMonth(myAllowance.getResident(), myAllowance.getPit()));
                    } else {

                        if (cashmap.get(keyMonth).contains(myAllowance)) {
                            cashmap.get(keyMonth).remove(myAllowance);
                        }
                        cashmap.get(keyMonth).add(myAllowance);

                        Collections.sort(cashmap.get(keyMonth));
                    }

                    // little trick to fix the carries
                    if (editAmount != null) {
                        updateCarrySums(myAllowance.getResident(), new LocalDate(myAllowance.getPit()),
                                editAmount.negate());
                    }
                    // add the new / edited amount
                    updateCarrySums(myAllowance);

                    createCP4(myAllowance.getResident());

                    try {
                        if (cpMap.get(keyResident).isCollapsed())
                            cpMap.get(keyResident).setCollapsed(false);
                        if (cpMap.get(keyYear).isCollapsed())
                            cpMap.get(keyYear).setCollapsed(false);
                        if (cpMap.get(keyMonth).isCollapsed())
                            cpMap.get(keyMonth).setCollapsed(false);
                    } catch (PropertyVetoException e) {
                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                    }

                    buildPanel();

                    GUITools.scroll2show(jspCash, cpMap.get(keyMonth), cpsCash, new Closure() {
                        @Override
                        public void execute(Object o) {
                            GUITools.flashBackground(linemap.get(myAllowance), Color.YELLOW, 2);
                        }
                    });

                } 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();
                }

            }
        }
    });
}

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

private JPanel createContentPanel4(final MedStock stock) {
    //        final String key = stock.getID() + ".xstock";

    //        if (!contentmap.containsKey(key)) {

    final JPanel pnlTX = new JPanel(new VerticalLayout());
    //            pnlTX.setLayout(new BoxLayout(pnlTX, BoxLayout.PAGE_AXIS));

    pnlTX.setOpaque(true);/*from www .ja  v a  2 s  .  c om*/
    //        pnlTX.setBackground(Color.white);
    synchronized (lstInventories) {
        pnlTX.setBackground(getColor(SYSConst.light2, lstInventories.indexOf(stock.getInventory()) % 2 != 0));
    }

    /***
     *         _       _     _ _______  __
     *        / \   __| | __| |_   _\ \/ /
     *       / _ \ / _` |/ _` | | |  \  /
     *      / ___ \ (_| | (_| | | |  /  \
     *     /_/   \_\__,_|\__,_| |_| /_/\_\
     *
     */
    JideButton btnAddTX = GUITools.createHyperlinkButton("nursingrecords.inventory.newmedstocktx",
            SYSConst.icon22add, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new DlgTX(new MedStockTransaction(stock, BigDecimal.ONE,
                            MedStockTransactionTools.STATE_EDIT_MANUAL), new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (o != null) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            final MedStockTransaction myTX = (MedStockTransaction) em.merge(o);
                                            MedStock myStock = em.merge(stock);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                            em.lock(em.merge(myTX.getStock().getInventory().getResident()),
                                                    LockModeType.OPTIMISTIC);
                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());

                                            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 (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            });
                }
            });
    btnAddTX.setEnabled(!stock.isClosed());
    pnlTX.add(btnAddTX);

    /***
     *      ____  _                           _ _   _______  __
     *     / ___|| |__   _____      __   __ _| | | |_   _\ \/ /___
     *     \___ \| '_ \ / _ \ \ /\ / /  / _` | | |   | |  \  // __|
     *      ___) | | | | (_) \ V  V /  | (_| | | |   | |  /  \\__ \
     *     |____/|_| |_|\___/ \_/\_/    \__,_|_|_|   |_| /_/\_\___/
     *
     */
    OPDE.getMainframe().setBlocked(true);
    OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

    SwingWorker worker = new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {
            int progress = 0;

            List<MedStockTransaction> listTX = MedStockTransactionTools.getAll(stock);
            OPDE.getDisplayManager().setProgressBarMessage(
                    new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));

            BigDecimal rowsum = MedStockTools.getSum(stock);
            //                BigDecimal rowsum = MedStockTools.getSum(stock);
            //                Collections.sort(stock.getStockTransaction());
            for (final MedStockTransaction tx : listTX) {
                progress++;
                OPDE.getDisplayManager().setProgressBarMessage(
                        new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));
                String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                .format(tx.getPit())
                        + "<br/>[" + tx.getID() + "]" + "</td>" + "<td width=\"200\" align=\"center\">"
                        + SYSTools.catchNull(tx.getText(), "--") + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + NumberFormat.getNumberInstance().format(tx.getAmount()) + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                        + NumberFormat.getNumberInstance().format(rowsum)
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" +

                        (stock.getTradeForm().isWeightControlled() ? "<td width=\"100\" align=\"right\">"
                                + NumberFormat.getNumberInstance().format(tx.getWeight()) + "g" + "</td>" : "")
                        +

                        "<td width=\"100\" align=\"left\">" + SYSTools.anonymizeUser(tx.getUser().getUID())
                        + "</td>" + "</tr>" + "</table>" +

                        "</font></html>";

                rowsum = rowsum.subtract(tx.getAmount());

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

                //                pnlTitle.getLeft().addMouseListener();

                if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) {
                    /***
                     *      ____       _ _______  __
                     *     |  _ \  ___| |_   _\ \/ /
                     *     | | | |/ _ \ | | |  \  /
                     *     | |_| |  __/ | | |  /  \
                     *     |____/ \___|_| |_| /_/\_\
                     *
                     */
                    final JButton btnDelTX = new JButton(SYSConst.icon22delete);
                    btnDelTX.setPressedIcon(SYSConst.icon22deletePressed);
                    btnDelTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnDelTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnDelTX.setContentAreaFilled(false);
                    btnDelTX.setBorder(null);
                    btnDelTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btndelete.tooltip"));
                    btnDelTX.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>"
                                    + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                            .format(tx.getPit())
                                    + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                    + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete,
                                    new Closure() {
                                        @Override
                                        public void execute(Object answer) {
                                            if (answer.equals(JOptionPane.YES_OPTION)) {
                                                EntityManager em = OPDE.createEM();
                                                try {
                                                    em.getTransaction().begin();

                                                    MedStockTransaction myTX = em.merge(tx);
                                                    MedStock myStock = em.merge(stock);
                                                    em.lock(em.merge(
                                                            myTX.getStock().getInventory().getResident()),
                                                            LockModeType.OPTIMISTIC);
                                                    em.lock(myStock, LockModeType.OPTIMISTIC);
                                                    em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                                    em.remove(myTX);
                                                    //                                                myStock.getStockTransaction().remove(myTX);
                                                    em.getTransaction().commit();

                                                    //                                                synchronized (lstInventories) {
                                                    //                                                    int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                    //                                                    int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                    //                                                }

                                                    //                                                synchronized (linemap) {
                                                    //                                                    linemap.remove(myTX);
                                                    //                                                }

                                                    createCP4(myStock.getInventory());

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

                        }
                    });
                    btnDelTX.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnDelTX);
                }

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>"
                                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                                .format(tx.getPit())
                                        + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                        + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                MedStock myStock = em.merge(stock);
                                                final MedStockTransaction myOldTX = em.merge(tx);

                                                myOldTX.setState(MedStockTransactionTools.STATE_CANCELLED);
                                                final MedStockTransaction myNewTX = em
                                                        .merge(new MedStockTransaction(myStock,
                                                                myOldTX.getAmount().negate(),
                                                                MedStockTransactionTools.STATE_CANCEL_REC));
                                                myOldTX.setText(SYSTools.xx("misc.msg.reversedBy") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myNewTX.getPit()));
                                                myNewTX.setText(SYSTools.xx("misc.msg.reversalFor") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myOldTX.getPit()));

                                                //                                            myStock.getStockTransaction().add(myNewTX);
                                                //                                            myStock.getStockTransaction().remove(tx);
                                                //                                            myStock.getStockTransaction().add(myOldTX);

                                                em.lock(em
                                                        .merge(myNewTX.getStock().getInventory().getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myStock, LockModeType.OPTIMISTIC);
                                                em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                                em.getTransaction().commit();

                                                //                                            synchronized (lstInventories) {
                                                //                                                int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                //                                                int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                //                                            }

                                                //                                            synchronized (linemap) {
                                                //                                                linemap.remove(tx);
                                                //                                            }
                                                createCP4(myStock.getInventory());
                                                buildPanel();
                                                //                                            SwingUtilities.invokeLater(new Runnable() {
                                                //                                                @Override
                                                //                                                public void run() {
                                                //                                                    synchronized (linemap) {
                                                //                                                        GUITools.flashBackground(linemap.get(myOldTX), Color.RED, 2);
                                                //                                                        GUITools.flashBackground(linemap.get(myNewTX), Color.YELLOW, 2);
                                                //                                                    }
                                                //                                                }
                                                //                                            });
                                            } 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();
                                            }
                                        }
                                    }
                                });

                    }
                });
                btnUndoTX.setEnabled(!stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                        || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                pnlTitle.getRight().add(btnUndoTX);

                if (stock.getTradeForm().isWeightControlled() && OPDE.getAppInfo()
                        .isAllowedTo(InternalClassACL.MANAGER, "nursingrecords.inventory")) {
                    /***
                     *               _ __        __   _       _     _
                     *      ___  ___| |\ \      / /__(_) __ _| |__ | |_
                     *     / __|/ _ \ __\ \ /\ / / _ \ |/ _` | '_ \| __|
                     *     \__ \  __/ |_ \ V  V /  __/ | (_| | | | | |_
                     *     |___/\___|\__| \_/\_/ \___|_|\__, |_| |_|\__|
                     *                                  |___/
                     */
                    final JButton btnSetWeight = new JButton(SYSConst.icon22scales);
                    btnSetWeight.setPressedIcon(SYSConst.icon22Pressed);
                    btnSetWeight.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnSetWeight.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnSetWeight.setContentAreaFilled(false);
                    btnSetWeight.setBorder(null);
                    btnSetWeight.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                    btnSetWeight.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {

                            BigDecimal weight;
                            new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (!SYSTools.catchNull(o).isEmpty()) {
                                        BigDecimal weight = (BigDecimal) o;

                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();
                                            MedStock myStock = em.merge(stock);
                                            final MedStockTransaction myTX = em.merge(tx);
                                            em.lock(myTX, LockModeType.OPTIMISTIC);
                                            myTX.setWeight(weight);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());
                                            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 (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            }, "nursingrecords.bhp.weight",
                                    NumberFormat.getNumberInstance().format(tx.getWeight()),
                                    new Validator<BigDecimal>() {
                                        @Override
                                        public boolean isValid(String value) {
                                            BigDecimal bd = parse(value);
                                            return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                                        }

                                        @Override
                                        public BigDecimal parse(String text) {
                                            return SYSTools.parseDecimal(text);
                                        }
                                    });

                        }
                    });
                    btnSetWeight.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_CREDIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnSetWeight);
                }

                pnlTX.add(pnlTitle.getMain());
            }

            return null;
        }

        @Override
        protected void done() {
            OPDE.getDisplayManager().setProgressBarMessage(null);
            OPDE.getMainframe().setBlocked(false);
        }
    };
    worker.execute();

    return pnlTX;
}

From source file:op.care.reports.PnlReport.java

private JPanel getMenu(final NReport nreport) {

    JPanel pnlMenu = new JPanel(new VerticalLayout());

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***/*from  w  w w  .  ja  v  a  2s.  c o  m*/
         *      _____    _ _ _
         *     | ____|__| (_) |_
         *     |  _| / _` | | __|
         *     | |__| (_| | | |_
         *     |_____\__,_|_|\__|
         *
         */
        final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.reports.btnEdit.tooltip",
                SYSConst.icon22edit3, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgReport(nreport.clone(), new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                final NReport newReport = em.merge((NReport) o);
                                NReport oldReport = em.merge(nreport);
                                em.lock(oldReport, LockModeType.OPTIMISTIC);
                                newReport.setReplacementFor(oldReport);

                                for (SYSNR2FILE oldAssignment : oldReport.getAttachedFilesConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldReport.getAttachedFilesConnections().clear();
                                for (SYSNR2PROCESS oldAssignment : oldReport.getAttachedQProcessConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldReport.getAttachedQProcessConnections().clear();

                                oldReport.setEditedBy(em.merge(OPDE.getLogin().getUser()));
                                oldReport.setEditDate(new Date());
                                oldReport.setReplacedBy(newReport);

                                em.getTransaction().commit();

                                final String keyNewDay = DateFormat.getDateInstance()
                                        .format(newReport.getPit());
                                final String keyOldDay = DateFormat.getDateInstance()
                                        .format(oldReport.getPit());

                                synchronized (contentmap) {
                                    contentmap.remove(keyNewDay);
                                    contentmap.remove(keyOldDay);
                                }
                                synchronized (linemap) {
                                    linemap.remove(oldReport);
                                }

                                synchronized (valuecache) {
                                    valuecache.get(keyOldDay).remove(nreport);
                                    valuecache.get(keyOldDay).add(oldReport);
                                    Collections.sort(valuecache.get(keyOldDay));

                                    if (valuecache.containsKey(keyNewDay)) {
                                        valuecache.get(keyNewDay).add(newReport);
                                        Collections.sort(valuecache.get(keyNewDay));
                                    }
                                }

                                synchronized (listUsedCommontags) {
                                    boolean reloadSearch = false;
                                    for (Commontags ctag : newReport.getCommontags()) {
                                        if (!listUsedCommontags.contains(ctag)) {
                                            listUsedCommontags.add(ctag);
                                            reloadSearch = true;
                                        }
                                    }
                                    if (reloadSearch) {
                                        prepareSearchArea();
                                    }
                                }

                                if (minmax.isAfter(new DateTime(newReport.getPit()))) {
                                    minmax.setStart(new DateTime(newReport.getPit()));
                                }

                                if (minmax.isBefore(new DateTime(newReport.getPit()))) {
                                    minmax.setEnd(new DateTime(newReport.getPit()));
                                }

                                createCP4Day(new LocalDate(oldReport.getPit()));
                                createCP4Day(new LocalDate(newReport.getPit()));

                                buildPanel();
                                GUITools.scroll2show(jspReports, cpMap.get(keyNewDay), cpsReports,
                                        new Closure() {
                                            @Override
                                            public void execute(Object o) {
                                                GUITools.flashBackground(linemap.get(newReport), Color.YELLOW,
                                                        2);
                                            }
                                        });
                            } 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(true);
                                }
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                });
            }
        });
        btnEdit.setEnabled(NReportTools.isChangeable(nreport));
        pnlMenu.add(btnEdit);
        /***
         *      ____       _      _
         *     |  _ \  ___| | ___| |_ ___
         *     | | | |/ _ \ |/ _ \ __/ _ \
         *     | |_| |  __/ |  __/ ||  __/
         *     |____/ \___|_|\___|\__\___|
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton("nursingrecords.reports.btnDelete.tooltip",
                SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(
                        SYSTools.xx("misc.questions.delete1") + "<br/><i>"
                                + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT).format(
                                        nreport.getPit())
                                + "</i><br/>" + SYSTools.xx("misc.questions.delete2"),
                        SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object answer) {
                                if (answer.equals(JOptionPane.YES_OPTION)) {
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        final NReport delReport = em.merge(nreport);
                                        em.lock(delReport, LockModeType.OPTIMISTIC);
                                        delReport.setDeletedBy(em.merge(OPDE.getLogin().getUser()));
                                        for (SYSNR2FILE oldAssignment : delReport
                                                .getAttachedFilesConnections()) {
                                            em.remove(oldAssignment);
                                        }
                                        delReport.getAttachedFilesConnections().clear();
                                        for (SYSNR2PROCESS oldAssignment : delReport
                                                .getAttachedQProcessConnections()) {
                                            em.remove(oldAssignment);
                                        }
                                        delReport.getAttachedQProcessConnections().clear();
                                        em.getTransaction().commit();

                                        final String keyDay = DateFormat.getDateInstance()
                                                .format(delReport.getPit());

                                        synchronized (contentmap) {
                                            contentmap.remove(keyDay);
                                        }
                                        synchronized (linemap) {
                                            linemap.remove(delReport);
                                        }

                                        synchronized (valuecache) {
                                            valuecache.get(keyDay).remove(nreport);
                                            valuecache.get(keyDay).add(delReport);
                                            Collections.sort(valuecache.get(keyDay));
                                        }

                                        createCP4Day(new LocalDate(delReport.getPit()));

                                        buildPanel();
                                        if (tbShowReplaced.isSelected()) {
                                            GUITools.flashBackground(linemap.get(delReport), Color.YELLOW, 2);
                                        }
                                    } 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(true);
                                        }
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }

                                }
                            }
                        });
            }
        });
        btnDelete.setEnabled(NReportTools.isChangeable(nreport));
        pnlMenu.add(btnDelete);

        /***
         *      _     _       _____  _    ____
         *     | |__ | |_ _ _|_   _|/ \  / ___|___
         *     | '_ \| __| '_ \| | / _ \| |  _/ __|
         *     | |_) | |_| | | | |/ ___ \ |_| \__ \
         *     |_.__/ \__|_| |_|_/_/   \_\____|___/
         *
         */
        final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple,
                null);
        btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnTAGs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                final JPanel pnl = new JPanel(new BorderLayout(5, 5));
                final PnlCommonTags pnlCommonTags = new PnlCommonTags(nreport.getCommontags(), true, 3);
                pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER);
                JButton btnApply = new JButton(SYSConst.icon22apply);
                pnl.add(btnApply, BorderLayout.SOUTH);
                btnApply.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            final NReport myReport = em.merge(nreport);
                            em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            myReport.getCommontags().clear();
                            for (Commontags commontag : pnlCommonTags.getListSelectedTags()) {
                                myReport.getCommontags().add(em.merge(commontag));
                            }

                            em.getTransaction().commit();

                            final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit());

                            synchronized (contentmap) {
                                contentmap.remove(keyNewDay);
                            }
                            synchronized (linemap) {
                                linemap.remove(nreport);
                            }

                            synchronized (valuecache) {
                                valuecache.get(keyNewDay).remove(nreport);
                                valuecache.get(keyNewDay).add(myReport);
                                Collections.sort(valuecache.get(keyNewDay));
                            }

                            synchronized (listUsedCommontags) {
                                boolean reloadSearch = false;
                                for (Commontags ctag : myReport.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }
                            }

                            createCP4Day(new LocalDate(myReport.getPit()));

                            buildPanel();
                            GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            } else {
                                reloadDisplay(true);
                            }
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnTAGs);
                popup.removeExcludedComponent(btnTAGs);
                pnl.setPreferredSize(new Dimension(350, 150));
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);

            }
        });
        btnTAGs.setEnabled(NReportTools.isChangeable(nreport) && NReportTools.isMine(nreport));
        pnlMenu.add(btnTAGs);

        /***
         *      _     _         __  __ _             _
         *     | |__ | |_ _ __ |  \/  (_)_ __  _   _| |_ ___  ___
         *     | '_ \| __| '_ \| |\/| | | '_ \| | | | __/ _ \/ __|
         *     | |_) | |_| | | | |  | | | | | | |_| | ||  __/\__ \
         *     |_.__/ \__|_| |_|_|  |_|_|_| |_|\__,_|\__\___||___/
         *
         */
        final JButton btnMinutes = GUITools.createHyperlinkButton("nursingrecords.reports.btnminutes.tooltip",
                SYSConst.icon22clock, null);
        btnMinutes.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMinutes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {

                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);
                                    NReport myReport = em.merge(nreport);
                                    em.lock(myReport, LockModeType.OPTIMISTIC);

                                    myReport.setMinutes((Integer) o);
                                    myReport.setEditDate(new Date());

                                    em.getTransaction().commit();

                                    final String keyNewDay = DateFormat.getDateInstance()
                                            .format(myReport.getPit());

                                    synchronized (contentmap) {
                                        contentmap.remove(keyNewDay);
                                    }
                                    synchronized (linemap) {
                                        linemap.remove(nreport);
                                    }

                                    synchronized (valuecache) {
                                        valuecache.get(keyNewDay).remove(nreport);
                                        valuecache.get(keyNewDay).add(myReport);
                                        Collections.sort(valuecache.get(keyNewDay));
                                    }

                                    createCP4Day(new LocalDate(myReport.getPit()));

                                    buildPanel();
                                    GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                                } 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(true);
                                    }
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                            }
                        });

                menu.show(btnMinutes, 0, btnMinutes.getHeight());
            }
        });
        btnMinutes.setEnabled(!nreport.isObsolete() && NReportTools.isMine(nreport));
        pnlMenu.add(btnMinutes);

        pnlMenu.add(new JSeparator());

        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Closure fileHandleClosure = nreport.isObsolete() ? null : new Closure() {
                    @Override
                    public void execute(Object o) {
                        EntityManager em = OPDE.createEM();
                        final NReport myReport = em.find(NReport.class, nreport.getID());
                        em.close();

                        final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit());

                        synchronized (contentmap) {
                            contentmap.remove(keyNewDay);
                        }
                        synchronized (linemap) {
                            linemap.remove(nreport);
                        }

                        synchronized (valuecache) {
                            valuecache.get(keyNewDay).remove(nreport);
                            valuecache.get(keyNewDay).add(myReport);
                            Collections.sort(valuecache.get(keyNewDay));
                        }

                        createCP4Day(new LocalDate(myReport.getPit()));

                        buildPanel();
                        GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                    }
                };
                new DlgFiles(nreport, fileHandleClosure);
            }
        });
        btnFiles.setEnabled(OPDE.isFTPworking());
        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(nreport, 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);
                            NReport myReport = em.merge(nreport);
                            em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

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

                            em.getTransaction().commit();

                            final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit());

                            synchronized (contentmap) {
                                contentmap.remove(keyNewDay);
                            }
                            synchronized (linemap) {
                                linemap.remove(nreport);
                            }

                            synchronized (valuecache) {
                                valuecache.get(keyNewDay).remove(nreport);
                                valuecache.get(keyNewDay).add(myReport);
                                Collections.sort(valuecache.get(keyNewDay));
                            }

                            createCP4Day(new LocalDate(myReport.getPit()));

                            buildPanel();
                            GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                        } 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(true);
                            }
                        } 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();
                        }

                    }
                });
            }
        });
        pnlMenu.add(btnProcess);

    }
    return pnlMenu;
}

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

private JPanel getMenu(final MedStock stock) {
    final String key = stock.getID() + ".xstock";
    JPanel pnlMenu = new JPanel(new VerticalLayout());
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) {
        /***//from w  w w.j av  a  2  s . c  o  m
         *      ____       _   ____  _             _
         *     |  _ \  ___| | / ___|| |_ ___   ___| | __
         *     | | | |/ _ \ | \___ \| __/ _ \ / __| |/ /
         *     | |_| |  __/ |  ___) | || (_) | (__|   <
         *     |____/ \___|_| |____/ \__\___/ \___|_|\_\
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton(
                "nursingrecords.inventory.stock.btndelete.tooltip", SYSConst.icon22delete, null);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(
                        SYSTools.xx("misc.questions.delete1") + "<br/><b>"
                                + SYSTools.xx("nursingrecords.inventory.search.stockid") + ": " + stock.getID()
                                + "</b>" + "<br/>" + SYSTools.xx("misc.questions.delete2"),
                        SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object answer) {
                                if (answer.equals(JOptionPane.YES_OPTION)) {
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        MedStock myStock = em.merge(stock);
                                        em.lock(em.merge(myStock.getInventory().getResident()),
                                                LockModeType.OPTIMISTIC);
                                        em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC);
                                        //                                    synchronized (lstInventories) {
                                        //                                        int index = lstInventories.indexOf(myStock.getInventory());
                                        //                                        lstInventories.get(index).getMedStocks().remove(myStock);
                                        //                                    }
                                        em.remove(myStock);
                                        em.getTransaction().commit();

                                        synchronized (cpMap) {
                                            cpMap.remove(key);
                                        }
                                        createCP4(myStock.getInventory());
                                        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 (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });

            }
        });
        btnDelete.setEnabled(!stock.isClosed());
        pnlMenu.add(btnDelete);
    }

    /***
     *      ____       _   _____            _            ____        _
     *     / ___|  ___| |_| ____|_  ___ __ (_)_ __ _   _|  _ \  __ _| |_ ___
     *     \___ \ / _ \ __|  _| \ \/ / '_ \| | '__| | | | | | |/ _` | __/ _ \
     *      ___) |  __/ |_| |___ >  <| |_) | | |  | |_| | |_| | (_| | ||  __/
     *     |____/ \___|\__|_____/_/\_\ .__/|_|_|   \__, |____/ \__,_|\__\___|
     *                               |_|           |___/
     */
    final JButton btnExpiry = GUITools.createHyperlinkButton("nursingrecords.inventory.tooltip.btnSetExpiry",
            SYSConst.icon22gotoEnd, null);
    btnExpiry.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            final JidePopup popup = new JidePopup();
            popup.setMovable(false);

            PnlExpiry pnlExpiry = new PnlExpiry(stock.getExpires(),
                    SYSTools.xx("nursingrecords.inventory.pnlExpiry.title") + ": " + stock.getID(),
                    new Closure() {
                        @Override
                        public void execute(Object o) {
                            popup.hidePopup();

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                MedStock myStock = em.merge(stock);
                                em.lock(em.merge(myStock.getInventory().getResident()),
                                        LockModeType.OPTIMISTIC);
                                em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC);
                                myStock.setExpires((Date) o);
                                em.getTransaction().commit();
                                synchronized (cpMap) {
                                    cpMap.remove(key);
                                }
                                createCP4(myStock.getInventory());
                                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 (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

                        }
                    });
            popup.setOwner(btnExpiry);
            popup.setContentPane(pnlExpiry);
            popup.removeExcludedComponent(pnlExpiry);
            popup.setDefaultFocusComponent(pnlExpiry);
            GUITools.showPopup(popup, SwingConstants.WEST);
        }
    });
    btnExpiry.setEnabled(!stock.isClosed());
    pnlMenu.add(btnExpiry);

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "opde.medication")) {
        /***
         *      _____              _      _____                    _____    _ _ _
         *     |_   _| __ __ _  __| | ___|  ___|__  _ __ _ __ ___ | ____|__| (_) |_ ___  _ __
         *       | || '__/ _` |/ _` |/ _ \ |_ / _ \| '__| '_ ` _ \|  _| / _` | | __/ _ \| '__|
         *       | || | | (_| | (_| |  __/  _| (_) | |  | | | | | | |__| (_| | | || (_) | |
         *       |_||_|  \__,_|\__,_|\___|_|  \___/|_|  |_| |_| |_|_____\__,_|_|\__\___/|_|
         *
         */
        final JButton btnTFEditor = GUITools.createHyperlinkButton("TFEditor.tooltip", SYSConst.icon22medical,
                null);
        btnTFEditor.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgTradeForm(stock.getTradeForm());
                reload();
            }
        });
        pnlMenu.add(btnTFEditor);

        /***
         *      _   _ ____  ____          _ _ _
         *     | | | |  _ \|  _ \ ___  __| (_) |_ ___  _ __
         *     | | | | |_) | |_) / _ \/ _` | | __/ _ \| '__|
         *     | |_| |  __/|  _ <  __/ (_| | | || (_) | |
         *      \___/|_|   |_| \_\___|\__,_|_|\__\___/|_|
         *
         */
        final JButton btnUPReditor = GUITools.createHyperlinkButton("upreditor.tooltip", SYSConst.icon22calc,
                null);
        btnUPReditor.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgUPREditor(stock.getTradeForm(), new Closure() {
                    @Override
                    public void execute(Object o) {
                        reload();
                    }
                });
            }
        });
        btnUPReditor.setEnabled(stock.getTradeForm().getDosageForm().isUPRn());
        pnlMenu.add(btnUPReditor);
    }

    //            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
    //                /***
    //                 *       ____ _
    //                 *      / ___| |__   __ _ _ __   __ _  ___
    //                 *     | |   | '_ \ / _` | '_ \ / _` |/ _ \
    //                 *     | |___| | | | (_| | | | | (_| |  __/
    //                 *      \____|_| |_|\__,_|_| |_|\__, |\___|
    //                 *                              |___/
    //                 */
    //                final JButton btnChange = GUITools.createHyperlinkButton(internalClassID + ".btnChange.tooltip", SYSConst.icon22playerPlay, null);

    //                btnChange.setEnabled(!prescription.isClosed() && !prescription.isOnDemand() && numBHPs != 0);
    //                pnlMenu.add(btnChange);

    return pnlMenu;
}