Example usage for javax.persistence EntityManager lock

List of usage examples for javax.persistence EntityManager lock

Introduction

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

Prototype

public void lock(Object entity, LockModeType lockMode);

Source Link

Document

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

Usage

From source file:op.controlling.PnlControlling.java

private JPanel createContentPanel4Drugs() {
    JPanel pnlContent = new JPanel(new VerticalLayout());

    /***//from  w ww. ja  v a2  s .c om
     *      ____                      ____            _             _   _     _     _
     *     |  _ \ _ __ _   _  __ _   / ___|___  _ __ | |_ _ __ ___ | | | |   (_)___| |_
     *     | | | | '__| | | |/ _` | | |   / _ \| '_ \| __| '__/ _ \| | | |   | / __| __|
     *     | |_| | |  | |_| | (_| | | |__| (_) | | | | |_| | | (_) | | | |___| \__ \ |_
     *     |____/|_|   \__,_|\__, |  \____\___/|_| |_|\__|_|  \___/|_| |_____|_|___/\__|
     *                       |___/
     */
    JPanel pnlDrugControl = new JPanel(new BorderLayout());
    final JButton btnDrugControl = GUITools.createHyperlinkButton("opde.controlling.drugs.controllist", null,
            null);
    final JComboBox cmbStation = new JComboBox(StationTools.getAll4Combobox(false));
    btnDrugControl.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            OPDE.getMainframe().setBlocked(true);
            SwingWorker worker = new SwingWorker() {
                @Override
                protected Object doInBackground() throws Exception {
                    return MedStockTools.getListForMedControl((Station) cmbStation.getSelectedItem(),
                            progressClosure);
                }

                @Override
                protected void done() {
                    try {
                        SYSFilesTools.print(get().toString(), true);
                    } catch (ExecutionException ee) {
                        OPDE.fatal(ee);
                    } catch (InterruptedException ie) {
                        // nop
                    }

                    OPDE.getDisplayManager().setProgressBarMessage(null);
                    OPDE.getMainframe().setBlocked(false);
                }
            };
            worker.execute();
        }
    });
    pnlDrugControl.add(btnDrugControl, BorderLayout.WEST);
    pnlDrugControl.add(cmbStation, BorderLayout.EAST);
    pnlContent.add(pnlDrugControl);

    /***
     *     __        __   _       _     _    ____            _             _   _   _                     _   _
     *     \ \      / /__(_) __ _| |__ | |_ / ___|___  _ __ | |_ _ __ ___ | | | \ | | __ _ _ __ ___ ___ | |_(_) ___ ___
     *      \ \ /\ / / _ \ |/ _` | '_ \| __| |   / _ \| '_ \| __| '__/ _ \| | |  \| |/ _` | '__/ __/ _ \| __| |/ __/ __|
     *       \ V  V /  __/ | (_| | | | | |_| |__| (_) | | | | |_| | | (_) | | | |\  | (_| | | | (_| (_) | |_| | (__\__ \
     *        \_/\_/ \___|_|\__, |_| |_|\__|\____\___/|_| |_|\__|_|  \___/|_| |_| \_|\__,_|_|  \___\___/ \__|_|\___|___/
     *                      |___/
     */
    JPanel pnlWeightControllNarcotics = new JPanel(new BorderLayout());
    final JButton btnWeightControl = GUITools
            .createHyperlinkButton("opde.controlling.prescription.narcotics.weightcontrol", null, null);

    //               final JComboBox cmbStation = new JComboBox(StationTools.getAll4Combobox(false));
    btnWeightControl.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            OPDE.getMainframe().setBlocked(true);
            SwingWorker worker = new SwingWorker() {
                @Override
                protected Object doInBackground() throws Exception {

                    return MedStockTools.getNarcoticsWeightList(new LocalDate().minusMonths(1),
                            new LocalDate());
                }

                @Override
                protected void done() {

                    try {
                        SYSFilesTools.print(get().toString(), true);
                    } catch (ExecutionException ee) {
                        OPDE.fatal(ee);
                    } catch (InterruptedException ie) {
                        // nop
                    }

                    OPDE.getDisplayManager().setProgressBarMessage(null);
                    OPDE.getMainframe().setBlocked(false);
                }
            };
            worker.execute();
        }
    });

    final JToggleButton btnNotify = new JToggleButton(SYSConst.icon22mailOFF);
    btnNotify.setSelectedIcon(SYSConst.icon22mailON);
    btnNotify.setSelected(NotificationTools.find(OPDE.getLogin().getUser(),
            NotificationTools.NKEY_DRUG_WEIGHT_CONTROL) != null);
    btnNotify.setToolTipText(SYSTools.xx("opde.notification.enable.for.this.topic"));

    btnNotify.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {

            EntityManager em = OPDE.createEM();
            try {
                em.getTransaction().begin();
                Users user = em.merge(OPDE.getLogin().getUser());
                em.lock(user, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Notification myNotification = em
                            .merge(new Notification(NotificationTools.NKEY_DRUG_WEIGHT_CONTROL, user));
                    user.getNotifications().add(myNotification);
                } else {
                    Notification myNotification = em.merge(NotificationTools.find(OPDE.getLogin().getUser(),
                            NotificationTools.NKEY_DRUG_WEIGHT_CONTROL));
                    user.getNotifications().remove(myNotification);
                    em.remove(myNotification);
                }

                em.getTransaction().commit();
                OPDE.getLogin().setUser(user);
            } 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 ex) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                OPDE.fatal(ex);
            } finally {
                em.close();
            }

        }
    });

    pnlWeightControllNarcotics.add(btnWeightControl, BorderLayout.WEST);
    pnlWeightControllNarcotics.add(btnNotify, BorderLayout.EAST);
    pnlContent.add(pnlWeightControllNarcotics);

    return pnlContent;
}

From source file:op.users.PnlUser.java

private java.util.List<Component> addCommands() {

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

    /***//from w w  w.j  ava 2  s  .  c o  m
     *         _       _     _ _   _
     *        / \   __| | __| | | | |___  ___ _ __
     *       / _ \ / _` |/ _` | | | / __|/ _ \ '__|
     *      / ___ \ (_| | (_| | |_| \__ \  __/ |
     *     /_/   \_\__,_|\__,_|\___/|___/\___|_|
     *
     */
    final JideButton btnAddUser = GUITools.createHyperlinkButton(SYSTools.xx("opde.users.btnAddUser"),
            SYSConst.icon22addUser, null);
    btnAddUser.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            if (tabMain.getSelectedIndex() != TAB_USER) {
                tabMain.setSelectedIndex(TAB_USER);
            }
            new DlgUser(new Users(), new Closure() {
                @Override
                public void execute(Object o) {
                    if (o != null) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            Users user = em.merge((Users) o);
                            // Put everyone into >>everyone<<
                            Groups everyone = em.find(Groups.class, "everyone");
                            em.lock(everyone, LockModeType.OPTIMISTIC);
                            user.getGroups().add(everyone);
                            everyone.getMembers().add(user);

                            em.getTransaction().commit();
                            lstUsers.add(user);
                            reloadDisplay();
                        } catch (Exception e) {
                            em.getTransaction().rollback();
                        } finally {
                            em.close();
                        }
                    }
                }
            });

        }
    });
    list.add(btnAddUser);

    /***
     *         _       _     _  ____
     *        / \   __| | __| |/ ___|_ __ ___  _   _ _ __
     *       / _ \ / _` |/ _` | |  _| '__/ _ \| | | | '_ \
     *      / ___ \ (_| | (_| | |_| | | | (_) | |_| | |_) |
     *     /_/   \_\__,_|\__,_|\____|_|  \___/ \__,_| .__/
     *                                              |_|
     */
    final JideButton btnAddGroup = GUITools.createHyperlinkButton(SYSTools.xx("opde.users.btnAddGroup"),
            SYSConst.icon22addGroup, null);
    btnAddGroup.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            if (tabMain.getSelectedIndex() != TAB_GROUPS) {
                tabMain.setSelectedIndex(TAB_GROUPS);
            }
            new DlgGroup(new Groups(), new Closure() {
                @Override
                public void execute(Object o) {
                    if (o != null) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            Groups myGroup = em.merge((Groups) o);
                            em.getTransaction().commit();
                            createCP4(myGroup);
                            lstGroups.add(myGroup);
                            Collections.sort(lstGroups);
                            buildPanel();
                        } catch (Exception e) {
                            //                                em.getTransaction().rollback();
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                }
            });

        }
    });
    list.add(btnAddGroup);

    /***
     *      _     _         ____       _       _
     *     | |__ | |_ _ __ |  _ \ _ __(_)_ __ | |_
     *     | '_ \| __| '_ \| |_) | '__| | '_ \| __|
     *     | |_) | |_| | | |  __/| |  | | | | | |_
     *     |_.__/ \__|_| |_|_|   |_|  |_|_| |_|\__|
     *
     */
    //        JideButton btnPrint = GUITools.createHyperlinkButton(SYSTools.xx("misc.commands.print"), SYSConst.icon22print2, new ActionListener() {
    //            @Override
    //            public void actionPerformed(ActionEvent actionEvent) {
    //
    //            }
    //        });
    //        list.add(btnPrint);

    return list;
}

From source file:op.users.PnlUser.java

private CollapsiblePane createCP4(final Users user) {
    final String key = user.getUID() + ".xusers";
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        try {/*from w  w  w  .j  av  a 2 s  . c o m*/
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }

    }
    final CollapsiblePane cp = cpMap.get(key);
    DefaultCPTitle cptitle = new DefaultCPTitle("<html><font size=+1>" + user.toString()
            + (UsersTools.isQualified(user) ? ", " + SYSTools.xx("opde.users.qualifiedNurse") : "")
            + "</font></html>", new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        cp.setCollapsed(!cp.isCollapsed());
                    } catch (PropertyVetoException pve) {
                        // BAH!
                    }
                }
            });

    /***
     *       ____ _                            ______        __
     *      / ___| |__   __ _ _ __   __ _  ___|  _ \ \      / /
     *     | |   | '_ \ / _` | '_ \ / _` |/ _ \ |_) \ \ /\ / /
     *     | |___| | | | (_| | | | | (_| |  __/  __/ \ V  V /
     *      \____|_| |_|\__,_|_| |_|\__, |\___|_|     \_/\_/
     *                              |___/
     */
    final JButton btnChangePW = new JButton(SYSConst.icon22password);
    btnChangePW.setPressedIcon(SYSConst.icon22passwordPressed);
    btnChangePW.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnChangePW.setContentAreaFilled(false);
    btnChangePW.setBorder(null);
    btnChangePW.setToolTipText(SYSTools.xx("opde.users.btnChangePW.tooltip"));
    btnChangePW.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {

            EntityManager em = OPDE.createEM();
            try {
                em.getTransaction().begin();
                Users myUser = em.merge(usermap.get(user.getUID()));
                String newpw = SYSTools.generatePassword(myUser.getVorname(), myUser.getName());
                em.lock(myUser, LockModeType.OPTIMISTIC);
                myUser.setMd5pw(SYSTools.hashword(newpw));
                em.getTransaction().commit();

                lstUsers.remove(user);
                lstUsers.add(myUser);
                usermap.put(key, myUser);
                Collections.sort(lstUsers);

                SYSTools.printpw(newpw, myUser);

                OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("opde.users.pwchanged")));
            } catch (OptimisticLockException ole) {
                OPDE.warn(ole);
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }

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

        }
    });
    btnChangePW.setEnabled(user.isActive());
    cptitle.getRight().add(btnChangePW);

    /***
     *      _     _            _        _   _           ___                  _   _
     *     | |__ | |_ _ __    / \   ___| |_(_)_   _____|_ _|_ __   __ _  ___| |_(_)_   _____
     *     | '_ \| __| '_ \  / _ \ / __| __| \ \ / / _ \| || '_ \ / _` |/ __| __| \ \ / / _ \
     *     | |_) | |_| | | |/ ___ \ (__| |_| |\ V /  __/| || | | | (_| | (__| |_| |\ V /  __/
     *     |_.__/ \__|_| |_/_/   \_\___|\__|_| \_/ \___|___|_| |_|\__,_|\___|\__|_| \_/ \___|
     *
     */
    final JButton btnActiveInactive = new JButton(
            user.isActive() ? SYSConst.icon22stop : SYSConst.icon22playerPlay);
    btnActiveInactive
            .setPressedIcon(user.isActive() ? SYSConst.icon22stopPressed : SYSConst.icon22playerPlayPressed);
    btnActiveInactive.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnActiveInactive.setContentAreaFilled(false);
    btnActiveInactive.setBorder(null);
    btnActiveInactive.setToolTipText(SYSTools
            .xx(internalClassID + (user.isActive() ? ".btnActiveInactive.stop" : ".btnActiveInactive.play")));
    btnActiveInactive.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {

            EntityManager em = OPDE.createEM();
            try {
                em.getTransaction().begin();
                Users myUser = em.merge(usermap.get(user.getUID()));
                em.lock(myUser, LockModeType.OPTIMISTIC);

                myUser.setStatus(myUser.isActive() ? UsersTools.STATUS_INACTIVE : UsersTools.STATUS_ACTIVE);
                em.getTransaction().commit();
                lstUsers.remove(user);
                lstUsers.add(myUser);
                usermap.put(myUser.getUID(), myUser);
                Collections.sort(lstUsers);
                CollapsiblePane cp = createCP4(myUser);
                boolean wasCollapsed = cpMap.get(key).isCollapsed();
                cpMap.put(key, cp);

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

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

    /***
     *               _ _ _
     *       ___  __| (_) |_
     *      / _ \/ _` | | __|
     *     |  __/ (_| | | |_
     *      \___|\__,_|_|\__|
     *
     */
    final JButton btnEdit = new JButton(SYSConst.icon22edit3);
    btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
    btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnEdit.setContentAreaFilled(false);
    btnEdit.setBorder(null);
    btnEdit.setToolTipText(SYSTools.xx("opde.users.btnEdit"));
    btnEdit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {

            new DlgUser(user, new Closure() {
                @Override
                public void execute(Object o) {
                    if (o != null) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            Users myUser = em.merge((Users) o);
                            em.lock(myUser, LockModeType.OPTIMISTIC);
                            em.getTransaction().commit();
                            lstUsers.remove(user);
                            lstUsers.add(myUser);
                            usermap.put(myUser.getUID(), myUser);
                            Collections.sort(lstUsers);
                            CollapsiblePane cp = createCP4(myUser);
                            boolean wasCollapsed = cpMap.get(key).isCollapsed();
                            cpMap.put(key, cp);

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

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

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

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

    cp.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            if (!contentMap.containsKey(key)) {
                contentMap.put(key, new PnlEditMemberships(user, lstGroups));
            }
            cp.setContentPane(contentMap.get(key));
            cp.setOpaque(false);
        }
    }

    );
    cp.setBackground(UsersTools.getBG1(user));
    cp.setCollapsible(user.isActive());

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

    return cp;
}

From source file:org.apache.camel.bam.processor.ActivityMonitorEngine.java

@SuppressWarnings("unchecked")
protected void fireExpiredEvent(final ActivityState activityState) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Trying to fire expiration of: " + activityState);
    }/*from w ww .  ja  v  a2 s . c o  m*/

    template.execute(new JpaCallback() {
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            // lets try lock the object first
            if (isUseLocking()) {
                LOG.info("Attempting to lock: " + activityState);
                entityManager.lock(activityState, LockModeType.WRITE);
                LOG.info("Grabbed lock: " + activityState);
            }

            try {
                rules.processExpired(activityState);
            } catch (Exception e) {
                LOG.error("Failed to process expiration of: " + activityState + ". Reason: " + e, e);
            }
            activityState.setTimeOverdue(null);
            //activityState.setEscalationLevel(escalateLevel + 1);
            return null;
        }
    });
}

From source file:org.apache.camel.component.jpa.JpaConsumer.java

/**
 * A strategy method to lock an object with an exclusive lock so that it can
 * be processed//from   ww  w  .java 2s  .  c  om
 * 
 * @param entity the entity to be locked
 * @param entityManager entity manager
 * @return true if the entity was locked
 */
protected boolean lockEntity(Object entity, EntityManager entityManager) {
    if (!getEndpoint().isConsumeDelete() || !getEndpoint().isConsumeLockEntity()) {
        return true;
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Acquiring exclusive lock on entity: " + entity);
        }
        entityManager.lock(entity, LockModeType.WRITE);
        return true;
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed to achieve lock on entity: " + entity + ". Reason: " + e, e);
        }
        return false;
    }
}