Example usage for javax.persistence EntityManager remove

List of usage examples for javax.persistence EntityManager remove

Introduction

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

Prototype

public void remove(Object entity);

Source Link

Document

Remove the entity instance.

Usage

From source file:com.jada.order.document.InvoiceEngine.java

public void saveOrder() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    if (masterHeader == null
            || !masterHeader.getRecUpdateDatetime().equals(invoiceHeader.getRecUpdateDatetime())) {
        if (invoiceHeader.getInvoiceNum() == null) {
            invoiceHeader.setInvoiceNum(
                    generateNumber(orderHeader.getSiteDomain().getSite(), Constants.SEQUENCE_INVOICE));
        }/* w  ww .ja  va 2  s  .co  m*/
        if (masterHeader == null) {
            masterHeader = new InvoiceHeader();
        }
        masterHeader.setInvoiceNum(invoiceHeader.getInvoiceNum());
        masterHeader.setShippingTotal(invoiceHeader.getShippingTotal());
        masterHeader.setInvoiceTotal(invoiceHeader.getInvoiceTotal());
        masterHeader.setInvoiceStatus(invoiceHeader.getInvoiceStatus());
        masterHeader.setInvoiceDate(invoiceHeader.getInvoiceDate());
        masterHeader.setRecUpdateBy(invoiceHeader.getRecUpdateBy());
        masterHeader.setRecUpdateDatetime(invoiceHeader.getRecUpdateDatetime());
        masterHeader.setRecCreateBy(invoiceHeader.getRecCreateBy());
        masterHeader.setRecCreateDatetime(invoiceHeader.getRecCreateDatetime());
        masterHeader.setOrderHeader(orderHeader);
        orderHeader.getInvoiceHeaders().add(masterHeader);

        // Copy data from invoiceHeader to masterHeader
        if (masterHeader.getInvoiceHeaderId() == null) {
            em.persist(masterHeader);
        }
        invoiceHeader.setInvoiceHeaderId(masterHeader.getInvoiceHeaderId());

        if (masterHeader != null) {
            Iterator<?> taxIterator = masterHeader.getInvoiceTaxes().iterator();
            while (taxIterator.hasNext()) {
                InvoiceDetailTax invoiceDetailTax = (InvoiceDetailTax) taxIterator.next();
                if (invoiceDetailTax.getInvoiceDetail() != null) {
                    continue;
                }
                em.remove(invoiceDetailTax);
                taxIterator.remove();
            }
        }

        Iterator<?> taxIterator = invoiceHeader.getInvoiceTaxes().iterator();
        while (taxIterator.hasNext()) {
            InvoiceDetailTax invoiceDetailTax = (InvoiceDetailTax) taxIterator.next();
            if (invoiceDetailTax.getInvoiceDetail() != null) {
                continue;
            }
            InvoiceDetailTax masterTax = new InvoiceDetailTax();
            //            masterTax.setInvoiceDetailTaxId(invoiceDetailTax.getInvoiceDetailTaxId());
            masterTax.setTaxName(invoiceDetailTax.getTaxName());
            masterTax.setTaxAmount(invoiceDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(invoiceDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(invoiceDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(invoiceDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(invoiceDetailTax.getRecCreateDatetime());
            masterTax.setTax(invoiceDetailTax.getTax());
            masterTax.setInvoiceDetail(null);
            masterTax.setInvoiceHeader(masterHeader);
            em.persist(masterTax);
        }
    }

    Iterator<?> iterator = masterHeader.getInvoiceDetails().iterator();
    while (iterator.hasNext()) {
        InvoiceDetail masterDetail = (InvoiceDetail) iterator.next();
        Iterator<?> taxIterator = masterDetail.getInvoiceDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            InvoiceDetailTax masterDetailTax = (InvoiceDetailTax) taxIterator.next();
            em.remove(masterDetailTax);
            taxIterator.remove();
        }
        em.remove(masterDetail);
        iterator.remove();
    }

    iterator = invoiceHeader.getInvoiceDetails().iterator();
    while (iterator.hasNext()) {
        InvoiceDetail invoiceDetail = (InvoiceDetail) iterator.next();
        InvoiceDetail masterDetail = new InvoiceDetail();
        masterDetail.setInvoiceHeader(masterHeader);
        masterDetail.setSeqNum(invoiceDetail.getSeqNum());
        masterDetail.setItemInvoiceQty(invoiceDetail.getItemInvoiceQty());
        masterDetail.setItemInvoiceAmount(invoiceDetail.getItemInvoiceAmount());
        masterDetail.setRecUpdateBy(invoiceDetail.getRecUpdateBy());
        masterDetail.setRecUpdateDatetime(invoiceDetail.getRecUpdateDatetime());
        masterDetail.setRecCreateBy(invoiceDetail.getRecCreateBy());
        masterDetail.setRecCreateDatetime(invoiceDetail.getRecCreateDatetime());
        masterDetail.setOrderItemDetail(invoiceDetail.getOrderItemDetail());
        em.persist(masterDetail);
        masterHeader.getInvoiceDetails().add(masterDetail);

        Iterator<?> taxIterator = invoiceDetail.getInvoiceDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            InvoiceDetailTax invoiceDetailTax = (InvoiceDetailTax) taxIterator.next();
            InvoiceDetailTax masterTax = new InvoiceDetailTax();
            masterTax.setTaxName(invoiceDetailTax.getTaxName());
            masterTax.setTaxAmount(invoiceDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(invoiceDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(invoiceDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(invoiceDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(invoiceDetailTax.getRecCreateDatetime());
            masterTax.setInvoiceDetail(masterDetail);
            masterTax.setTax(invoiceDetailTax.getTax());
            masterDetail.getInvoiceDetailTaxes().add(masterTax);
            masterTax.setInvoiceHeader(masterHeader);
            em.persist(masterTax);
        }
    }

    PaymentTran paymentTran = invoiceHeader.getPaymentTran();
    PaymentTran masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getPaymentTran();
    }
    if (isSavePaymentTran(paymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, paymentTran);
        masterHeader.setPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }

    PaymentTran voidPaymentTran = invoiceHeader.getVoidPaymentTran();
    masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getVoidPaymentTran();
    }
    if (isSavePaymentTran(voidPaymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, voidPaymentTran);
        masterHeader.setVoidPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }
}

From source file:com.jada.order.document.CreditEngine.java

public void saveOrder() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    if (masterHeader == null
            || !masterHeader.getRecUpdateDatetime().equals(creditHeader.getRecUpdateDatetime())) {
        if (creditHeader.getCreditNum() == null) {
            creditHeader.setCreditNum(//from ww  w.  j a  va2 s .com
                    generateNumber(orderHeader.getSiteDomain().getSite(), Constants.SEQUENCE_CREDIT));
        }
        if (masterHeader == null) {
            masterHeader = new CreditHeader();
        }
        masterHeader.setCreditNum(creditHeader.getCreditNum());
        masterHeader.setShippingTotal(creditHeader.getShippingTotal());
        masterHeader.setCreditTotal(creditHeader.getCreditTotal());
        masterHeader.setCreditStatus(creditHeader.getCreditStatus());
        masterHeader.setCreditDate(creditHeader.getCreditDate());
        masterHeader.setUpdateInventory(creditHeader.getUpdateInventory());
        masterHeader.setRecUpdateBy(creditHeader.getRecUpdateBy());
        masterHeader.setRecUpdateDatetime(creditHeader.getRecUpdateDatetime());
        masterHeader.setRecCreateBy(creditHeader.getRecCreateBy());
        masterHeader.setRecCreateDatetime(creditHeader.getRecCreateDatetime());
        masterHeader.setOrderHeader(orderHeader);
        masterHeader.setInvoiceHeader(invoiceHeader);
        orderHeader.getCreditHeaders().add(masterHeader);

        // Copy data from creditHeader to masterHeader
        if (masterHeader.getCreditHeaderId() == null) {
            em.persist(masterHeader);
        }
        creditHeader.setCreditHeaderId(masterHeader.getCreditHeaderId());

        if (masterHeader != null) {
            Iterator<?> taxIterator = masterHeader.getCreditTaxes().iterator();
            while (taxIterator.hasNext()) {
                CreditDetailTax creditDetailTax = (CreditDetailTax) taxIterator.next();
                if (creditDetailTax.getCreditDetail() != null) {
                    continue;
                }
                em.remove(creditDetailTax);
                taxIterator.remove();
            }
        }

        Iterator<?> taxIterator = creditHeader.getCreditTaxes().iterator();
        while (taxIterator.hasNext()) {
            CreditDetailTax creditDetailTax = (CreditDetailTax) taxIterator.next();
            if (creditDetailTax.getCreditDetail() != null) {
                continue;
            }
            CreditDetailTax masterTax = new CreditDetailTax();
            masterTax.setCreditDetailTaxId(creditDetailTax.getCreditDetailTaxId());
            masterTax.setTaxName(creditDetailTax.getTaxName());
            masterTax.setTaxAmount(creditDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(creditDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(creditDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(creditDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(creditDetailTax.getRecCreateDatetime());
            masterTax.setCreditDetail(null);
            masterTax.setCreditHeader(masterHeader);
            masterTax.setTax(creditDetailTax.getTax());
            masterTax.setCreditDetailTaxId(null);
            em.persist(masterTax);
        }
    }

    Iterator<?> iterator = masterHeader.getCreditDetails().iterator();
    while (iterator.hasNext()) {
        CreditDetail masterDetail = (CreditDetail) iterator.next();
        Iterator<?> taxIterator = masterDetail.getCreditDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            CreditDetailTax masterDetailTax = (CreditDetailTax) taxIterator.next();
            em.remove(masterDetailTax);
            taxIterator.remove();
        }
        em.remove(masterDetail);
        iterator.remove();
    }

    iterator = creditHeader.getCreditDetails().iterator();
    while (iterator.hasNext()) {
        CreditDetail creditDetail = (CreditDetail) iterator.next();
        CreditDetail masterDetail = new CreditDetail();
        masterDetail.setCreditHeader(masterHeader);
        masterDetail.setSeqNum(creditDetail.getSeqNum());
        masterDetail.setItemCreditQty(creditDetail.getItemCreditQty());
        masterDetail.setItemCreditAmount(creditDetail.getItemCreditAmount());
        masterDetail.setRecUpdateBy(creditDetail.getRecUpdateBy());
        masterDetail.setRecUpdateDatetime(creditDetail.getRecUpdateDatetime());
        masterDetail.setRecCreateBy(creditDetail.getRecCreateBy());
        masterDetail.setRecCreateDatetime(creditDetail.getRecCreateDatetime());
        masterDetail.setOrderItemDetail(creditDetail.getOrderItemDetail());
        em.persist(masterDetail);
        masterHeader.getCreditDetails().add(masterDetail);

        Iterator<?> taxIterator = creditDetail.getCreditDetailTaxes().iterator();
        while (taxIterator.hasNext()) {
            CreditDetailTax creditDetailTax = (CreditDetailTax) taxIterator.next();
            CreditDetailTax masterTax = new CreditDetailTax();
            masterTax.setTaxName(creditDetailTax.getTaxName());
            masterTax.setTaxAmount(creditDetailTax.getTaxAmount());
            masterTax.setRecUpdateBy(creditDetailTax.getRecUpdateBy());
            masterTax.setRecUpdateDatetime(creditDetailTax.getRecUpdateDatetime());
            masterTax.setRecCreateBy(creditDetailTax.getRecCreateBy());
            masterTax.setRecCreateDatetime(creditDetailTax.getRecCreateDatetime());
            masterTax.setCreditDetail(masterDetail);
            masterDetail.getCreditDetailTaxes().add(masterTax);
            masterTax.setCreditHeader(masterHeader);
            masterTax.setTax(creditDetailTax.getTax());
            em.persist(masterTax);
        }
    }

    PaymentTran paymentTran = creditHeader.getPaymentTran();
    PaymentTran masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getPaymentTran();
    }
    if (isSavePaymentTran(paymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, paymentTran);
        masterHeader.setPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }

    PaymentTran voidPaymentTran = creditHeader.getVoidPaymentTran();
    masterPaymentTran = null;
    if (masterHeader != null) {
        masterPaymentTran = masterHeader.getVoidPaymentTran();
    }
    if (isSavePaymentTran(voidPaymentTran, masterPaymentTran)) {
        if (masterPaymentTran == null) {
            masterPaymentTran = new PaymentTran();
        }
        PropertyUtils.copyProperties(masterPaymentTran, voidPaymentTran);
        masterHeader.setVoidPaymentTran(masterPaymentTran);
        if (masterPaymentTran.getPaymentTranId() == null) {
            em.persist(masterPaymentTran);
        }
    }
}

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward removeCustomAttributeDetails(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Throwable {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;
    AdminBean adminBean = getAdminBean(request);
    Site site = adminBean.getSite();//w  ww . j  ava 2 s  . c  om

    JSONEscapeObject jsonResult = new JSONEscapeObject();
    jsonResult.put("status", Constants.WEBSERVICE_STATUS_SUCCESS);

    Long customAttribGroupId = Format.getLong(form.getCustomAttribGroupId());
    CustomAttributeGroup customAttributeGroup = CustomAttributeGroupDAO.load(site.getSiteId(),
            customAttribGroupId);
    String customAttribDetailIds[] = form.getCustomAttribDetailIds();
    if (customAttribDetailIds != null) {
        for (int i = 0; i < customAttribDetailIds.length; i++) {
            CustomAttributeDetail customAttributeDetail = (CustomAttributeDetail) em
                    .find(CustomAttributeDetail.class, Format.getLong(customAttribDetailIds[i]));
            if (customAttributeDetail.getCustomAttribute()
                    .getCustomAttribTypeCode() == Constants.CUSTOM_ATTRIBUTE_TYPE_SKU_MAKEUP) {
                String sql = "select  count(*) " + "from     ItemAttributeDetail itemAttributeDetail "
                        + "where     itemAttributeDetail.customAttributeDetail = :customAttributeDetail "
                        + "and     itemAttributeDetail.item.itemTypeCd = :itemTypeCd";
                Query query = em.createQuery(sql);
                query.setParameter("customAttributeDetail", customAttributeDetail);
                query.setParameter("itemTypeCd", Constants.ITEM_TYPE_SKU);
                Long count = (Long) query.getSingleResult();
                if (count.intValue() > 0) {
                    jsonResult.put("status", Constants.WEBSERVICE_STATUS_FAILED);
                    jsonResult.put("reason", Constants.WEBSERVICE_REASON_INUSE);
                    streamWebService(response, jsonResult.toHtmlString());
                    return null;
                }
            }

            String sql = "delete " + "from   ItemAttributeDetail itemAttributeDetail "
                    + "where  itemAttributeDetail.customAttributeDetail = :customAttributeDetail ";
            Query query = em.createQuery(sql);
            query.setParameter("customAttributeDetail", customAttributeDetail);
            query.executeUpdate();

            customAttributeGroup.getCustomAttributeDetails().remove(customAttributeDetail);
            em.remove(customAttributeDetail);
        }
    }
    streamWebService(response, jsonResult.toHtmlString());
    return null;
}

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

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

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

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

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

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

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

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

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

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

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

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

    return pnlMenu;
}

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

private JPanel getMenu(final NReport nreport) {

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

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

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

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

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

                                em.getTransaction().commit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

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

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

                GUITools.showPopup(popup, SwingConstants.WEST);

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

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

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

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

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

                                    em.getTransaction().commit();

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

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

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

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

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

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

        pnlMenu.add(new JSeparator());

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

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

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

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

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

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

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

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

                        EntityManager em = OPDE.createEM();

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

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

    }
    return pnlMenu;
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

public void addPublisherAssertions(AddPublisherAssertions body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/* w w w  . j  av  a  2 s.c  o  m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateAddPublisherAssertions(em, body);

        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = body.getPublisherAssertion();
        for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) {

            org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion();

            MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion);

            org.apache.juddi.model.PublisherAssertion existingPubAssertion = em
                    .find(modelPubAssertion.getClass(), modelPubAssertion.getId());
            boolean persistNewAssertion = true;
            if (existingPubAssertion != null) {
                if (modelPubAssertion.getTmodelKey().equalsIgnoreCase(existingPubAssertion.getTmodelKey())
                        && modelPubAssertion.getKeyName().equalsIgnoreCase(existingPubAssertion.getKeyName())
                        && modelPubAssertion.getKeyValue()
                                .equalsIgnoreCase(existingPubAssertion.getKeyValue())) {
                    // This pub assertion is already been "asserted".  Simply need to set the "check" value on the existing (and persistent) assertion
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByFromKey()))
                        existingPubAssertion.setFromCheck("true");
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByToKey()))
                        existingPubAssertion.setToCheck("true");

                    persistNewAssertion = false;
                } else {
                    // Otherwise, it is a new relationship between these entities.  Remove the old one so the new one can be added.
                    // TODO: the model only seems to allow one assertion per two business (primary key is fromKey and toKey). Spec seems to imply as 
                    // many relationships as desired (the differentiator would be the keyedRef values).
                    em.remove(existingPubAssertion);
                }
            }

            if (persistNewAssertion) {
                org.apache.juddi.model.BusinessEntity beFrom = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey());
                org.apache.juddi.model.BusinessEntity beTo = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey());
                modelPubAssertion.setBusinessEntityByFromKey(beFrom);
                modelPubAssertion.setBusinessEntityByToKey(beTo);

                modelPubAssertion.setFromCheck("false");
                modelPubAssertion.setToCheck("false");

                em.persist(modelPubAssertion);

                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey()))
                    modelPubAssertion.setFromCheck("true");
                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey()))
                    modelPubAssertion.setToCheck("true");
            }

        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

public void removeFilter(Long id) throws PersistenceException {
    TransactionContext tc = null;/* ww  w .ja  va  2s . co m*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        Filter f = em.find(Filter.class, id);
        List<FilterValue> values = f.getValues();
        if (values != null && !values.isEmpty()) {
            for (FilterValue fv : values) {
                em.remove(fv);
            }
        }
        values.clear();
        em.remove(f);
        tx.begin();
        tx.commit();
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

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

@Override
public Long saveFilter(Filter f, String userName) throws PersistenceException {
    TransactionContext tc = null;/*from  ww  w . j  ava 2 s.  com*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Long id = null;
        Filter orig = null;
        if (f.getId() != null)
            orig = em.find(Filter.class, f.getId());
        if (orig != null) {
            if (orig.getValues() != null && !orig.getValues().isEmpty()) {
                for (FilterValue fv : orig.getValues()) {
                    em.remove(fv);
                }
                orig.getValues().clear();
            }
            orig.setName(f.getName());
            orig.setClassName(f.getClassName());
            orig.setViewName(f.getViewName());
            orig.setUserName(userName);
            ArrayList<FilterValue> l = new ArrayList<FilterValue>();
            orig.setValues(l);
            for (FilterValue fv : f.getValues()) {
                fv.setId(null);
                fv.setFilter(orig);
                em.persist(fv);
                l.add(fv);
            }
            if (f.getSortAttribute() != null) {
                orig.setSortAttribute(f.getSortAttribute());
                orig.setSortAsc(f.getSortAsc());
            }

            em.merge(orig);
            id = orig.getId();
        } else {
            f.setId(null);
            f.setCreateUser(userName);
            f.setUserName(userName);
            for (FilterValue fv : f.getValues())
                fv.setId(null);
            em.persist(f);
            id = f.getId();
        }

        tx.commit();
        return id;
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

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

@Override
public void saveConfiguration(String viewName, String className, int nbRows, List<HeaderInfo> headers,
        ScreenLabels sl, String connectedUser, LanguageEnum language) throws PersistenceException {
    TransactionContext tc = null;//from   w  w  w.  j  a  va  2s. c o m
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        List<ScreenConfig> l = em.createQuery(
                "select o from ScreenConfig o where o.viewName = :vN and o.className = :clazz and o.createUser = :user")
                .setParameter("vN", viewName).setParameter("clazz", className)
                .setParameter("user", connectedUser).getResultList();
        ScreenConfig sc = null;
        Map<String, ScreenHeaderInfo> headerByAttribute = new HashMap<String, ScreenHeaderInfo>();
        if (l != null && !l.isEmpty()) {
            sc = l.get(0);
            if (l.size() > 1) {
                for (int i = 1; i < l.size(); i++) {
                    em.remove(l.get(i));
                }
            }
            for (ScreenHeaderInfo hi : sc.getHeaders()) {
                headerByAttribute.put(hi.getAttribute(), hi);
            }
        } else {
            sc = new ScreenConfig();
            sc.setViewName(viewName);
            sc.setClassName(className);
            sc.setCreateUser(connectedUser);
            em.persist(sc);
        }
        sc.setNbRows(nbRows);

        if (sl != null) {
            boolean found = false;
            if (sc.getLabels() != null && !sc.getLabels().isEmpty()) {
                for (ScreenLabels lb : sc.getLabels()) {
                    if (lb.getLanguage().equals(language)) {
                        if (sl.getCreateLabel() != null)
                            lb.setCreateLabel(sl.getCreateLabel());
                        if (sl.getEditLabel() != null)
                            lb.setEditLabel(sl.getEditLabel());
                        if (sl.getFormLabel() != null)
                            lb.setFormLabel(sl.getFormLabel());
                        if (sl.getSelectLabel() != null)
                            lb.setSelectLabel(sl.getSelectLabel());
                        if (sl.getTableLabel() != null)
                            lb.setTableLabel(sl.getTableLabel());
                        if (sl.getViewLabel() != null)
                            lb.setViewLabel(sl.getViewLabel());
                        em.merge(lb);
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                sl.setScreenConfig(sc);
                em.persist(sl);
            }
        }
        for (HeaderInfo hi : headers) {
            ScreenHeaderInfo shi = headerByAttribute.get(hi.getAttribute());
            if (shi == null) {
                shi = new ScreenHeaderInfo();
                shi.setAttribute(hi.getAttribute());
                shi.setDisplayed(hi.isDisplayed());
                shi.setScreenConfig(sc);
                shi.setIndex(hi.getIndex());
                em.persist(shi);
            } else {
                shi.setDisplayed(hi.isDisplayed());
                shi.setScreenConfig(sc);
                shi.setIndex(hi.getIndex());
                em.merge(shi);
            }
            if (hi.getLabel() != null) {
                boolean found = false;
                List<Label> labels = shi.getLabels();
                if (labels != null && !labels.isEmpty()) {
                    Iterator<Label> it = labels.iterator();
                    while (it.hasNext()) {
                        Label lbl = it.next();
                        if (lbl.getLanguage().equals(language)) {
                            if (hi.getLabel().length() > 0) {
                                lbl.setLabel(hi.getLabel());
                                em.merge(lbl);
                            } else {
                                em.remove(lbl);
                                it.remove();
                            }
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    Label lbl = new Label();
                    lbl.setLanguage(language);
                    lbl.setLabel(hi.getLabel());
                    lbl.setHeader(shi);
                    em.persist(lbl);
                }
            }
        }
        tx.commit();
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

@Override
@SuppressWarnings("unchecked")
public Set<Entity> commit(CommitContext context) {
    if (log.isDebugEnabled())
        log.debug("commit: commitInstances=" + context.getCommitInstances() + ", removeInstances="
                + context.getRemoveInstances());

    Set<Entity> res = new HashSet<>();
    List<Entity> persisted = new ArrayList<>();
    List<BaseGenericIdEntity> identityEntitiesToStoreDynamicAttributes = new ArrayList<>();
    List<CategoryAttributeValue> attributeValuesToRemove = new ArrayList<>();

    try (Transaction tx = persistence.createTransaction(storeName)) {
        EntityManager em = persistence.getEntityManager(storeName);
        checkPermissions(context);/*from   ww w .  j a  v  a2 s  . com*/

        if (!context.isSoftDeletion())
            em.setSoftDeletion(false);

        persistence.getEntityManagerContext(storeName).setDbHints(context.getDbHints());

        List<BaseGenericIdEntity> entitiesToStoreDynamicAttributes = new ArrayList<>();

        // persist new
        for (Entity entity : context.getCommitInstances()) {
            if (PersistenceHelper.isNew(entity)) {
                attributeSecurity.beforePersist(entity);
                em.persist(entity);
                checkOperationPermitted(entity, ConstraintOperationType.CREATE);
                if (!context.isDiscardCommitted()) {
                    entityFetcher.fetch(entity, getViewFromContextOrNull(context, entity), true);
                    res.add(entity);
                }
                persisted.add(entity);

                if (entityHasDynamicAttributes(entity)) {
                    if (entity instanceof BaseDbGeneratedIdEntity) {
                        identityEntitiesToStoreDynamicAttributes.add((BaseGenericIdEntity) entity);
                    } else {
                        entitiesToStoreDynamicAttributes.add((BaseGenericIdEntity) entity);
                    }
                }
            }
        }

        // merge the rest - instances can be detached or not
        for (Entity entity : context.getCommitInstances()) {
            if (!PersistenceHelper.isNew(entity)) {
                if (isAuthorizationRequired()) {
                    security.checkSecurityToken(entity, null);
                }
                security.restoreSecurityStateAndFilteredData(entity);
                attributeSecurity.beforeMerge(entity);

                Entity merged = em.merge(entity);
                entityFetcher.fetch(merged, getViewFromContext(context, entity));
                attributeSecurity.afterMerge(merged);

                checkOperationPermitted(merged, ConstraintOperationType.UPDATE);
                if (!context.isDiscardCommitted()) {
                    res.add(merged);
                }
                if (entityHasDynamicAttributes(entity)) {
                    BaseGenericIdEntity originalBaseGenericIdEntity = (BaseGenericIdEntity) entity;
                    BaseGenericIdEntity mergedBaseGenericIdEntity = (BaseGenericIdEntity) merged;
                    mergedBaseGenericIdEntity
                            .setDynamicAttributes(originalBaseGenericIdEntity.getDynamicAttributes());
                    entitiesToStoreDynamicAttributes.add(mergedBaseGenericIdEntity);
                }
            }
        }

        for (BaseGenericIdEntity entity : entitiesToStoreDynamicAttributes) {
            dynamicAttributesManagerAPI.storeDynamicAttributes(entity);
        }

        // remove
        for (Entity entity : context.getRemoveInstances()) {
            if (isAuthorizationRequired()) {
                security.checkSecurityToken(entity, null);
            }
            security.restoreSecurityStateAndFilteredData(entity);

            Entity e;
            if (entity instanceof SoftDelete) {
                attributeSecurity.beforeMerge(entity);
                e = em.merge(entity);
                entityFetcher.fetch(e, getViewFromContext(context, entity));
                attributeSecurity.afterMerge(e);
            } else {
                e = em.merge(entity);
            }
            checkOperationPermitted(e, ConstraintOperationType.DELETE);
            em.remove(e);
            if (!context.isDiscardCommitted()) {
                res.add(e);
            }

            if (entityHasDynamicAttributes(entity)) {
                Map<String, CategoryAttributeValue> dynamicAttributes = ((BaseGenericIdEntity) entity)
                        .getDynamicAttributes();

                //dynamicAttributes checked for null in entityHasDynamicAttributes()
                //noinspection ConstantConditions
                for (CategoryAttributeValue categoryAttributeValue : dynamicAttributes.values()) {
                    if (!PersistenceHelper.isNew(categoryAttributeValue)) {
                        if (Stores.isMain(storeName)) {
                            em.remove(categoryAttributeValue);
                        } else {
                            attributeValuesToRemove.add(categoryAttributeValue);
                        }
                        if (!context.isDiscardCommitted()) {
                            res.add(categoryAttributeValue);
                        }
                    }
                }
            }

            if (!context.isDiscardCommitted() && isAuthorizationRequired()
                    && userSessionSource.getUserSession().hasConstraints()) {
                security.filterByConstraints(res);
            }
        }

        tx.commit();
    }

    if (!attributeValuesToRemove.isEmpty()) {
        try (Transaction tx = persistence.createTransaction()) {
            EntityManager em = persistence.getEntityManager();
            for (CategoryAttributeValue entity : attributeValuesToRemove) {
                em.remove(entity);
            }
            tx.commit();
        }
    }

    try (Transaction tx = persistence.createTransaction(storeName)) {
        for (BaseGenericIdEntity entity : identityEntitiesToStoreDynamicAttributes) {
            dynamicAttributesManagerAPI.storeDynamicAttributes(entity);
        }
        tx.commit();
    }

    if (!context.isDiscardCommitted() && isAuthorizationRequired()
            && userSessionSource.getUserSession().hasConstraints()) {
        security.applyConstraints(res);
    }

    if (!context.isDiscardCommitted()) {
        for (Entity entity : res) {
            if (!persisted.contains(entity)) {
                attributeSecurity.afterCommit(entity);
            }
        }
        updateReferences(persisted, res);
    }

    return res;
}