Example usage for javax.persistence LockModeType OPTIMISTIC_FORCE_INCREMENT

List of usage examples for javax.persistence LockModeType OPTIMISTIC_FORCE_INCREMENT

Introduction

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

Prototype

LockModeType OPTIMISTIC_FORCE_INCREMENT

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

Click Source Link

Document

Optimistic lock, with version update.

Usage

From source file:com.czecht.architecture.ddd.annotations.support.infrastructure.repository.jpa.GenericJpaRepository.java

public void save(A aggregate) {
    if (entityManager.contains(aggregate)) {
        //locking Aggregate Root logically protects whole aggregate
        entityManager.lock(aggregate, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    } else {/*from   w w w  .j  a v a  2 s  .  c  o  m*/
        entityManager.persist(aggregate);
    }
}

From source file:com.edugility.substantia.substance.TestCasePerson.java

@Test
public void testingJPA() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
    assertNotNull(emf);/* w  ww . j a va 2 s  . co m*/

    final EntityManager em = emf.createEntityManager();
    assertNotNull(em);

    final EntityTransaction et = em.getTransaction();
    assertNotNull(et);
    et.begin();

    final Person p = new Person();
    em.persist(p);
    em.flush();
    assertFalse(p.isTransient());
    assertTrue(p.isVersioned());
    assertEquals(Long.valueOf(1L), p.getId());
    assertEquals(Integer.valueOf(1), p.getVersion());

    et.commit();
    et.begin();

    final Person p2 = em.find(Person.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    assertNotNull(p2);
    assertFalse(p2.isTransient());
    assertTrue(p2.isVersioned());
    assertEquals(Long.valueOf(1L), p2.getId());
    assertEquals(Integer.valueOf(1), p2.getVersion());

    et.commit();
    et.begin();

    final Person p3 = em.getReference(Person.class, 1L);
    assertNotNull(p3);
    assertFalse(p3.isTransient());
    assertTrue(p3.isVersioned());
    assertEquals(Long.valueOf(1L), p3.getId());
    assertEquals(Integer.valueOf(2), p3.getVersion());

    et.commit();
    et.begin();

    assertTrue(em.contains(p));
    em.remove(p);

    et.commit();

    em.close();

    emf.close();
}

From source file:com.hiperium.dao.common.generic.GenericDAO.java

/**
 * //w w  w .j ava2s.  c o  m
 * @param id
 * @param lock
 * @param bypassCache
 * @return
 */
protected T findById(ID id, boolean lock, boolean bypassCache) {
    this.logger.debug("findById - START");
    T entity = null;
    if (bypassCache) {
        this.entityManager.setProperty(RETRIEVE_MODE, CacheRetrieveMode.BYPASS);
        this.entityManager.setProperty(STORE_MODE, CacheStoreMode.REFRESH);
        entity = this.entityManager.find(this.entityClass, id);
    } else {
        entity = this.entityManager.find(this.entityClass, id);
    }
    if (lock) {
        this.entityManager.lock(entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    }
    this.logger.debug("findById - END");
    return entity;
}

From source file:bq.jpa.demo.lock.service.LockService.java

/**
 * modify employees salary//from w  w w  . ja  v a 2s.c  o  m
 */
@Transactional
public void doModify() {
    try {
        lock.lock();

        TypedQuery<Employee> query = em.createQuery("SELECT e FROM jpa_lock_employee e", Employee.class);
        List<Employee> results = query.getResultList();

        for (Employee employee : results) {
            em.lock(employee, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
            employee.setSalary(employee.getSalary() + 33);
        }
        System.out.println("[Thread-writing] lock employee");

        // let read thread continue
        readCondition.signal();
        writeCondition.await();

        System.out.println("[Thread-writing] modify employee salary!");
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

From source file:op.care.bhp.PnlBHP.java

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

    ActionListener applyActionListener = new ActionListener() {
        @Override//  w  ww. j  a  va  2  s.co  m
        public void actionPerformed(ActionEvent actionEvent) {
            if (bhp.getState() != BHPTools.STATE_OPEN) {
                return;
            }
            if (bhp.getPrescription().isClosed()) {
                return;
            }

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

                }

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

                if (bhp.getPrescription().isWeightControlled()) {
                    new DlgYesNo(SYSConst.icon48scales, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (SYSTools.catchNull(o).isEmpty()) {
                                weight = null;
                            } else {
                                weight = (BigDecimal) o;
                            }
                        }
                    }, "nursingrecords.bhp.weight", null, new Validator<BigDecimal>() {
                        @Override
                        public boolean isValid(String value) {
                            BigDecimal bd = parse(value);
                            return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                        }

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

                }

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

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

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

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

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

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

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

                    em.getTransaction().commit();

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

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

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

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

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

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

    String title;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    }

                });
                cptitle.getRight().add(btnOpenStock);
            }

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

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

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

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

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

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

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

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

                        if (BHPTools.isChangeable(bhp)) {

                            if (bhp.getPrescription().isWeightControlled()) {
                                new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                    @Override
                                    public void execute(Object o) {
                                        if (SYSTools.catchNull(o).isEmpty()) {
                                            weight = null;
                                        } else {
                                            weight = (BigDecimal) o;
                                        }
                                    }
                                }, "nursingrecords.bhp.weight", null, new Validator<BigDecimal>() {
                                    @Override
                                    public boolean isValid(String value) {
                                        BigDecimal bd = parse(value);
                                        return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                                    }

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

                            }

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

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

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

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

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

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

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

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

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

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

                    BHP outcomeBHP = BHPTools.getComment(bhp);

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

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

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

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

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

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

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

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

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

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

        cptitle.getRight().add(btnInfo);

    }

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

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

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

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

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

From source file:op.care.med.structure.DlgProduct.java

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

    if (!saveOK())
        return;//from  w  w  w . java 2 s . c o  m

    EntityManager em = OPDE.createEM();
    try {
        em.getTransaction().begin();
        MedProducts myProduct = em.merge(product);

        myProduct.setText(txtName.getText().trim());
        myProduct.setSideEffects(txtSideEffects.getText().trim());
        myProduct.setACME(em.merge((ACME) cmbAcme.getSelectedItem()));

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

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

    //hier gehts weiter. prf auch die anderen locks bei den anderen editoren

}

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

private JPanel createNPPanel(final NursingProcess np) {
    /***/* ww w.ja  v  a2 s  . com*/
     *                          _        ____ ____  _  _     _   _ ____
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |   | \ | |  _ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_  |  \| | |_) |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| | |\  |  __/
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_|   |_| \_|_|
     *
     */
    if (!contenPanelMap.containsKey(np)) {
        String title = "<html><table border=\"0\">";

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

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

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

        if (!np.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(Integer.toString(np.getAttachedFilesConnections().size()),
                    SYSConst.icon22greenStar);
            btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
            btnFiles.setForeground(Color.BLUE);
            btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnFiles.setFont(SYSConst.ARIAL18BOLD);
            btnFiles.setPressedIcon(SYSConst.icon22Pressed);
            btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
            btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnFiles.setContentAreaFilled(false);
            btnFiles.setBorder(null);
            btnFiles.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    Closure fileHandleClosure = np.isClosed() ? null : new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final NursingProcess myNP = em.find(NursingProcess.class, np.getID());
                            em.close();
                            // Refresh Display
                            valuecache.get(np.getCategory()).remove(np);
                            contenPanelMap.remove(np);
                            valuecache.get(myNP.getCategory()).add(myNP);
                            Collections.sort(valuecache.get(myNP.getCategory()));

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

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

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

                            EntityManager em = OPDE.createEM();

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

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

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

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

                                em.getTransaction().commit();

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

                                createCP4(myNP.getCategory());
                                buildPanel();

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

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

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

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

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

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

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

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

    return contenPanelMap.get(np);
}

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

private JPanel getMenu(final NursingProcess np) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                em.getTransaction().commit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                em.getTransaction().commit();

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

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

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

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

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

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

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

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

                GUITools.showPopup(popup, SwingConstants.WEST);

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

        pnlMenu.add(new JSeparator());

        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Closure fileHandleClosure = np.isClosed() ? null : new Closure() {
                    @Override
                    public void execute(Object o) {
                        EntityManager em = OPDE.createEM();
                        final NursingProcess myNP = em.find(NursingProcess.class, np.getID());
                        em.close();
                        // Refresh Display
                        valuecache.get(np.getCategory()).remove(np);
                        contenPanelMap.remove(np);
                        valuecache.get(myNP.getCategory()).add(myNP);
                        Collections.sort(valuecache.get(myNP.getCategory()));

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

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

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

                        EntityManager em = OPDE.createEM();

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

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

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

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

                            em.getTransaction().commit();

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

                            createCP4(myNP.getCategory());
                            buildPanel();

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

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

    }
    return pnlMenu;
}

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

private CollapsiblePane createCP4(final Prescription prescription) {
    /***/* w  w w .j  a  v a2s.c om*/
     *                          _        ____ ____  _  _    ______                          _       _   _           __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /  _ \ _ __ ___  ___  ___ _ __(_)_ __ | |_(_) ___  _ __\ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| || |_) | '__/ _ \/ __|/ __| '__| | '_ \| __| |/ _ \| '_ \| |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| ||  __/| | |  __/\__ \ (__| |  | | |_) | |_| | (_) | | | | |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||_|   |_|  \___||___/\___|_|  |_| .__/ \__|_|\___/|_| |_| |
     *                                                     \_\                               |_|                    /_/
     */
    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 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  ww w  .ja v a  2s .c  o 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;
}