Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

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

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:gov.osti.services.Metadata.java

/**
 * Obtain a reserved DOI value if possible.
 *
 * @return a DoiReservation if successful, or null if not
 *//* w  ww  . ja v  a2s  .  c o m*/
private static DoiReservation getReservedDoi() {
    EntityManager em = DoeServletContextListener.createEntityManager();
    // set a LOCK TIMEOUT to prevent collision
    em.setProperty("javax.persistence.lock.timeout", 5000);

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

        DoiReservation reservation = em.find(DoiReservation.class, DoiReservation.TYPE,
                LockModeType.PESSIMISTIC_WRITE);

        if (null == reservation)
            reservation = new DoiReservation();

        reservation.reserve();

        em.merge(reservation);

        em.getTransaction().commit();

        // send it back
        return reservation;
    } catch (PessimisticLockException | LockTimeoutException e) {
        log.warn("DOI Reservation, unable to obtain lock.", e);
        return null;
    } finally {
        em.close();
    }
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public <T extends Serializable> List<T> findByExample(Class<T> clazz, T anExample) throws Exception {
    List<T> res = new ArrayList<T>();

    EntityManager em = getEntityManagerFactory().createEntityManager();
    Session session = null;//from   ww w  .j  av  a2  s  .  c  o  m
    Criteria cri = null;

    try {

        session = (Session) em.getDelegate();

        res = session.createCriteria(clazz).add(Example.create(anExample).excludeZeroes().enableLike()).list();

        // res = em.createQuery("SELECT e FROM " + clazz.getCanonicalName()
        // + " e", clazz).getResultList();

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();
        em.close();
    }

    return res;
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void setJobQueue(int idJob, int idQueue) {
    EntityManager em = null;
    JobInstance ji = null;/*from   w  w w  . ja  va 2  s .co  m*/
    Queue q = null;

    try {
        em = getEm();
        q = em.find(Queue.class, idQueue);
    } catch (NoResultException e) {
        closeQuietly(em);
        throw new JqmClientException("Queue does not exist");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("Cannot retrieve queue", e);
    }

    try {
        em.getTransaction().begin();
        ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE);
        if (ji == null || !ji.getState().equals(State.SUBMITTED)) {
            throw new NoResultException();
        }
        ji.setQueue(q);
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmClientException("Job instance does not exist or has already started");
    } catch (Exception e) {
        throw new JqmClientException("could not change the queue of a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Generic persist method for data set objects.
 * // ww w.  j a v  a 2s . co  m
 * @param dataSet
 *            data set to persist
 * @param pType
 *            which type of persistence operation, new, update (i.e. overwrite existing data set), ...
 * @param out
 *            PrintWriter to log error messages which can be presented to the end user
 * @return true if persist is successful, false otherwise
 * @see #preCheckAndPersist(DataSet)
 */
public boolean checkAndPersist(T dataSet, PersistType pType, PrintWriter out) {
    // TODO: check if version shall be excluded for some types

    if (dataSet.getRootDataStock() == null) {
        out.println("Error: root data stock must not be null!");
        return false;
    }

    // perform pre-persist actions
    this.preCheckAndPersist(dataSet);

    EntityManager em = PersistenceUtil.getEntityManager();

    // locate existing method by UUID
    T existingDataSet = this.getByUuidAndVersion(dataSet.getUuidAsString(), dataSet.getVersion());

    // if existing found ...
    if (existingDataSet != null) {
        // ... and mode is set to only new ...
        if (PersistType.ONLYNEW.equals(pType)) {
            if (out != null) {
                out.println("Warning: " + this.getAccessedClass().getSimpleName() + " data set with uuid "
                        + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString()
                        + " already exists in database; will ignore this data set.");
            }
            // ... just ignore it
            return false;
        }
    }

    EntityTransaction t = em.getTransaction();
    // now the DB interaction
    try {
        t.begin();
        // delete existing for merge operation
        if (existingDataSet != null && PersistType.MERGE.equals(pType)) {
            if (out != null) {
                out.println("Notice: " + this.getAccessedClass().getSimpleName() + " method data set with uuid "
                        + existingDataSet.getUuidAsString() + " and version "
                        + existingDataSet.getVersion().getVersionString()
                        + " already exists in database; will replace it with this data set");
            }
            em.remove(existingDataSet);
        }
        // persist the new method
        em.persist(dataSet);

        // actual write to DB
        t.commit();

        // set the most recent version flags correctly
        if (!this.setMostRecentVersionFlags(dataSet.getUuidAsString())) {
            return false;
        }

        // and return with success :)
        return true;
    } catch (Exception e) {
        DataSetDao.LOGGER.error(
                "Cannot persist " + this.getAccessedClass().getSimpleName() + " data set with uuid {}",
                dataSet.getUuidAsString());
        DataSetDao.LOGGER.error("Exception is: ", e);
        if (out != null) {
            out.println("Error: " + this.getAccessedClass().getSimpleName() + " data set with uuid "
                    + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString()
                    + " could not be saved into database; unknown database error; Exception message: "
                    + e.getMessage());
        }
        t.rollback();
    }

    return false;
}

From source file:nl.b3p.viewer.admin.stripes.LayoutManagerActionBean.java

public Resolution saveApplicationLayout() {
    try {/* ww w  .j  a  v  a  2 s  . c om*/
        EntityManager em = Stripersist.getEntityManager();
        JSONObject jsonLayout = new JSONObject(layout);

        for (Iterator it = jsonLayout.keys(); it.hasNext();) {
            String key = (String) it.next();
            JSONObject layoutItem = jsonLayout.getJSONObject(key);
            if (layoutItem.has("components")) {
                JSONArray layoutItemComponents = layoutItem.getJSONArray("components");
                for (int i = 0; i < layoutItemComponents.length(); i++) {
                    JSONObject layoutComponent = layoutItemComponents.getJSONObject(i);
                    String compName = layoutComponent.getString("name");
                    String compClassName = layoutComponent.getString("componentClass");
                    Query q = em.createQuery(
                            "from ConfiguredComponent where application = :application and name = :name")
                            .setParameter("application", application).setParameter("name", compName);
                    // Check if the component is already saved. If not, return error
                    try {
                        q.getSingleResult();
                    } catch (NoResultException nre) {
                        ConfiguredComponent cc = new ConfiguredComponent();
                        cc.setClassName(compClassName);
                        cc.setName(compName);
                        cc.setApplication(application);
                        em.persist(cc);
                    }
                }
            }
        }

        application.setLayout(layout);
        application.setGlobalLayout(globalLayout);
        // Remove legacy properties to clean old apps
        application.removeOldProperties();
        em.persist(application);
        em.getTransaction().commit();
    } catch (JSONException ex) {
        Logger.getLogger(LayoutManagerActionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return new ForwardResolution("/WEB-INF/jsp/application/layoutmanager.jsp");
}

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/* www.ja v 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:com.enioka.jqm.api.HibernateClient.java

@Override
public int enqueue(JobRequest jd) {
    jqmlogger.trace("BEGINING ENQUEUE");
    EntityManager em = getEm();
    JobDef job = null;//from w ww.  j  a  va  2  s. co  m
    try {
        job = em.createNamedQuery("HibApi.findJobDef", JobDef.class)
                .setParameter("applicationName", jd.getApplicationName()).getSingleResult();
    } catch (NoResultException ex) {
        jqmlogger.error("Job definition named " + jd.getApplicationName() + " does not exist");
        closeQuietly(em);
        throw new JqmInvalidRequestException("no job definition named " + jd.getApplicationName());
    }

    jqmlogger.trace("Job to enqueue is from JobDef " + job.getId());
    Integer hl = null;
    List<RuntimeParameter> jps = overrideParameter(job, jd, em);

    // Begin transaction (that will hold a lock in case of Highlander)
    try {
        em.getTransaction().begin();

        if (job.isHighlander()) {
            hl = highlanderMode(job, em);
        }

        if (hl != null) {
            jqmlogger.trace(
                    "JI won't actually be enqueued because a job in highlander mode is currently submitted: "
                            + hl);
            closeQuietly(em);
            return hl;
        }
        jqmlogger.trace("Not in highlander mode or no currently enqueued instance");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("Could not do highlander analysis", e);
    }

    try {
        Queue q = job.getQueue();
        if (jd.getQueueName() != null) {
            q = em.createNamedQuery("HibApi.findQueue", Queue.class).setParameter("name", jd.getQueueName())
                    .getSingleResult();
        }

        JobInstance ji = new JobInstance();
        ji.setJd(job);

        ji.setState(State.SUBMITTED);
        ji.setQueue(q);
        ji.setNode(null);
        ji.setApplication(jd.getApplication());
        ji.setEmail(jd.getEmail());
        ji.setKeyword1(jd.getKeyword1());
        ji.setKeyword2(jd.getKeyword2());
        ji.setKeyword3(jd.getKeyword3());
        ji.setModule(jd.getModule());
        ji.setProgress(0);
        ji.setSessionID(jd.getSessionID());
        ji.setUserName(jd.getUser());

        ji.setCreationDate(Calendar.getInstance());
        if (jd.getParentID() != null) {
            ji.setParentId(jd.getParentID());
        }
        em.persist(ji);

        // There is sadly no portable and easy way to get DB time before insert... so we update afterwards.
        // Also updates the internal queue position marker (done in update and not setter to avoid full stupid JPA update).
        em.createNamedQuery("HibApi.updateJiWithDbTime").setParameter("i", ji.getId()).executeUpdate();

        for (RuntimeParameter jp : jps) {
            jqmlogger.trace("Parameter: " + jp.getKey() + " - " + jp.getValue());
            em.persist(ji.addParameter(jp.getKey(), jp.getValue()));
        }

        jqmlogger.trace("JI just created: " + ji.getId());
        em.getTransaction().commit();
        return ji.getId();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException("An entity specified in the execution request does not exist", e);
    } catch (Exception e) {
        throw new JqmClientException("Could not create new JobInstance", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

public int restartCrashedJob(int idJob) {
    EntityManager em = null;

    // History and Job ID have the same ID.
    History h = null;/*w w w .  j a  v  a2 s . co  m*/
    try {
        em = getEm();
        h = em.find(History.class, idJob);
    } catch (NoResultException e) {
        closeQuietly(em);
        throw new JqmClientException(
                "You cannot restart a job that is not done or which was purged from history");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("could not restart a job (internal error)", e);
    }

    if (!h.getState().equals(State.CRASHED)) {
        closeQuietly(em);
        throw new JqmClientException("You cannot restart a job that has not crashed");
    }

    if (!h.getJd().isCanBeRestarted()) {
        closeQuietly(em);
        throw new JqmClientException("This type of job was configured to prevent being restarded");
    }

    try {
        em.getTransaction().begin();
        em.remove(h);
        em.getTransaction().commit();
        return enqueue(getJobRequest(h, em));
    } catch (Exception e) {
        throw new JqmClientException("could not purge & restart a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java

public void updateExerciseInstanceUsedHints(ExerciseInstance ei, FlagQuestionHint hint) {
    EntityManager em = getHibernateEntityManager();
    EntityTransaction et = em.getTransaction();
    et.begin();/*from  www. j  a va  2  s.  c o  m*/
    try {
        em.createNativeQuery("INSERT INTO exerciseInstances_flagQuestionHints "
                + "(ExerciseInstance_idExerciseInstance,usedHints_idFlagQuestionHint) " + "VALUES (?,?)")
                .setParameter(1, ei.getIdExerciseInstance()).setParameter(2, hint.getId()).executeUpdate();
        et.commit();
        em.close();
    } catch (Exception e) {
        et.rollback();
        em.close();
        logger.error("Failed adding hint " + hint.getId() + " to exercise instance "
                + ei.getIdExerciseInstance() + " because of: \n" + e.getMessage());
    }

}