Example usage for javax.persistence EntityManager lock

List of usage examples for javax.persistence EntityManager lock

Introduction

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

Prototype

public void lock(Object entity, LockModeType lockMode);

Source Link

Document

Lock an entity instance that is contained in the persistence context with the specified lock mode type.

Usage

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

private CollapsiblePane createCP4(final Prescription prescription) {
    /***/*from w w  w  . ja v  a2 s  . co  m*/
     *                          _        ____ ____  _  _    ______                          _       _   _           __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /  _ \ _ __ ___  ___  ___ _ __(_)_ __ | |_(_) ___  _ __\ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| || |_) | '__/ _ \/ __|/ __| '__| | '_ \| __| |/ _ \| '_ \| |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| ||  __/| | |  __/\__ \ (__| |  | | |_) | |_| | (_) | | | | |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||_|   |_|  \___||___/\___|_|  |_| .__/ \__|_|\___/|_| |_| |
     *                                                     \_\                               |_|                    /_/
     */
    final String key = prescription.getID() + ".xprescription";
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        try {
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    final CollapsiblePane cpPres = cpMap.get(key);

    String title = "<html><table border=\"0\">" + "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">"
            + prescription.getPITAsHTML() + "</td>" + "<td width=\"380\" align=\"left\">" + "<font size=+1>"
            + PrescriptionTools.getShortDescription(prescription) + "</font>"
            + PrescriptionTools.getDoseAsHTML(prescription)
            + PrescriptionTools.getInventoryInformationAsHTML(prescription) + "</td>"
            + "<td width=\"200\" align=\"left\">" + PrescriptionTools.getOriginalPrescription(prescription)
            + PrescriptionTools.getRemark(prescription) + "</td>";

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

    if (PrescriptionTools.isAnnotationNecessary(prescription)) {
        title += "<tr>" + "    <td colspan=\"3\">" + PrescriptionTools.getAnnontationsAsHTML(prescription)
                + "</td>" + "  </tr>";
    }

    title += "</table>" + "</html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
    cpPres.setCollapsible(false);
    cptitle.getButton().setIcon(getIcon(prescription));

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

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

        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                // checked for acls
                Closure fileHandleClosure = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                        internalClassID) ? null : new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                final Prescription myPrescription = em.find(Prescription.class,
                                        prescription.getID());
                                em.close();
                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                                buildPanel();
                                GUITools.flashBackground(myCP, Color.YELLOW, 2);
                            }
                        };
                new DlgFiles(prescription, fileHandleClosure);
            }
        });
        btnFiles.setEnabled(OPDE.isFTPworking());
        cptitle.getRight().add(btnFiles);
    }

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

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

                        EntityManager em = OPDE.createEM();

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

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

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

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

                            em.getTransaction().commit();

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

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

                    }
                });
            }
        });
        // checked for acls
        btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
        cptitle.getRight().add(btnProcess);
    }

    /***
     *      __  __
     *     |  \/  | ___ _ __  _   _
     *     | |\/| |/ _ \ '_ \| | | |
     *     | |  | |  __/ | | | |_| |
     *     |_|  |_|\___|_| |_|\__,_|
     *
     */
    final JButton btnMenu = new JButton(SYSConst.icon22menu);
    btnMenu.setPressedIcon(SYSConst.icon22Pressed);
    btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
    btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    btnMenu.setContentAreaFilled(false);
    btnMenu.setBorder(null);
    btnMenu.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JidePopup popup = new JidePopup();
            popup.setMovable(false);
            popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
            popup.setOwner(btnMenu);
            popup.removeExcludedComponent(btnMenu);
            JPanel pnl = getMenu(prescription);
            popup.getContentPane().add(pnl);
            popup.setDefaultFocusComponent(pnl);

            GUITools.showPopup(popup, SwingConstants.WEST);
        }
    });
    cptitle.getRight().add(btnMenu);

    cpPres.setHorizontalAlignment(SwingConstants.LEADING);
    cpPres.setOpaque(false);

    return cpPres;
}

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

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

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton addRegular = GUITools.createHyperlinkButton("nursingrecords.prescription.btnNewRegular",
                SYSConst.icon22add, new ActionListener() {
                    @Override// w  w  w.  j  ava  2s. c om
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgRegular(new Prescription(resident), DlgRegular.MODE_NEW, new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o != null) {
                                    Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o;
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        Prescription myPrescription = em.merge(returnPackage.getFirst());
                                        myPrescription
                                                .setRelation(UniqueTools.getNewUID(em, "__verkenn").getUid());
                                        BHPTools.generate(em, myPrescription.getPrescriptionSchedule(),
                                                new LocalDate(), true);
                                        em.getTransaction().commit();

                                        lstPrescriptions.add(myPrescription);
                                        Collections.sort(lstPrescriptions);
                                        final CollapsiblePane myCP = createCP4(myPrescription);
                                        buildPanel();
                                        SwingUtilities.invokeLater(new Runnable() {
                                            @Override
                                            public void run() {
                                                GUITools.scroll2show(jspPrescription,
                                                        myCP.getLocation().y - 100, new Closure() {
                                                            @Override
                                                            public void execute(Object o) {
                                                                GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                            }
                                                        });
                                            }
                                        });
                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        }
                                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                    buildPanel();
                                }
                            }
                        });
                    }
                });
        list.add(addRegular);
    }

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton addNewOnDemand = GUITools.createHyperlinkButton("nursingrecords.prescription.btnNewOnDemand",
                SYSConst.icon22add, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgOnDemand(new Prescription(resident), new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o != null) {

                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        Prescription myPrescription = em.merge((Prescription) o);
                                        myPrescription
                                                .setRelation(UniqueTools.getNewUID(em, "__verkenn").getUid());
                                        em.getTransaction().commit();

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

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

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

    // checked for acls
    if (resident.isCalcMediUPR1() && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton buchenButton = GUITools.createHyperlinkButton("nursingrecords.prescription.newstocks",
                new ImageIcon(getClass().getResource("/artwork/22x22/shetaddrow.png")), new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgNewStocks(resident);
                        reload();
                    }
                });
        list.add(buchenButton);
    }

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.PRINT, internalClassID)) {
        JideButton printPrescription = GUITools.createHyperlinkButton("nursingrecords.prescription.print",
                SYSConst.icon22print2, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        SYSFilesTools.print(PrescriptionTools.getPrescriptionsAsHTML(lstPrescriptions, true,
                                true, false, tbClosed.isSelected(), true), true);
                    }
                });
        list.add(printPrescription);

        //            JideButton printDaily = GUITools.createHyperlinkButton("nursingrecords.prescription.printdailyplan", SYSConst.icon22print2, new ActionListener() {
        //                @Override
        //                public void actionPerformed(ActionEvent actionEvent) {
        //                    SYSFilesTools.print(PrescriptionTools.printDailyPlan(resident.getStation().getHome()), true);
        //                }
        //            });
        //            list.add(printDaily);
    }

    return list;
}

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

private JPanel getMenu(final Prescription prescription) {

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

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

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

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

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

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

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

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

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

                                // Refresh Display
                                createCP4(oldPrescription);
                                final CollapsiblePane myNewCP = createCP4(newPrescription);
                                buildPanel();
                                GUITools.flashBackground(myNewCP, Color.YELLOW, 2);
                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                            //                                buildPanel();
                        }
                    }
                });
            }
        });
        btnChange.setEnabled(!prescription.isClosed() && !prescription.isOnDemand() && numBHPs != 0);
        pnlMenu.add(btnChange);

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

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

                                buildPanel();

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

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                em.getTransaction().rollback();
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                });
            }
        });
        btnStop.setEnabled(!prescription.isClosed()); //  && numBHPs != 0
        pnlMenu.add(btnStop);

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

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

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

                                    em.getTransaction().commit();

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

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

                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                                //                                    buildPanel();
                            }
                        }
                    });
                } else {
                    new DlgRegular(prescription, DlgRegular.MODE_EDIT, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {

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

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

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

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

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

                                    em.getTransaction().commit();

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

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

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

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

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

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

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

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

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

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

                            myPrescription.getCommontags().removeAll(listTags2Remove);

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

                            em.getTransaction().commit();

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

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

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

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

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

                GUITools.showPopup(popup, SwingConstants.WEST);

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

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

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

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

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

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

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

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

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

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

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

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

                OPDE.debug(lstPrescriptions);

                dlg.setVisible(true);

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

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

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

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

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

                                        OPDE.getDisplayManager().addSubMessage(
                                                new DisplayMessage(SYSTools.xx("misc.msg.Deleted") + ": "
                                                        + PrescriptionTools.toPrettyString(myverordnung)));
                                        lstPrescriptions.remove(prescription);
                                        buildPanel();
                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        }
                                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                    } catch (Exception e) {
                                        em.getTransaction().rollback();
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });
            }

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

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

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

                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    MedStock myStock = em.merge(stockInUse);
                                    em.lock(em.merge(myStock.getInventory().getResident()),
                                            LockModeType.OPTIMISTIC);
                                    em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC);
                                    myStock.setExpires((Date) o);
                                    em.getTransaction().commit();
                                    createCP4(prescription);
                                    buildPanel();
                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }

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

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

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

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

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

        pnlMenu.add(new JSeparator());

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

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

        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

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

                        EntityManager em = OPDE.createEM();

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

    /***/*  w  w w. j  a  va 2s . c  o  m*/
     *      _   _
     *     | \ | | _____      __
     *     |  \| |/ _ \ \ /\ / /
     *     | |\  |  __/\ V  V /
     *     |_| \_|\___| \_/\_/
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton addButton = GUITools.createHyperlinkButton(SYSTools.xx("misc.commands.new"),
                new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png")), new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgReport(new NReport(resident), new Closure() {
                            @Override
                            public void execute(Object report) {
                                if (report != null) {
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        final NReport myReport = (NReport) em.merge(report);
                                        em.getTransaction().commit();

                                        final String keyYear = Integer
                                                .toString(new DateTime(myReport.getPit()).getYear()) + ".year";
                                        if (!cpMap.containsKey(keyYear)) {
                                            reloadDisplay();
                                        } else {
                                            final String keyDay = DateFormat.getDateInstance()
                                                    .format(myReport.getPit());
                                            synchronized (contentmap) {
                                                contentmap.remove(keyDay);
                                            }
                                            synchronized (valuecache) {
                                                if (valuecache.containsKey(keyDay)) {
                                                    valuecache.get(keyDay).add(myReport);
                                                    Collections.sort(valuecache.get(keyDay));
                                                }
                                            }
                                            synchronized (listUsedCommontags) {
                                                boolean reloadSearch = false;
                                                for (Commontags ctag : myReport.getCommontags()) {
                                                    if (!listUsedCommontags.contains(ctag)) {
                                                        listUsedCommontags.add(ctag);
                                                        reloadSearch = true;
                                                    }
                                                }
                                                if (reloadSearch) {
                                                    prepareSearchArea();
                                                }
                                            }

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

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

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

                                            buildPanel();
                                            GUITools.scroll2show(jspReports, cpMap.get(keyDay), cpsReports,
                                                    new Closure() {
                                                        @Override
                                                        public void execute(Object o) {
                                                            GUITools.flashBackground(linemap.get(myReport),
                                                                    Color.YELLOW, 2);
                                                        }
                                                    });
                                        }
                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        } else {
                                            reloadDisplay(true);
                                        }
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });
                    }
                });
        list.add(addButton);
    }
    return list;
}

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

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

    final String key = DateFormat.getDateInstance().format(day.toDate());
    synchronized (contentmap) {
        if (contentmap.containsKey(key)) {
            return contentmap.get(key);
        }/*from   ww  w .ja  v a2  s .c  o m*/
    }
    final JPanel dayPanel = new JPanel(new VerticalLayout());
    dayPanel.setOpaque(false);
    synchronized (valuecache) {
        if (!valuecache.containsKey(key)) {
            valuecache.put(key, NReportTools.getNReports4Day(resident, day));
        }

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

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

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

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

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

                    btnFiles.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            Closure fileHandleClosure = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                                    internalClassID) ? null : new Closure() {
                                        @Override
                                        public void execute(Object o) {
                                            EntityManager em = OPDE.createEM();
                                            final NReport myReport = em.find(NReport.class, nreport.getID());
                                            em.close();

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

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

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

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

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

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

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

                                    EntityManager em = OPDE.createEM();

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

                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        NReport myReport = em.merge(nreport);
                                        em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                        ArrayList<SYSNR2PROCESS> attached = new ArrayList<SYSNR2PROCESS>(
                                                myReport.getAttachedQProcessConnections());
                                        for (SYSNR2PROCESS linkObject : attached) {
                                            if (unassigned.contains(linkObject.getQProcess())) {
                                                linkObject.getQProcess().getAttachedNReportConnections()
                                                        .remove(linkObject);
                                                linkObject.getNReport().getAttachedQProcessConnections()
                                                        .remove(linkObject);
                                                em.merge(new PReport(
                                                        SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT)
                                                                + ": " + nreport.getTitle() + " ID: "
                                                                + nreport.getID(),
                                                        PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                                        linkObject.getQProcess()));

                                                em.remove(linkObject);
                                            }
                                        }
                                        attached.clear();

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

                                        em.getTransaction().commit();

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

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

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

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

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

                                }
                            });
                        }
                    });
                    btnProcess.setEnabled(
                            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
                    pnlSingle.getRight().add(btnProcess);
                }

                /***
                 *      __  __
                 *     |  \/  | ___ _ __  _   _
                 *     | |\/| |/ _ \ '_ \| | | |
                 *     | |  | |  __/ | | | |_| |
                 *     |_|  |_|\___|_| |_|\__,_|
                 *
                 */
                final JButton btnMenu = new JButton(SYSConst.icon22menu);
                btnMenu.setPressedIcon(SYSConst.icon22Pressed);
                btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
                btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnMenu.setContentAreaFilled(false);
                btnMenu.setBorder(null);
                btnMenu.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JidePopup popup = new JidePopup();
                        popup.setMovable(false);
                        popup.getContentPane()
                                .setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                        popup.setOwner(btnMenu);
                        popup.removeExcludedComponent(btnMenu);
                        JPanel pnl = getMenu(nreport);
                        popup.getContentPane().add(pnl);
                        popup.setDefaultFocusComponent(pnl);

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

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

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

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

private JPanel getMenu(final NReport nreport) {

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

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

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

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

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

                                em.getTransaction().commit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

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

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

                GUITools.showPopup(popup, SwingConstants.WEST);

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

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

                final JPopupMenu menu = SYSCalendar.getMinutesMenu(
                        new int[] { 1, 2, 3, 4, 5, 10, 15, 20, 30, 45, 60, 120, 240, 360 }, new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();

                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    NReport myReport = em.merge(nreport);
                                    em.lock(myReport, LockModeType.OPTIMISTIC);

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

                                    em.getTransaction().commit();

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

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

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

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

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

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

        pnlMenu.add(new JSeparator());

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

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

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

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

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

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

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(nreport, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

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

                        EntityManager em = OPDE.createEM();

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

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            NReport myReport = em.merge(nreport);
                            em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSNR2PROCESS> attached = new ArrayList<SYSNR2PROCESS>(
                                    myReport.getAttachedQProcessConnections());
                            for (SYSNR2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getNReport().getAttachedQProcessConnections().remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + nreport.getTitle() + " ID: " + nreport.getID(),
                                            PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                            linkObject.getQProcess()));
                                    em.remove(linkObject);
                                }
                            }
                            attached.clear();

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

                            em.getTransaction().commit();

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

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

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

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

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

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

    }
    return pnlMenu;
}

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

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

    JideButton controlButton = GUITools.createHyperlinkButton(
            SYSTools.xx("nursingrecords.vitalparameters.btnControlling.tooltip"), SYSConst.icon22magnify1,
            new ActionListener() {
                @Override//from   w  w w.  j  a v a 2  s.  co  m
                public void actionPerformed(ActionEvent actionEvent) {
                    if (!resident.isActive()) {
                        OPDE.getDisplayManager()
                                .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                        return;
                    }
                    new DlgValueControl(resident, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    Resident myResident = em.merge(resident);
                                    em.lock(myResident, LockModeType.OPTIMISTIC);
                                    myResident.setControlling((Properties) o);
                                    em.getTransaction().commit();

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

                            }
                        }
                    });
                }
            });
    list.add(controlButton);

    return list;
}

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

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

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

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

    pnlYear.setOpaque(false);

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

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

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

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

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

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

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

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

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

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

                            EntityManager em = OPDE.createEM();

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

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

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

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

                                em.getTransaction().commit();

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

                                buildPanel();

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

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

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

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

private JPanel getMenu(final ResValue resValue) {

    final ResValueTypes vtype = resValue.getType();

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

    boolean doesNotBelongToResInfos = ResInfoTools.getInfosFor(resValue).isEmpty();

    if (doesNotBelongToResInfos && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***/* ww  w . j a  v a2 s.  c  o m*/
         *      _____    _ _ _
         *     | ____|__| (_) |_
         *     |  _| / _` | | __|
         *     | |__| (_| | | |_
         *     |_____\__,_|_|\__|
         *
         */
        final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.vitalparameters.btnEdit.tooltip",
                SYSConst.icon22edit3, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgValue(resValue.clone(), DlgValue.MODE_EDIT, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {

                            EntityManager em = OPDE.createEM();
                            try {

                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                final ResValue newValue = em.merge((ResValue) o);
                                ResValue oldValue = em.merge(resValue);

                                em.lock(oldValue, LockModeType.OPTIMISTIC);
                                newValue.setReplacementFor(oldValue);

                                for (SYSVAL2FILE oldAssignment : oldValue.getAttachedFilesConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldValue.getAttachedFilesConnections().clear();
                                for (SYSVAL2PROCESS oldAssignment : oldValue.getAttachedProcessConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldValue.getAttachedProcessConnections().clear();

                                oldValue.setEditedBy(em.merge(OPDE.getLogin().getUser()));
                                oldValue.setEditDate(new Date());
                                oldValue.setReplacedBy(newValue);

                                em.getTransaction().commit();

                                DateTime dt = new DateTime(newValue.getPit());
                                final String keyType = vtype.getID() + ".xtypes";
                                final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                        + ".year";

                                synchronized (mapType2Values) {
                                    mapType2Values.get(key).remove(resValue);
                                    mapType2Values.get(key).add(oldValue);
                                    mapType2Values.get(key).add(newValue);
                                    Collections.sort(mapType2Values.get(key));
                                }

                                createCP4Year(vtype, dt.getYear());

                                try {
                                    synchronized (cpMap) {
                                        cpMap.get(keyType).setCollapsed(false);
                                        cpMap.get(key).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();
                            }

                        }
                    }
                });
            }
        });
        btnEdit.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnEdit);

        /***
         *      ____       _      _
         *     |  _ \  ___| | ___| |_ ___
         *     | | | |/ _ \ |/ _ \ __/ _ \
         *     | |_| |  __/ |  __/ ||  __/
         *     |____/ \___|_|\___|\__\___|
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton(
                "nursingrecords.vitalparameters.btnDelete.tooltip", SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>"
                        + DateFormat.getDateTimeInstance().format(resValue.getPit()) + "</i><br/>"
                        + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o.equals(JOptionPane.YES_OPTION)) {

                                    EntityManager em = OPDE.createEM();
                                    try {

                                        em.getTransaction().begin();

                                        ResValue myValue = em.merge(resValue);
                                        myValue.setDeletedBy(em.merge(OPDE.getLogin().getUser()));

                                        for (SYSVAL2FILE file : myValue.getAttachedFilesConnections()) {
                                            em.remove(file);
                                        }
                                        myValue.getAttachedFilesConnections().clear();

                                        // Vorgangszuordnungen entfernen
                                        for (SYSVAL2PROCESS connObj : myValue.getAttachedProcessConnections()) {
                                            em.remove(connObj);
                                        }
                                        myValue.getAttachedProcessConnections().clear();
                                        myValue.getAttachedProcesses().clear();
                                        em.getTransaction().commit();

                                        DateTime dt = new DateTime(myValue.getPit());
                                        final String keyType = vtype.getID() + ".xtypes";

                                        final String key = vtype.getID() + ".xtypes."
                                                + Integer.toString(dt.getYear()) + ".year";

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

                                        createCP4Year(vtype, dt.getYear());

                                        try {
                                            synchronized (cpMap) {
                                                cpMap.get(keyType).setCollapsed(false);
                                                cpMap.get(key).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();
                                    }

                                }
                            }
                        });
            }
        });
        btnDelete.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnDelete);

        pnlMenu.add(new JSeparator());
        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */

        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgFiles(resValue, new Closure() {
                    @Override
                    public void execute(Object o) {
                        EntityManager em = OPDE.createEM();
                        final ResValue myValue = em.find(ResValue.class, resValue.getID());
                        em.close();

                        DateTime dt = new DateTime(myValue.getPit());
                        final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                + ".year";

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

                        buildPanel();
                    }
                });
            }
        });
        btnFiles.setEnabled(!resValue.isObsolete() && OPDE.isFTPworking());
        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(resValue, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

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

                        EntityManager em = OPDE.createEM();

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

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

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

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

                            em.getTransaction().commit();

                            DateTime dt = new DateTime(myValue.getPit());
                            final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                    + ".year";

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

                            createCP4Year(vtype, dt.getYear());

                            buildPanel();
                            //GUITools.flashBackground(contentmap.get(keyMonth), Color.YELLOW, 2);

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

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

private void addValue(final ResValueTypes vtype) {

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

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

            if (o != null) {

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

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

                if (myValue != null) {

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

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

                    synchronized (mapType2Values) {

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

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

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

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

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

                    createCP4Type(vtype);

                    buildPanel();

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

                }
            }

        }
    });
}