Example usage for javax.persistence OptimisticLockException getMessage

List of usage examples for javax.persistence OptimisticLockException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:entity.files.SYSFilesTools.java

public static boolean deleteFile(SYSFiles sysfile) {
    boolean success = false;
    EntityManager em = OPDE.createEM();// w w w . j  a v  a  2  s  .  com

    try {
        em.getTransaction().begin();
        SYSFiles mySYSFile = em.merge(sysfile);
        em.remove(mySYSFile);
        em.getTransaction().commit();
        success = true;
    } 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());
        success = false;
    } catch (Exception ex) {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        success = false;
    } finally {
        em.close();
    }

    if (success) {
        try {
            FileTransferClient ftp = getFTPClient();
            ftp.deleteFile(sysfile.getRemoteFilename());
            ftp.disconnect();
            OPDE.info("DELETING FILE FROM FTPSERVER: " + sysfile.getFilename() + " (" + sysfile.getMd5() + ")");
        } catch (Exception e) {
            OPDE.error(e);
            success = false;
        }
    }

    return success;
}

From source file:entity.files.SYSFilesTools.java

public static void detachFiles(SYSFiles[] files, SYSFilesContainer sysFilesContainer) {

    FileTransferClient ftp = getFTPClient();

    if (ftp != null) {
        EntityManager em = OPDE.createEM();
        try {/*from  w w w.j a va 2  s  .c  om*/
            em.getTransaction().begin();

            for (SYSFiles sysfile : files) {
                SYSFilesLink link = em.merge(sysFilesContainer.detachFile(sysfile));
                em.remove(link);
            }

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

From source file:entity.files.SYSFilesTools.java

public static List<SYSFiles> putFiles(File[] files, Object attachable) {
    ArrayList<SYSFiles> successful = new ArrayList<SYSFiles>(files.length);
    FileTransferClient ftp = getFTPClient();

    if (ftp != null) {
        EntityManager em = OPDE.createEM();
        try {/*from   w  w  w.j ava 2s . co  m*/
            em.getTransaction().begin();

            for (File file : files) {
                if (file.isFile()) { // prevents exceptions if somebody has the bright idea to include directories.
                    SYSFiles sysfile = putFile(em, ftp, file);
                    if (attachable != null) {
                        if (attachable instanceof NReport) {
                            SYSNR2FILE link = em.merge(new SYSNR2FILE(sysfile, (NReport) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getNrAssignCollection().add(link);
                            ((NReport) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Prescription) {
                            SYSPRE2FILE link = em.merge(new SYSPRE2FILE(sysfile, (Prescription) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getPreAssignCollection().add(link);
                            ((Prescription) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof ResInfo) {
                            SYSINF2FILE link = em.merge(new SYSINF2FILE(sysfile, (ResInfo) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getBwiAssignCollection().add(link);
                            ((ResInfo) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof ResValue) {
                            SYSVAL2FILE link = em.merge(new SYSVAL2FILE(sysfile, (ResValue) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getValAssignCollection().add(link);
                            ((ResValue) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof NursingProcess) {
                            SYSNP2FILE link = em.merge(new SYSNP2FILE(sysfile, (NursingProcess) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getNpAssignCollection().add(link);
                            ((NursingProcess) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training) {
                            Training2File link = em.merge(new Training2File(sysfile, (Training) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getTrAssignCollection().add(link);
                            ((Training) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Users) {
                            User2File link = em.merge(new User2File(sysfile, (Users) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getUsersAssignCollection().add(link);
                            ((Users) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Resident) {
                            Resident2File link = em.merge(new Resident2File(sysfile, (Resident) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getResidentAssignCollection().add(link);
                            ((Resident) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Qmsplan) {
                            Qmsplan2File link = em.merge(new Qmsplan2File(sysfile, (Qmsplan) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getQmsplanAssignCollection().add(link);
                            ((Qmsplan) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Qms) {
                            Qms2File link = em.merge(new Qms2File(sysfile, (Qms) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getQmsAssignCollection().add(link);
                            ((Qms) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training) {
                            Training2File link = em.merge(new Training2File(sysfile, (Training) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getTrainingAssignCollection().add(link);
                            ((Training) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training2Users) {
                            em.merge(((SYSFilesContainer) attachable).attachFile(sysfile));
                        }
                    }
                    successful.add(sysfile);
                }
                if (successful.size() != files.length) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.nodirectories")));
                }
            }
            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();
            }
            // Bereits gespeicherte wieder lschen
            //                for (SYSFiles sysfile : successful) {
            //                    try {
            //                        ftp.deleteFile(sysfile.getRemoteFilename());
            //                    } catch (IOException e) {
            //                        OPDE.fatal(e);
            //                    }
            //                }
            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
        } catch (Exception ex) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            // Bereits gespeicherte wieder lschen
            //                for (SYSFiles sysfile : successful) {
            //                    try {
            //                        ftp.deleteFile(sysfile.getRemoteFilename());
            //                    } catch (IOException e) {
            //                        OPDE.fatal(e);
            //                    }
            //                }
            OPDE.fatal(ex);
        } finally {
            em.close();
            try {
                ftp.disconnect();
            } catch (Exception e) {
                OPDE.error(e);
            }
        }
    }
    return successful;
}

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);/* ww  w  .j  a  va  2s .c  om*/

        //            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.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 .jav  a 2s.  c o m
        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.bhp.PnlBHP.java

private CollapsiblePane createCP4(final BHP bhp) {
    final CollapsiblePane bhpPane = new CollapsiblePane();
    bhpPane.setCollapseOnTitleClick(false);

    ActionListener applyActionListener = new ActionListener() {
        @Override/*from   www .j a  v a 2s  . c o  m*/
        public void actionPerformed(ActionEvent actionEvent) {
            if (bhp.getState() != BHPTools.STATE_OPEN) {
                return;
            }
            if (bhp.getPrescription().isClosed()) {
                return;
            }

            if (BHPTools.isChangeable(bhp)) {
                outcomeText = null;
                if (bhp.getNeedsText()) {
                    new DlgYesNo(SYSConst.icon48comment, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (SYSTools.catchNull(o).isEmpty()) {
                                outcomeText = null;
                            } else {
                                outcomeText = o.toString();
                            }
                        }
                    }, "nursingrecords.bhp.describe.outcome", null, null);

                }

                if (bhp.getNeedsText() && outcomeText == null) {
                    OPDE.getDisplayManager().addSubMessage(
                            new DisplayMessage("nursingrecords.bhp.notext.nooutcome", DisplayMessage.WARNING));
                    return;
                }

                if (bhp.getPrescription().isWeightControlled()) {
                    new DlgYesNo(SYSConst.icon48scales, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (SYSTools.catchNull(o).isEmpty()) {
                                weight = null;
                            } else {
                                weight = (BigDecimal) o;
                            }
                        }
                    }, "nursingrecords.bhp.weight", null, 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);
                        }
                    });

                }

                if (bhp.getPrescription().isWeightControlled() && weight == null) {
                    OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                            "nursingrecords.bhp.noweight.nosuccess", DisplayMessage.WARNING));
                    return;
                }

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();

                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                    BHP myBHP = em.merge(bhp);
                    em.lock(myBHP, LockModeType.OPTIMISTIC);

                    if (myBHP.isOnDemand()) {
                        em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                        em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                    } else {
                        em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                        em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);
                    }

                    myBHP.setState(BHPTools.STATE_DONE);
                    myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                    myBHP.setIst(new Date());
                    myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                    myBHP.setMDate(new Date());
                    myBHP.setText(outcomeText);

                    Prescription involvedPresciption = null;
                    if (myBHP.shouldBeCalculated()) {
                        MedInventory inventory = TradeFormTools.getInventory4TradeForm(resident,
                                myBHP.getTradeForm());
                        MedInventoryTools.withdraw(em, em.merge(inventory), myBHP.getDose(), weight, myBHP);
                        // Was the prescription closed during this withdraw ?
                        involvedPresciption = em.find(Prescription.class, myBHP.getPrescription().getID());
                    }

                    BHP outcomeBHP = null;
                    // add outcome check BHP if necessary
                    if (!myBHP.isOutcomeText()
                            && myBHP.getPrescriptionSchedule().getCheckAfterHours() != null) {
                        outcomeBHP = em.merge(new BHP(myBHP));
                        mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND).add(outcomeBHP);
                    }

                    em.getTransaction().commit();

                    if (myBHP.shouldBeCalculated() && involvedPresciption.isClosed()) { // &&
                        reload();
                    } else if (outcomeBHP != null) {
                        reload();
                    } else {
                        mapBHP2Pane.put(myBHP, createCP4(myBHP));
                        int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                        mapShift2BHP.get(myBHP.getShift()).remove(position);
                        mapShift2BHP.get(myBHP.getShift()).add(position, myBHP);
                        if (myBHP.isOnDemand()) {
                            // This whole thing here is only to handle the BPHs on Demand
                            // Fix the other BHPs on demand. If not, you will get locking exceptions,
                            // we FORCED INCREMENTED LOCKS on the Schedule and the Prescription.
                            ArrayList<BHP> changeList = new ArrayList<BHP>();
                            for (BHP bhp : mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND)) {
                                if (bhp.getPrescription().getID() == myBHP.getPrescription().getID()
                                        && bhp.getBHPid() != myBHP.getBHPid()) {
                                    bhp.setPrescription(myBHP.getPrescription());
                                    bhp.setPrescriptionSchedule(myBHP.getPrescriptionSchedule());
                                    changeList.add(bhp);
                                }
                            }
                            for (BHP bhp : changeList) {
                                mapBHP2Pane.put(bhp, createCP4(myBHP));
                                position = mapShift2BHP.get(bhp.getShift()).indexOf(bhp);
                                mapShift2BHP.get(myBHP.getShift()).remove(position);
                                mapShift2BHP.get(myBHP.getShift()).add(position, bhp);
                            }

                            Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                    BHPTools.getOnDemandComparator());
                        } else {
                            Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                        }

                        mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                        buildPanel(false);
                    }
                } catch (OptimisticLockException ole) {
                    OPDE.warn(ole);
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                        OPDE.getMainframe().emptyFrame();
                        OPDE.getMainframe().afterLogin();
                    }
                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                } catch (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();
                }

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

    //        JPanel titlePanelleft = new JPanel();
    //        titlePanelleft.setLayout(new BoxLayout(titlePanelleft, BoxLayout.LINE_AXIS));

    MedStock stock = mapPrescription2Stock.get(bhp.getPrescription());
    if (bhp.hasMed() && stock == null) {
        stock = MedStockTools
                .getStockInUse(TradeFormTools.getInventory4TradeForm(resident, bhp.getTradeForm()));
        mapPrescription2Stock.put(bhp.getPrescription(), stock);
    }

    String title;

    if (bhp.isOutcomeText()) {
        title = "<html><font size=+1>"
                + SYSConst.html_italic(SYSTools
                        .left("&ldquo;" + PrescriptionTools.getShortDescriptionAsCompactText(
                                bhp.getPrescriptionSchedule().getPrescription()), MAX_TEXT_LENGTH)
                        + BHPTools.getScheduleText(bhp.getOutcome4(), "&rdquo;, ", ""))
                + " [" + bhp.getPrescriptionSchedule().getCheckAfterHours() + " "
                + SYSTools.xx("misc.msg.Hour(s)") + "] " + BHPTools.getScheduleText(bhp, ", ", "")
                + (bhp.getPrescription().isWeightControlled()
                        ? " " + SYSConst.html_16x16_scales_internal + (bhp.isOpen() ? ""
                                : (bhp.getStockTransaction().isEmpty() ? " "
                                        : NumberFormat.getNumberInstance()
                                                .format(bhp.getStockTransaction().get(0).getWeight()) + "g "))
                        : "")
                + (bhp.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(bhp.getUser().getUID()) + "</i>"
                        : "")
                +

                "</font></html>";
    } else {
        title = "<html><font size=+1>"
                + SYSTools.left(PrescriptionTools.getShortDescriptionAsCompactText(
                        bhp.getPrescriptionSchedule().getPrescription()), MAX_TEXT_LENGTH)
                + (bhp.hasMed()
                        ? ", <b>" + SYSTools.getAsHTML(bhp.getDose()) + " "
                                + DosageFormTools.getUsageText(
                                        bhp.getPrescription().getTradeForm().getDosageForm())
                                + "</b>"
                        : "")
                + BHPTools.getScheduleText(bhp, ", ", "")
                + (bhp.getPrescription().isWeightControlled()
                        ? " " + SYSConst.html_16x16_scales_internal + (bhp.isOpen() ? ""
                                : (bhp.getStockTransaction().isEmpty() ? " "
                                        : NumberFormat.getNumberInstance()
                                                .format(bhp.getStockTransaction().get(0).getWeight()) + "g "))
                        : "")
                + (bhp.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(bhp.getUser().getUID()) + "</i>"
                        : "")
                + "</font></html>";
    }

    DefaultCPTitle cptitle = new DefaultCPTitle(title,
            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID) ? applyActionListener
                    : null);

    JLabel icon1 = new JLabel(BHPTools.getIcon(bhp));
    icon1.setOpaque(false);
    if (!bhp.isOpen()) {
        icon1.setToolTipText(DateFormat.getDateTimeInstance().format(bhp.getIst()));
    }

    JLabel icon2 = new JLabel(BHPTools.getWarningIcon(bhp, stock));
    icon2.setOpaque(false);

    cptitle.getAdditionalIconPanel().add(icon1);
    cptitle.getAdditionalIconPanel().add(icon2);

    if (bhp.getPrescription().isClosed()) {
        JLabel icon3 = new JLabel(SYSConst.icon22stopSign);
        icon3.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon3);
    }

    if (bhp.isOutcomeText()) {
        JLabel icon4 = new JLabel(SYSConst.icon22comment);
        icon4.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon4);
    }

    if (!bhp.isOutcomeText() && bhp.getPrescriptionSchedule().getCheckAfterHours() != null) {
        JLabel icon4 = new JLabel(SYSConst.icon22intervalBySecond);
        icon4.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon4);
    }

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        if (!bhp.getPrescription().isClosed()) {

            /***
             *      _     _            _                _
             *     | |__ | |_ _ __    / \   _ __  _ __ | |_   _
             *     | '_ \| __| '_ \  / _ \ | '_ \| '_ \| | | | |
             *     | |_) | |_| | | |/ ___ \| |_) | |_) | | |_| |
             *     |_.__/ \__|_| |_/_/   \_\ .__/| .__/|_|\__, |
             *                             |_|   |_|      |___/
             */
            JButton btnApply = new JButton(SYSConst.icon22apply);
            btnApply.setPressedIcon(SYSConst.icon22applyPressed);
            btnApply.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnApply.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnApply.tooltip"));
            btnApply.addActionListener(applyActionListener);
            btnApply.setContentAreaFilled(false);
            btnApply.setBorder(null);
            btnApply.setEnabled(bhp.isOpen()
                    && (!bhp.hasMed() || mapPrescription2Stock.containsKey(bhp.getPrescription())));
            cptitle.getRight().add(btnApply);

            /***
             *                             ____  _             _
             *       ___  _ __   ___ _ __ / ___|| |_ ___   ___| | __
             *      / _ \| '_ \ / _ \ '_ \\___ \| __/ _ \ / __| |/ /
             *     | (_) | |_) |  __/ | | |___) | || (_) | (__|   <
             *      \___/| .__/ \___|_| |_|____/ \__\___/ \___|_|\_\
             *           |_|
             */
            if (bhp.hasMed() && stock == null && MedInventoryTools.getNextToOpen(
                    TradeFormTools.getInventory4TradeForm(resident, bhp.getTradeForm())) != null) {
                final JButton btnOpenStock = new JButton(SYSConst.icon22ledGreenOn);
                btnOpenStock.setPressedIcon(SYSConst.icon22ledGreenOff);
                btnOpenStock.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnOpenStock.setContentAreaFilled(false);
                btnOpenStock.setBorder(null);
                btnOpenStock.setToolTipText(SYSTools
                        .toHTMLForScreen(SYSTools.xx("nursingrecords.inventory.stock.btnopen.tooltip")));
                btnOpenStock.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            BHP myBHP = em.merge(bhp);
                            em.lock(myBHP, LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                            MedStock myStock = em.merge(MedInventoryTools.openNext(
                                    TradeFormTools.getInventory4TradeForm(resident, myBHP.getTradeForm())));
                            em.lock(myStock, LockModeType.OPTIMISTIC);
                            em.getTransaction().commit();

                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage(
                                            String.format(SYSTools.xx("newstocks.stock.has.been.opened"),
                                                    myStock.getID().toString())));
                            reload();

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

            if (!bhp.isOutcomeText()) {
                /***
                 *      _     _         ____       __
                 *     | |__ | |_ _ __ |  _ \ ___ / _|_   _ ___  ___
                 *     | '_ \| __| '_ \| |_) / _ \ |_| | | / __|/ _ \
                 *     | |_) | |_| | | |  _ <  __/  _| |_| \__ \  __/
                 *     |_.__/ \__|_| |_|_| \_\___|_|  \__,_|___/\___|
                 *
                 */
                final JButton btnRefuse = new JButton(SYSConst.icon22cancel);
                btnRefuse.setPressedIcon(SYSConst.icon22cancelPressed);
                btnRefuse.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnRefuse.setContentAreaFilled(false);
                btnRefuse.setBorder(null);
                btnRefuse.setToolTipText(
                        SYSTools.toHTMLForScreen(SYSTools.xx("nursingrecords.bhp.btnRefuse.tooltip")));
                btnRefuse.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (bhp.getState() != BHPTools.STATE_OPEN) {
                            return;
                        }

                        if (BHPTools.isChangeable(bhp)) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                BHP myBHP = em.merge(bhp);
                                em.lock(myBHP, LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                                myBHP.setState(BHPTools.STATE_REFUSED);
                                myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                                myBHP.setIst(new Date());
                                myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                                myBHP.setMDate(new Date());

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                em.getTransaction().commit();
                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

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

                /***
                 *      _     _         ____       __                ____  _                       _
                 *     | |__ | |_ _ __ |  _ \ ___ / _|_   _ ___  ___|  _ \(_)___  ___ __ _ _ __ __| |
                 *     | '_ \| __| '_ \| |_) / _ \ |_| | | / __|/ _ \ | | | / __|/ __/ _` | '__/ _` |
                 *     | |_) | |_| | | |  _ <  __/  _| |_| \__ \  __/ |_| | \__ \ (_| (_| | | | (_| |
                 *     |_.__/ \__|_| |_|_| \_\___|_|  \__,_|___/\___|____/|_|___/\___\__,_|_|  \__,_|
                 *
                 */
                final JButton btnRefuseDiscard = new JButton(SYSConst.icon22deleteall);
                btnRefuseDiscard.setPressedIcon(SYSConst.icon22deleteallPressed);
                btnRefuseDiscard.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnRefuseDiscard.setContentAreaFilled(false);
                btnRefuseDiscard.setBorder(null);
                btnRefuseDiscard.setToolTipText(
                        SYSTools.toHTMLForScreen(SYSTools.xx("nursingrecords.bhp.btnRefuseDiscard.tooltip")));
                btnRefuseDiscard.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (bhp.getState() != BHPTools.STATE_OPEN) {
                            return;
                        }

                        if (BHPTools.isChangeable(bhp)) {

                            if (bhp.getPrescription().isWeightControlled()) {
                                new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                    @Override
                                    public void execute(Object o) {
                                        if (SYSTools.catchNull(o).isEmpty()) {
                                            weight = null;
                                        } else {
                                            weight = (BigDecimal) o;
                                        }
                                    }
                                }, "nursingrecords.bhp.weight", null, 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);
                                    }
                                });

                            }

                            if (bhp.getPrescription().isWeightControlled() && weight == null) {
                                OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                                        "nursingrecords.bhp.noweight.nosuccess", DisplayMessage.WARNING));
                                return;
                            }

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                BHP myBHP = em.merge(bhp);
                                em.lock(myBHP, LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                                myBHP.setState(BHPTools.STATE_REFUSED_DISCARDED);
                                myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                                myBHP.setIst(new Date());
                                myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                                myBHP.setMDate(new Date());

                                if (myBHP.shouldBeCalculated()) {
                                    MedInventory inventory = TradeFormTools.getInventory4TradeForm(resident,
                                            myBHP.getTradeForm());
                                    if (inventory != null) {
                                        MedInventoryTools.withdraw(em, em.merge(inventory), myBHP.getDose(),
                                                weight, myBHP);
                                    } else {
                                        OPDE.getDisplayManager().addSubMessage(
                                                new DisplayMessage("nursingrecords.bhp.NoInventory"));
                                    }
                                }

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                em.getTransaction().commit();
                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

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

                btnRefuseDiscard.setEnabled(
                        !bhp.isOnDemand() && bhp.hasMed() && bhp.shouldBeCalculated() && bhp.isOpen());
                cptitle.getRight().add(btnRefuseDiscard);
            }

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

                    BHP outcomeBHP = BHPTools.getComment(bhp);

                    if (outcomeBHP != null && !outcomeBHP.isOpen()) {
                        // already commented
                        return;
                    }

                    if (BHPTools.isChangeable(bhp)) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            BHP myBHP = em.merge(bhp);

                            em.lock(myBHP, LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                            // the normal BHPs (those assigned to a NursingProcess) are reset to the OPEN state.
                            // TXs are deleted
                            myBHP.setState(BHPTools.STATE_OPEN);
                            myBHP.setUser(null);
                            myBHP.setIst(null);
                            myBHP.setiZeit(null);
                            myBHP.setMDate(new Date());
                            myBHP.setText(null);

                            if (myBHP.shouldBeCalculated()) {
                                for (MedStockTransaction tx : myBHP.getStockTransaction()) {
                                    em.remove(tx);
                                }
                                myBHP.getStockTransaction().clear();
                            }

                            if (outcomeBHP != null) {
                                BHP myOutcomeBHP = em.merge(outcomeBHP);
                                em.remove(myOutcomeBHP);
                            }

                            if (myBHP.isOnDemand()) {
                                em.remove(myBHP);
                            }

                            em.getTransaction().commit();

                            if (myBHP.isOnDemand()) {
                                reload();
                            } else {

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            }
                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }

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

        /***
         *      _     _         ___        __
         *     | |__ | |_ _ __ |_ _|_ __  / _| ___
         *     | '_ \| __| '_ \ | || '_ \| |_ / _ \
         *     | |_) | |_| | | || || | | |  _| (_) |
         *     |_.__/ \__|_| |_|___|_| |_|_|  \___/
         *
         */
        final JButton btnInfo = new JButton(SYSConst.icon22info);

        btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
        btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnInfo.setContentAreaFilled(false);
        btnInfo.setBorder(null);
        btnInfo.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnInfo.tooltip"));
        final JTextPane txt = new JTextPane();
        txt.setContentType("text/html");
        txt.setEditable(false);
        final JidePopup popupInfo = new JidePopup();
        popupInfo.setMovable(false);
        popupInfo.setContentPane(new JScrollPane(txt));
        popupInfo.removeExcludedComponent(txt);
        popupInfo.setDefaultFocusComponent(txt);

        btnInfo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                popupInfo.setOwner(btnInfo);

                if (bhp.isOutcomeText() && !bhp.isOpen()) {
                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getText())));
                } else {
                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getPrescription().getText())));
                }

                //                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getPrescription().getText())));
                GUITools.showPopup(popupInfo, SwingConstants.SOUTH_WEST);
            }
        });

        if (bhp.isOutcomeText() && !bhp.isOpen()) {
            btnInfo.setEnabled(true);
        } else {
            btnInfo.setEnabled(!SYSTools.catchNull(bhp.getPrescription().getText()).isEmpty());
        }

        cptitle.getRight().add(btnInfo);

    }

    bhpPane.setTitleLabelComponent(cptitle.getMain());
    bhpPane.setSlidingDirection(SwingConstants.SOUTH);

    final JTextPane contentPane = new JTextPane();
    contentPane.setEditable(false);
    contentPane.setContentType("text/html");
    bhpPane.setContentPane(contentPane);
    bhpPane.setBackground(bhp.getBG());
    bhpPane.setForeground(bhp.getFG());

    try {
        bhpPane.setCollapsed(true);
    } catch (PropertyVetoException e) {
        OPDE.error(e);
    }

    bhpPane.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            contentPane.setText(SYSTools.toHTML(
                    PrescriptionTools.getPrescriptionAsHTML(bhp.getPrescription(), false, false, true, false)));
        }
    });

    bhpPane.setHorizontalAlignment(SwingConstants.LEADING);
    bhpPane.setOpaque(false);
    return bhpPane;
}

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

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

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

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

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

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

                    em.getTransaction().commit();

                    CollapsiblePane cp1 = createCP4(myDFN);

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

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

                    buildPanel(false);

                } catch (OptimisticLockException ole) {
                    OPDE.warn(ole);
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                        OPDE.getMainframe().emptyFrame();
                        OPDE.getMainframe().afterLogin();
                    }
                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                } catch (Exception e) {
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    OPDE.fatal(e);
                } finally {
                    em.close();
                }

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

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

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

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

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

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

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

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

                        em.getTransaction().commit();

                        CollapsiblePane cp1 = createCP4(myDFN);
                        synchronized (mapDFN2Pane) {
                            mapDFN2Pane.put(myDFN, cp1);
                        }
                        synchronized (mapShift2DFN) {
                            int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                            mapShift2DFN.get(myDFN.getShift()).remove(position);
                            mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                        }
                        CollapsiblePane cp2 = createCP4(myDFN.getShift());
                        synchronized (mapShift2Pane) {
                            mapShift2Pane.put(myDFN.getShift(), cp2);
                        }
                        buildPanel(false);
                    } catch (OptimisticLockException ole) {
                        OPDE.warn(ole);
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                            OPDE.getMainframe().emptyFrame();
                            OPDE.getMainframe().afterLogin();
                        }
                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                    } catch (Exception e) {
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        OPDE.fatal(e);
                    } finally {
                        em.close();
                    }

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

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

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

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

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

                        CollapsiblePane cp2 = createCP4(myDFN.getShift());
                        synchronized (mapShift2Pane) {
                            mapShift2Pane.put(myDFN.getShift(), cp2);
                        }
                        buildPanel(false);
                    } catch (OptimisticLockException ole) {
                        OPDE.warn(ole);
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                            OPDE.getMainframe().emptyFrame();
                            OPDE.getMainframe().afterLogin();
                        }
                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                    } catch (Exception e) {
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        OPDE.fatal(e);
                    } finally {
                        em.close();
                    }

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

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

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

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

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

                                    buildPanel(false);
                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                            }
                        });

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

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

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

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

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

    dfnPane.setTitleLabelComponent(cptitle.getMain());

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

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 av  a2  s  .co 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.med.inventory.DlgCloseStock.java

private void save() {
    EntityManager em = OPDE.createEM();/*from  ww w.j  a v a  2  s . c o m*/
    try {
        em.getTransaction().begin();

        final MedStock myStock = em.merge(medStock);
        em.lock(myStock, LockModeType.OPTIMISTIC);
        em.lock(em.merge(myStock.getInventory().getResident()), LockModeType.OPTIMISTIC);
        em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC);

        OPDE.important("StockID: " + myStock.getID() + " " + SYSTools.xx("misc.msg.closed"));
        OPDE.important("UID: " + OPDE.getLogin().getUser().getUID());

        MedStock nextBest = null;
        if (cmbBestID.getSelectedIndex() > 0) {
            nextBest = em.merge((MedStock) cmbBestID.getSelectedItem());
            OPDE.important(SYSTools.xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_SOON1")
                    + ": " + nextBest.getID());
            em.lock(nextBest, LockModeType.OPTIMISTIC);
            myStock.setNextStock(nextBest);
        }

        if (rbStellen.isSelected()) {
            BigDecimal inhalt = new BigDecimal(Double.parseDouble(txtLetzte.getText().replace(",", ".")));
            MedStockTools.setStockTo(em, myStock, inhalt,
                    SYSTools.xx("nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_SOON"),
                    MedStockTransactionTools.STATE_EDIT_EMPTY_SOON);
            myStock.setState(MedStockTools.STATE_WILL_BE_CLOSED_SOON);
            OPDE.important(SYSTools.xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_SOON1")
                    + ": " + inhalt);
        } else {
            if (rbGefallen.isSelected()) {
                MedStockTools.close(em, myStock,
                        SYSTools.xx(
                                "nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_BROKEN_OR_LOST"),
                        MedStockTransactionTools.STATE_EDIT_EMPTY_BROKEN_OR_LOST);
                OPDE.important(SYSTools
                        .xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_BROKEN_OR_LOST"));
            } else if (rbAbgelaufen.isSelected()) {
                MedStockTools.close(em, myStock,
                        SYSTools.xx(
                                "nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_PAST_EXPIRY"),
                        MedStockTransactionTools.STATE_EDIT_EMPTY_PAST_EXPIRY);
                OPDE.important(SYSTools
                        .xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_PAST_EXPIRY"));
            } else {
                MedStockTools.close(em, myStock,
                        SYSTools.xx("nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_NOW"),
                        MedStockTransactionTools.STATE_EDIT_EMPTY_NOW);
                OPDE.important(
                        SYSTools.xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_NOW"));
            }
        }

        em.getTransaction().commit();

        medStock = myStock;

    } catch (javax.persistence.OptimisticLockException 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();
    }

    dispose();
}

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

private void save() {
    EntityManager em = OPDE.createEM();/*from  w  w w  .j  av a2s  . c  o m*/

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

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

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

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

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

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

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

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

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

        // if the label printer is not used, the new number is shown until the next message, so the user has time to write the number down manually.
        OPDE.getDisplayManager()
                .addSubMessage(new DisplayMessage(
                        SYSTools.xx("newstocks.registration.success.1") + " <b>" + newStock.getID() + "</b> "
                                + SYSTools.xx("newstocks.registration.success.2"),
                        btnPrint.isSelected() ? 2 : 0));
    } catch (OptimisticLockException ole) {
        OPDE.warn(ole);
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
            OPDE.getMainframe().emptyFrame();
            OPDE.getMainframe().afterLogin();
        }
        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
    } catch (Exception ex) {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        OPDE.fatal(ex);
    } finally {
        em.close();
    }
}