Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

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

@Override
public INakedObject getLinkedObject(String nakedObjectName, com.hiperf.common.ui.shared.util.Id id,
        String attributeName) throws PersistenceException {
    INakedObject o = null;/*  w  w  w  .  jav  a 2 s  . c o  m*/
    EntityManager em = null;
    try {
        em = getEntityManager();
        if (id.getFieldNames().size() == 1) {
            o = (INakedObject) em.find(Class.forName(nakedObjectName), id.getFieldValues().get(0));
        } else {
            Class c = Class.forName(nakedObjectName);
            o = (INakedObject) em.find(c, getCompositeId(c, id.getFieldNames(), id.getFieldValues()));
        }
        if (o != null) {
            return deproxyLinkedObject(o, attributeName, em);
        }
        return null;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in getLinkedObject " + e.getMessage(), e);
        throw new PersistenceException("Exception in getLinkedObject " + e.getMessage(), e);
    } finally {
        closeEntityManager(em);
    }
}

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

private INakedObject getObject(Class<?> clazz, com.hiperf.common.ui.shared.util.Id id, EntityManager em)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    INakedObject o;/*w w w. j a v  a  2 s  .c  o  m*/
    if (id.getFieldValues().size() == 1) {
        o = (INakedObject) em.find(clazz, id.getFieldValues().get(0));
    } else {
        o = (INakedObject) em.find(clazz, getCompositeId(clazz, id.getFieldNames(), id.getFieldValues()));
    }
    return o;
}

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

@Override
public List<INakedObject> reload(String nakedObjectName, List<String> idFields, List<List<Object>> idList)
        throws PersistenceException {
    TransactionContext tc = null;//from  www  .  j  a  v a2  s .  c om
    List<INakedObject> l = new ArrayList<INakedObject>(idList.size());
    try {
        Class<?> c = Class.forName(nakedObjectName);
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        if (idFields.size() == 1) {
            for (List myId : idList) {
                l.add((INakedObject) em.find(c, myId.get(0)));
            }
            l = deproxyEntities(nakedObjectName, l, true, null);
        } else {
            for (List myId : idList) {
                l.add((INakedObject) em.find(c, getCompositeId(c, idFields, myId)));
            }
            l = deproxyEntities(nakedObjectName, l, true, null);
        }
        return l;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in reload : " + e.getMessage(), e);
        throw new PersistenceException("Exception in reload : " + e.getMessage(), e);
    } finally {
        finalizeTx(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  w w  w  .ja va  2  s . c o  m
    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 String replaceFile(String fileClass, String fileNameField, String fileStorageField, String fileName,
        FileItem fileItem, String existingId) throws PersistenceException {
    String idField = getIdFieldFromFileStorageClass(fileClass);
    boolean error = false;
    TransactionContext tc = null;/*from  www.j a v a2  s  .c  o m*/
    Object id = null;
    PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(fileClass);

    try {
        id = getFileId(existingId, idField, pds);
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Object o;
        Class<?> clazz = Class.forName(fileClass);
        o = em.find(clazz, id);
        for (PropertyDescriptor pd : pds) {
            if (fileNameField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileName);
            } else if (fileStorageField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileItem.get());
            }
        }
        em.merge(o);

        tx.commit();
        //idsByClassName.get(fileClass).iterator().next().getReadMethod().invoke(o, new Object[0]);
    } catch (Exception e) {
        error = true;
        logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
        try {
            if (tc != null)
                tc.rollback();
        } catch (Exception ee) {
        }
    } finally {
        if (tc != null) {
            if (!error)
                close(tc);
            else
                tc.close();
        }
    }
    if (error) {
        try {
            tc = createTransactionalContext();
            EntityManager em = tc.getEm();
            ITransaction tx = tc.getTx();
            tx.begin();
            Class<?> clazz = Class.forName(fileClass);
            em.createQuery("delete from " + fileClass + " o where o." + idField + " = :id")
                    .setParameter("id", id).executeUpdate();
            Object newDoc = clazz.newInstance();
            for (PropertyDescriptor pd : pds) {
                if (fileNameField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileName);
                } else if (fileStorageField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileItem.get());
                }
            }
            em.persist(newDoc);
            tx.commit();
            for (PropertyDescriptor pd : pds) {
                if (idField.equals(pd.getName())) {
                    existingId = pd.getReadMethod().invoke(newDoc, new String[0]).toString();
                    break;
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
            try {
                if (tc != null)
                    tc.rollback();
            } catch (Exception ee) {
            }
            throw new PersistenceException(e.getMessage(), e);
        } finally {
            if (tc != null)
                close(tc);
        }
    }

    return existingId;
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getContracts(java.lang.String, java.lang.String, java.lang.String, int, int)
 *//* w  ww. j av a2s  .  c om*/
@Override
public List<ContractSummaryBean> getContracts(String organizationId, String apiId, String version, int page,
        int pageSize) throws StorageException {
    int start = (page - 1) * pageSize;
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        String jpql = "SELECT c from ContractBean c " + "  JOIN c.api apiv " + "  JOIN apiv.api api "
                + "  JOIN c.client clientv " + "  JOIN clientv.client client " + "  JOIN api.organization sorg"
                + "  JOIN client.organization aorg" + " WHERE api.id = :apiId " + "   AND sorg.id = :orgId "
                + "   AND apiv.version = :version " + " ORDER BY sorg.id, api.id ASC";
        Query query = entityManager.createQuery(jpql);
        query.setParameter("orgId", organizationId);
        query.setParameter("apiId", apiId);
        query.setParameter("version", version);
        query.setFirstResult(start);
        query.setMaxResults(pageSize);
        List<ContractBean> contracts = query.getResultList();
        List<ContractSummaryBean> rval = new ArrayList<>(contracts.size());
        for (ContractBean contractBean : contracts) {
            ClientBean client = contractBean.getClient().getClient();
            ApiBean api = contractBean.getApi().getApi();
            PlanBean plan = contractBean.getPlan().getPlan();

            OrganizationBean clientOrg = entityManager.find(OrganizationBean.class,
                    client.getOrganization().getId());
            OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());

            ContractSummaryBean csb = new ContractSummaryBean();
            csb.setClientId(client.getId());
            csb.setClientOrganizationId(client.getOrganization().getId());
            csb.setClientOrganizationName(clientOrg.getName());
            csb.setClientName(client.getName());
            csb.setClientVersion(contractBean.getClient().getVersion());
            csb.setContractId(contractBean.getId());
            csb.setCreatedOn(contractBean.getCreatedOn());
            csb.setPlanId(plan.getId());
            csb.setPlanName(plan.getName());
            csb.setPlanVersion(contractBean.getPlan().getVersion());
            csb.setApiDescription(api.getDescription());
            csb.setApiId(api.getId());
            csb.setApiName(api.getName());
            csb.setApiOrganizationId(apiOrg.getId());
            csb.setApiOrganizationName(apiOrg.getName());
            csb.setApiVersion(contractBean.getApi().getVersion());

            rval.add(csb);
        }
        return rval;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

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

@Override
public Collection<INakedObject> getCollection(String nakedObjectName, com.hiperf.common.ui.shared.util.Id id,
        String attributeName) throws PersistenceException {
    INakedObject o = null;//  ww w.  ja va2 s.  c o  m
    EntityManager em = null;
    try {
        em = getEntityManager();
        Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyContext = new HashMap<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>>();
        if (id.getFieldNames().size() == 1) {
            o = (INakedObject) em.find(Class.forName(nakedObjectName), id.getFieldValues().get(0));
        } else {
            Class c = Class.forName(nakedObjectName);
            o = (INakedObject) em.find(c, getCompositeId(c, id.getFieldNames(), id.getFieldValues()));
        }
        if (o != null) {
            return deproxyCollection(o, attributeName, em, deproxyContext);
        }
        return null;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in getCollection " + e.getMessage(), e);
        throw new PersistenceException("Exception in getCollection " + e.getMessage(), e);
    } finally {
        closeEntityManager(em);
    }
}

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

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

    ActionListener applyActionListener = new ActionListener() {
        @Override/*from  w  w  w  . jav  a  2  s .  c om*/
        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:org.apache.juddi.validation.ValidatePublish.java

public void validatePublisherAssertion(EntityManager em, org.uddi.api_v3.PublisherAssertion pubAssertion)
        throws DispositionReportFaultMessage {
    // A supplied publisher assertion can't be null
    if (pubAssertion == null) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.NullInput"));
    }// w  ww . j a  v a2  s .  c om

    // The keyedRef must not be blank and every field must contain data.
    org.uddi.api_v3.KeyedReference keyedRef = pubAssertion.getKeyedReference();
    if (keyedRef == null || keyedRef.getTModelKey() == null || keyedRef.getTModelKey().length() == 0
            || keyedRef.getKeyName() == null || keyedRef.getKeyName().length() == 0
            || keyedRef.getKeyValue() == null || keyedRef.getKeyValue().length() == 0) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankKeyedRef"));
    }

    String fromKey = pubAssertion.getFromKey();
    if (fromKey == null || fromKey.length() == 0) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankFromKey"));
    }

    String toKey = pubAssertion.getToKey();
    if (toKey == null || toKey.length() == 0) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankToKey"));
    }

    if (fromKey.equalsIgnoreCase(toKey)) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.SameBusinessKey"));
    }

    // Per section 4.4: keys must be case-folded
    fromKey = fromKey.toLowerCase();
    pubAssertion.setFromKey(fromKey);
    toKey = toKey.toLowerCase();
    pubAssertion.setToKey(toKey);
    validateKeyLength(toKey);
    validateKeyLength(fromKey);
    Object fromObj = em.find(org.apache.juddi.model.BusinessEntity.class, fromKey);
    if (fromObj == null) {
        throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", fromKey));
    }

    Object toObj = em.find(org.apache.juddi.model.BusinessEntity.class, pubAssertion.getToKey());
    if (toObj == null) {
        throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", toKey));
    }

    if (!publisher.isOwner((UddiEntity) fromObj) && !publisher.isOwner((UddiEntity) toObj)) {
        throw new UserMismatchException(
                new ErrorMessage("errors.pubassertion.UserMismatch", fromKey + " & " + toKey));
    }

    try {
        validateKeyedReference(pubAssertion.getKeyedReference(), AppConfig.getConfiguration(), false);
    } catch (ConfigurationException ce) {
        log.error("Could not optain config. " + ce.getMessage(), ce);
    }
}

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

public List<INakedObject> fillResultList(String className, EntityManager em, Set<PropertyDescriptor> ids,
        List<String> idFieldNames, Query q, boolean hasOrder)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    q.setHint("org.hibernate.readOnly", Boolean.TRUE);
    List<Object[]> ll = q.getResultList();
    if (ll != null && !ll.isEmpty()) {
        boolean single = ids.size() == 1;
        Object pk = null;//from   w  w w  .j a  va  2  s. c  om
        Class<?> c = Class.forName(className);
        Class clazz = null;
        if (!single) {
            IdClass idClass = c.getAnnotation(IdClass.class);
            clazz = idClass.value();
            pk = clazz.newInstance();
        }
        List<INakedObject> list = new ArrayList<>(ll.size());
        for (Object o : ll) {
            if (single) {
                list.add((INakedObject) em.find(c, hasOrder ? ((Object[]) o)[0] : o));
            } else {
                for (Field f : clazz.getDeclaredFields()) {
                    int idx = idFieldNames.indexOf(f.getName());
                    if (idx >= 0) {
                        boolean b = false;
                        if (!f.isAccessible()) {
                            f.setAccessible(true);
                            b = true;
                        }
                        f.set(pk, ((Object[]) o)[idx]);
                        if (b)
                            f.setAccessible(false);
                    }
                }
                list.add((INakedObject) em.find(c, pk));
            }
        }
        return list;
    }
    return null;
}