Example usage for javax.persistence EntityManager merge

List of usage examples for javax.persistence EntityManager merge

Introduction

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

Prototype

public <T> T merge(T entity);

Source Link

Document

Merge the state of the given entity into the current persistence context.

Usage

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*w  w w .  j a  va2s .c  o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#init(java.lang.String)
 */
@Override
public String init(final String dataSourceID) throws DeltaIndexingException {
    if (dataSourceID == null) {
        throw new DeltaIndexingException("parameter dataSourceID is null");
    }

    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao dao = findDataSourceDao(em, dataSourceID);
            if (dao != null && dao.getSessionId() != null) {
                throw new DeltaIndexingException(
                        "data source " + dataSourceID + " is already locked by another session");
            }

            final String sessionId = UUID.randomUUID().toString();

            final DataSourceDao lockedDao = new DataSourceDao(dataSourceID, sessionId);
            // lock the data source
            if (dao == null) {
                em.persist(lockedDao);
            } else {
                em.merge(lockedDao);
            }

            // reset visited and modified flags
            resetFlags(em, dataSourceID);

            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("created session " + sessionId + " for data source: " + dataSourceID);
            }
            return sessionId;
        } catch (final DeltaIndexingException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error initializing delta indexing for data source: " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:op.care.supervisor.PnlHandover.java

private void createContentPanel4Day(final LocalDate day, final CollapsiblePane cpDay) {

    final JPanel dayPanel = new JPanel(new VerticalLayout());

    OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));
    OPDE.getMainframe().setBlocked(true);

    SwingWorker worker = new SwingWorker() {

        @Override//from   ww w . j  a  va  2 s .co m
        protected Object doInBackground() throws Exception {

            //                final JPanel dayPanel = new JPanel(new VerticalLayout());
            dayPanel.setOpaque(false);

            ArrayList<Handovers> listHO = HandoversTools.getBy(day, (Homes) cmbHomes.getSelectedItem());
            ArrayList<NReport> listNR = NReportTools.getNReports4Handover(day,
                    (Homes) cmbHomes.getSelectedItem());

            Collections.sort(listNR, myComparator);

            int max = listHO.size() + listNR.size();
            int i = 0; // for zebra pattern and progress
            for (final Handovers handover : listHO) {
                OPDE.getDisplayManager()
                        .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), i, max));

                String title = "<html><table border=\"0\">" + "<tr valign=\"top\">"
                        + "<td width=\"100\" align=\"left\">"
                        + DateFormat.getTimeInstance(DateFormat.SHORT).format(handover.getPit()) + " "
                        + SYSTools.xx("misc.msg.Time.short") + "</td>"
                        + "<td width=\"100\" align=\"center\">--</td>" + "<td width=\"400\" align=\"left\">"
                        + handover.getText() + "</td>" +

                        "<td width=\"100\" align=\"left\">" + handover.getUser().getFullname() + "</td>"
                        + "</tr>" + "</table>" + "</html>";

                final DefaultCPTitle pnlSingle = new DefaultCPTitle(SYSTools.toHTMLForScreen(title),
                        new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent evt) {
                                EntityManager em = OPDE.createEM();
                                if (Handover2UserTools.containsUser(em, handover, OPDE.getLogin().getUser())) {
                                    em.close();
                                    return;
                                }
                                try {
                                    em.getTransaction().begin();
                                    Handovers myHO = em.merge(handover);
                                    Handover2User connObj = em.merge(
                                            new Handover2User(myHO, em.merge(OPDE.getLogin().getUser())));
                                    myHO.getUsersAcknowledged().add(connObj);
                                    em.getTransaction().commit();

                                    createCP4Day(day);
                                    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();
                                }
                            }
                        });

                final JButton btnInfo = new JButton(SYSConst.icon22info);
                btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
                btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnInfo.setAlignmentY(Component.TOP_ALIGNMENT);
                btnInfo.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnInfo.setContentAreaFilled(false);
                btnInfo.setBorder(null);
                btnInfo.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        OPDE.getDisplayManager().setProgressBarMessage(
                                new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));
                        OPDE.getMainframe().setBlocked(true);

                        SwingWorker worker = new SwingWorker() {

                            @Override
                            protected Object doInBackground() throws Exception {
                                SYSFilesTools.print(Handover2UserTools.getAsHTML(handover), false);
                                return null;
                            }

                            @Override
                            protected void done() {
                                try {
                                    get();
                                } catch (Exception ex1) {
                                    OPDE.fatal(ex1);
                                }
                                OPDE.getDisplayManager().setProgressBarMessage(null);
                                OPDE.getMainframe().setBlocked(false);
                            }

                        };
                        worker.execute();

                    }
                });
                pnlSingle.getRight().add(btnInfo);

                EntityManager em = OPDE.createEM();
                pnlSingle.getButton()
                        .setIcon(Handover2UserTools.containsUser(em, handover, OPDE.getLogin().getUser())
                                ? SYSConst.icon22ledGreenOn
                                : SYSConst.icon22ledRedOn);
                em.close();

                pnlSingle.getButton().setVerticalTextPosition(SwingConstants.TOP);

                JPanel zebra = new JPanel();
                zebra.setLayout(new BoxLayout(zebra, BoxLayout.LINE_AXIS));
                zebra.setOpaque(true);
                if (i % 2 == 0) {
                    zebra.setBackground(SYSConst.orange1[SYSConst.light2]);
                } else {
                    zebra.setBackground(Color.WHITE);
                }
                zebra.add(pnlSingle.getMain());
                i++;
                dayPanel.add(zebra);
            }
            for (final NReport nreport : listNR) {
                OPDE.getDisplayManager()
                        .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), i, max));

                String title = "<html><table border=\"0\">" + "<tr valign=\"top\">"
                        + "<td width=\"100\" align=\"left\">"
                        + DateFormat.getTimeInstance(DateFormat.SHORT).format(nreport.getPit()) + " "
                        + SYSTools.xx("misc.msg.Time.short") + "<br/>" + nreport.getMinutes() + " "
                        + SYSTools.xx("misc.msg.Minute(s)") + "</td>" + "<td width=\"100\" align=\"left\">"
                        + ResidentTools.getTextCompact(nreport.getResident()) + "</td>"
                        + "<td width=\"400\" align=\"left\">" + nreport.getText() + "</td>" +

                        "<td width=\"100\" align=\"left\">" + nreport.getUser().getFullname() + "</td>"
                        + "</tr>" + "</table>" + "</html>";

                final DefaultCPTitle pnlSingle = new DefaultCPTitle(SYSTools.toHTMLForScreen(title),
                        new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent evt) {
                                EntityManager em = OPDE.createEM();
                                if (NR2UserTools.containsUser(em, nreport, OPDE.getLogin().getUser())) {
                                    em.close();
                                    return;
                                }

                                try {
                                    em.getTransaction().begin();
                                    NReport myNR = em.merge(nreport);
                                    NR2User connObj = em
                                            .merge(new NR2User(myNR, em.merge(OPDE.getLogin().getUser())));
                                    myNR.getUsersAcknowledged().add(connObj);
                                    em.getTransaction().commit();
                                    createCP4Day(day);
                                    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();
                                }
                            }
                        });

                final JButton btnInfo = new JButton(SYSConst.icon22info);
                btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
                btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnInfo.setAlignmentY(Component.TOP_ALIGNMENT);
                btnInfo.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnInfo.setContentAreaFilled(false);
                btnInfo.setBorder(null);
                btnInfo.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {

                        SYSFilesTools.print(NR2UserTools.getAsHTML(nreport), false);

                        //                            OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));
                        //                            OPDE.getMainframe().setBlocked(true);
                        //
                        //                            SwingWorker worker = new SwingWorker() {
                        //
                        //                                @Override
                        //                                protected Object doInBackground() throws Exception {
                        //
                        //                                    return null;
                        //                                }
                        //
                        //                                @Override
                        //                                protected void done() {
                        //                                    OPDE.getDisplayManager().setProgressBarMessage(null);
                        //                                    OPDE.getMainframe().setBlocked(false);
                        //                                }
                        //
                        //                            };
                        //                            worker.execute();

                    }
                });
                pnlSingle.getRight().add(btnInfo);

                EntityManager em = OPDE.createEM();
                pnlSingle.getButton()
                        .setIcon(NR2UserTools.containsUser(em, nreport, OPDE.getLogin().getUser())
                                ? SYSConst.icon22ledGreenOn
                                : SYSConst.icon22ledRedOn);
                em.close();

                pnlSingle.getButton().setVerticalTextPosition(SwingConstants.TOP);

                JPanel zebra = new JPanel();
                zebra.setLayout(new BoxLayout(zebra, BoxLayout.LINE_AXIS));
                zebra.setOpaque(true);
                if (i % 2 == 0) {
                    zebra.setBackground(SYSConst.orange1[SYSConst.light2]);
                } else {
                    zebra.setBackground(Color.WHITE);
                }
                zebra.add(pnlSingle.getMain());
                i++;

                dayPanel.add(zebra);
            }
            final String key = DateFormat.getDateInstance().format(day.toDate());
            synchronized (cacheHO) {
                cacheHO.put(key, listHO);
            }
            synchronized (cacheNR) {
                cacheNR.put(key, listNR);
            }
            return null;

        }

        @Override
        protected void done() {
            try {
                get();
            } catch (Exception ex2) {
                OPDE.fatal(ex2);
            }
            cpDay.setContentPane(dayPanel);
            OPDE.getDisplayManager().setProgressBarMessage(null);
            OPDE.getMainframe().setBlocked(false);
        }
    };
    worker.execute();

}

From source file:op.care.dfn.PnlDFN.java

private CollapsiblePane createCP4(final DFN dfn) {
    final CollapsiblePane dfnPane = new CollapsiblePane();

    ActionListener applyActionListener = new ActionListener() {
        @Override//from www  .j a  v  a  2  s  .  com
        public void actionPerformed(ActionEvent actionEvent) {
            if (dfn.getState() == DFNTools.STATE_DONE) {
                return;
            }
            if (!dfn.isOnDemand() && dfn.getNursingProcess().isClosed()) {
                return;
            }

            if (DFNTools.isChangeable(dfn)) {
                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();

                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                    DFN myDFN = em.merge(dfn);
                    em.lock(myDFN, LockModeType.OPTIMISTIC);
                    if (!myDFN.isOnDemand()) {
                        em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                    }

                    myDFN.setState(DFNTools.STATE_DONE);
                    myDFN.setUser(em.merge(OPDE.getLogin().getUser()));
                    myDFN.setIst(new Date());
                    myDFN.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                    myDFN.setMdate(new Date());

                    em.getTransaction().commit();

                    CollapsiblePane cp1 = createCP4(myDFN);

                    synchronized (mapDFN2Pane) {
                        mapDFN2Pane.put(myDFN, cp1);
                    }
                    synchronized (mapShift2DFN) {
                        int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                        mapShift2DFN.get(myDFN.getShift()).remove(position);
                        mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                    }

                    CollapsiblePane cp2 = createCP4(myDFN.getShift());
                    synchronized (mapShift2Pane) {
                        mapShift2Pane.put(myDFN.getShift(), cp2);
                    }

                    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.dfn.notchangeable")));
            }
        }
    };

    String title = "<html><font size=+1>" +
    //                (dfn.isFloating() ? (dfn.isActive() ? "(!) " : "(OK) ") : "") +
            SYSTools.left(dfn.getIntervention().getBezeichnung(), MAX_TEXT_LENGTH)
            + DFNTools.getScheduleText(dfn, " [", "]") + ", " + dfn.getMinutes() + " "
            + SYSTools.xx("misc.msg.Minute(s)")
            + (dfn.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(dfn.getUser().getUID()) + "</i>" : "")
            + "</font></html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title,
            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID) ? applyActionListener
                    : null);
    dfnPane.setCollapseOnTitleClick(false);
    //        cptitle.getTitleButton().setIcon(DFNTools.getIcon(dfn));
    JLabel icon1 = new JLabel(DFNTools.getIcon(dfn));
    icon1.setOpaque(false);
    JLabel icon2 = new JLabel(DFNTools.getFloatingIcon(dfn));
    icon2.setOpaque(false);
    cptitle.getAdditionalIconPanel().add(icon1);
    cptitle.getAdditionalIconPanel().add(icon2);

    if (dfn.isFloating()) {
        cptitle.getButton().setToolTipText(SYSTools.xx("nursingrecords.dfn.enforced.tooltip") + ": "
                + DateFormat.getDateInstance().format(dfn.getStDatum()));
    }

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)
            && (dfn.isOnDemand() || !dfn.getNursingProcess().isClosed())) {
        /***
         *      _     _            _                _
         *     | |__ | |_ _ __    / \   _ __  _ __ | |_   _
         *     | '_ \| __| '_ \  / _ \ | '_ \| '_ \| | | | |
         *     | |_) | |_| | | |/ ___ \| |_) | |_) | | |_| |
         *     |_.__/ \__|_| |_/_/   \_\ .__/| .__/|_|\__, |
         *                             |_|   |_|      |___/
         */
        JButton btnApply = new JButton(SYSConst.icon22apply);
        btnApply.setPressedIcon(SYSConst.icon22applyPressed);
        btnApply.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnApply.setContentAreaFilled(false);
        btnApply.setBorder(null);
        btnApply.addActionListener(applyActionListener);
        btnApply.setEnabled(!dfn.isOnDemand() && dfn.isOpen());
        cptitle.getRight().add(btnApply);
        //            JPanel spacer = new JPanel();
        //            spacer.setOpaque(false);
        //            cptitle.getRight().add(spacer);
        /***
         *      _     _          ____                     _
         *     | |__ | |_ _ __  / ___|__ _ _ __   ___ ___| |
         *     | '_ \| __| '_ \| |   / _` | '_ \ / __/ _ \ |
         *     | |_) | |_| | | | |__| (_| | | | | (_|  __/ |
         *     |_.__/ \__|_| |_|\____\__,_|_| |_|\___\___|_|
         *
         */
        final JButton btnCancel = new JButton(SYSConst.icon22cancel);
        btnCancel.setPressedIcon(SYSConst.icon22cancelPressed);
        btnCancel.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnCancel.setContentAreaFilled(false);
        btnCancel.setBorder(null);
        //            btnCancel.setToolTipText(SYSTools.xx("nursingrecords.dfn.btneval.tooltip"));
        btnCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (dfn.getState() == DFNTools.STATE_REFUSED) {
                    return;
                }

                if (DFNTools.isChangeable(dfn)) {
                    EntityManager em = OPDE.createEM();
                    try {
                        em.getTransaction().begin();

                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                        DFN myDFN = em.merge(dfn);
                        em.lock(myDFN, LockModeType.OPTIMISTIC);
                        if (!myDFN.isOnDemand()) {
                            em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                        }

                        myDFN.setState(DFNTools.STATE_REFUSED);
                        myDFN.setUser(em.merge(OPDE.getLogin().getUser()));
                        myDFN.setIst(new Date());
                        myDFN.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                        myDFN.setMdate(new Date());

                        em.getTransaction().commit();

                        CollapsiblePane cp1 = createCP4(myDFN);
                        synchronized (mapDFN2Pane) {
                            mapDFN2Pane.put(myDFN, cp1);
                        }
                        synchronized (mapShift2DFN) {
                            int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                            mapShift2DFN.get(myDFN.getShift()).remove(position);
                            mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                        }
                        CollapsiblePane cp2 = createCP4(myDFN.getShift());
                        synchronized (mapShift2Pane) {
                            mapShift2Pane.put(myDFN.getShift(), cp2);
                        }
                        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.dfn.notchangeable")));
                }
            }
        });
        btnCancel.setEnabled(!dfn.isOnDemand() && dfn.isOpen());
        cptitle.getRight().add(btnCancel);

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

                if (DFNTools.isChangeable(dfn)) {
                    EntityManager em = OPDE.createEM();
                    try {
                        em.getTransaction().begin();

                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                        DFN myDFN = em.merge(dfn);
                        em.lock(myDFN, LockModeType.OPTIMISTIC);
                        if (!myDFN.isOnDemand()) {
                            em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                        }

                        // on demand DFNs are deleted if they not wanted anymore
                        if (myDFN.isOnDemand()) {
                            em.remove(myDFN);
                            synchronized (mapDFN2Pane) {
                                mapDFN2Pane.remove(myDFN);
                            }
                            synchronized (mapShift2DFN) {
                                mapShift2DFN.get(myDFN.getShift()).remove(myDFN);
                            }
                        } else {
                            // the normal DFNs (those assigned to a NursingProcess) are reset to the OPEN state.
                            myDFN.setState(DFNTools.STATE_OPEN);
                            myDFN.setUser(null);
                            myDFN.setIst(null);
                            myDFN.setiZeit(null);
                            myDFN.setMdate(new Date());
                            CollapsiblePane cp1 = createCP4(myDFN);
                            synchronized (mapDFN2Pane) {
                                mapDFN2Pane.put(myDFN, cp1);
                            }
                            synchronized (mapShift2DFN) {
                                int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                                mapShift2DFN.get(myDFN.getShift()).remove(position);
                                mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                            }
                        }
                        em.getTransaction().commit();

                        CollapsiblePane cp2 = createCP4(myDFN.getShift());
                        synchronized (mapShift2Pane) {
                            mapShift2Pane.put(myDFN.getShift(), cp2);
                        }
                        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.dfn.notchangeable")));
                }
            }
        });
        btnEmpty.setEnabled(!dfn.isOpen());
        cptitle.getRight().add(btnEmpty);

        /***
         *      _     _         __  __ _             _
         *     | |__ | |_ _ __ |  \/  (_)_ __  _   _| |_ ___  ___
         *     | '_ \| __| '_ \| |\/| | | '_ \| | | | __/ _ \/ __|
         *     | |_) | |_| | | | |  | | | | | | |_| | ||  __/\__ \
         *     |_.__/ \__|_| |_|_|  |_|_|_| |_|\__,_|\__\___||___/
         *
         */
        final JButton btnMinutes = new JButton(SYSConst.icon22clock);
        btnMinutes.setPressedIcon(SYSConst.icon22clockPressed);
        btnMinutes.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMinutes.setContentAreaFilled(false);
        btnMinutes.setBorder(null);
        //            btnCancel.setToolTipText(SYSTools.xx("nursingrecords.dfn.btneval.tooltip"));
        btnMinutes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (!DFNTools.isChangeable(dfn)) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.dfn.notchangeable")));
                    return;
                }
                final JPopupMenu menu = SYSCalendar.getMinutesMenu(
                        new int[] { 1, 2, 3, 4, 5, 10, 15, 20, 30, 45, 60, 120, 240, 360 }, new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();

                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    DFN myDFN = em.merge(dfn);
                                    em.lock(myDFN, LockModeType.OPTIMISTIC);
                                    if (!myDFN.isOnDemand()) {
                                        em.lock(myDFN.getNursingProcess(), LockModeType.OPTIMISTIC);
                                    }

                                    myDFN.setMinutes(new BigDecimal((Integer) o));
                                    myDFN.setUser(em.merge(OPDE.getLogin().getUser()));
                                    myDFN.setMdate(new Date());
                                    em.getTransaction().commit();

                                    CollapsiblePane cp1 = createCP4(myDFN);
                                    synchronized (mapDFN2Pane) {
                                        mapDFN2Pane.put(myDFN, cp1);
                                    }
                                    synchronized (mapShift2DFN) {
                                        int position = mapShift2DFN.get(myDFN.getShift()).indexOf(myDFN);
                                        mapShift2DFN.get(myDFN.getShift()).remove(position);
                                        mapShift2DFN.get(myDFN.getShift()).add(position, myDFN);
                                    }
                                    CollapsiblePane cp2 = createCP4(myDFN.getShift());
                                    synchronized (mapShift2Pane) {
                                        mapShift2Pane.put(myDFN.getShift(), cp2);
                                    }

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

                menu.show(btnMinutes, 0, btnMinutes.getHeight());
            }
        });
        btnMinutes.setEnabled(dfn.getState() != DFNTools.STATE_OPEN);
        cptitle.getRight().add(btnMinutes);
    }

    /***
     *      _     _         ___        __
     *     | |__ | |_ _ __ |_ _|_ __  / _| ___
     *     | '_ \| __| '_ \ | || '_ \| |_ / _ \
     *     | |_) | |_| | | || || | | |  _| (_) |
     *     |_.__/ \__|_| |_|___|_| |_|_|  \___/
     *
     */
    final JButton btnInfo = new JButton(SYSConst.icon22info);
    final JidePopup popupInfo = new JidePopup();
    btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
    btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnInfo.setContentAreaFilled(false);
    btnInfo.setBorder(null);
    final JTextPane txt = new JTextPane();
    txt.setContentType("text/html");
    txt.setEditable(false);

    popupInfo.setMovable(false);
    popupInfo.getContentPane().setLayout(new BoxLayout(popupInfo.getContentPane(), BoxLayout.LINE_AXIS));
    popupInfo.getContentPane().add(new JScrollPane(txt));
    popupInfo.removeExcludedComponent(txt);
    popupInfo.setDefaultFocusComponent(txt);

    btnInfo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            popupInfo.setOwner(btnInfo);
            txt.setText(SYSTools.toHTML(SYSConst.html_div(dfn.getInterventionSchedule().getBemerkung())));
            GUITools.showPopup(popupInfo, SwingConstants.WEST);
        }
    });

    btnInfo.setEnabled(
            !dfn.isOnDemand() && !SYSTools.catchNull(dfn.getInterventionSchedule().getBemerkung()).isEmpty());
    cptitle.getRight().add(btnInfo);

    dfnPane.setTitleLabelComponent(cptitle.getMain());

    dfnPane.setBackground(dfn.getBG());
    dfnPane.setForeground(dfn.getFG());
    try {
        dfnPane.setCollapsed(true);
    } catch (PropertyVetoException e) {
        OPDE.error(e);
    }
    dfnPane.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            JTextPane contentPane = new JTextPane();
            contentPane.setContentType("text/html");
            contentPane.setEditable(false);
            contentPane.setText(SYSTools
                    .toHTML(NursingProcessTools.getAsHTML(dfn.getNursingProcess(), false, true, false, false)));
            dfnPane.setContentPane(contentPane);
        }
    });
    dfnPane.setCollapsible(dfn.getNursingProcess() != null);
    dfnPane.setHorizontalAlignment(SwingConstants.LEADING);
    dfnPane.setOpaque(false);
    return dfnPane;
}

From source file:op.allowance.PnlAllowance.java

private JPanel createContentPanel4(final Resident resident, LocalDate month) {
    final String key = getKey(resident, month);

    if (!contentmap.containsKey(key)) {

        JPanel pnlMonth = new JPanel(new VerticalLayout());

        pnlMonth.setBackground(getBG(resident, 11));
        pnlMonth.setOpaque(false);/*from   ww w  . j a v  a  2 s  . com*/

        //            final String prevKey = resident.getRID() + "-" + SYSCalendar.eom(month.minusMonths(1)).getYear() + "-" + SYSCalendar.eom(month.minusMonths(1)).getMonthOfYear();
        if (!carrySums.containsKey(key)) {
            carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month.minusMonths(1))));
        }

        BigDecimal rowsum = carrySums.get(key);

        if (!cashmap.containsKey(key)) {
            cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
        }

        JLabel lblEOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMaximumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.endofmonth") + "</td>"
                + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        pnlMonth.add(lblEOM);

        for (final Allowance allowance : cashmap.get(key)) {

            String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                    + DateFormat.getDateInstance().format(allowance.getPit()) + "</td>"
                    + "<td width=\"400\" align=\"left\">" + allowance.getText() + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                    + cf.format(allowance.getAmount())
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>"
                    +

                    "</font></html>";

            DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                }
            });
            cptitle.getButton().setIcon(
                    allowance.isReplaced() || allowance.isReplacement() ? SYSConst.icon22eraser : null);

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
                /***
                 *      _____    _ _ _
                 *     | ____|__| (_) |_
                 *     |  _| / _` | | __|
                 *     | |__| (_| | | |_
                 *     |_____\__,_|_|\__|
                 *
                 */
                final JButton btnEdit = new JButton(SYSConst.icon22edit3);
                btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
                btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnEdit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnEdit.setContentAreaFilled(false);
                btnEdit.setBorder(null);
                btnEdit.setToolTipText(SYSTools.xx("admin.residents.cash.btnedit.tooltip"));
                btnEdit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        final JidePopup popupTX = new JidePopup();
                        popupTX.setMovable(false);
                        PnlTX pnlTX = getPnlTX(resident, allowance);
                        popupTX.setContentPane(pnlTX);
                        popupTX.removeExcludedComponent(pnlTX);
                        popupTX.setDefaultFocusComponent(pnlTX);

                        popupTX.setOwner(btnEdit);
                        GUITools.showPopup(popupTX, SwingConstants.WEST);

                    }
                });
                cptitle.getRight().add(btnEdit);
                // you can edit your own entries or you are a manager. once they are replaced or a replacement record, its over.
                btnEdit.setEnabled((OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, internalClassID)
                        || allowance.getUser().equals(OPDE.getLogin().getUser())) && !allowance.isReplaced()
                        && !allowance.isReplacement());

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("admin.residents.cash.btnundotx.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>" + "<br/><i>"
                                        + allowance.getText() + "&nbsp;" + cf.format(allowance.getAmount())
                                        + "</i><br/>" + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();

                                                Allowance myOldAllowance = em.merge(allowance);
                                                Allowance myCancelAllowance = em
                                                        .merge(new Allowance(myOldAllowance));
                                                em.lock(em.merge(myOldAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myOldAllowance, LockModeType.OPTIMISTIC);
                                                myOldAllowance.setReplacedBy(myCancelAllowance,
                                                        em.merge(OPDE.getLogin().getUser()));

                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myCancelAllowance.getPit());

                                                final String keyMonth = myCancelAllowance.getResident().getRID()
                                                        + "-" + txDate.getYear() + "-"
                                                        + txDate.getMonthOfYear();
                                                contentmap.remove(keyMonth);
                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(allowance);
                                                cashmap.get(keyMonth).add(myOldAllowance);
                                                cashmap.get(keyMonth).add(myCancelAllowance);
                                                Collections.sort(cashmap.get(keyMonth));

                                                updateCarrySums(myCancelAllowance);

                                                createCP4(myCancelAllowance.getResident());

                                                try {
                                                    cpMap.get(keyMonth).setCollapsed(false);
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                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(btnUndoTX);
                btnUndoTX.setEnabled(!allowance.isReplaced() && !allowance.isReplacement());
            }

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
                /***
                 *      ____       _      _
                 *     |  _ \  ___| | ___| |_ ___
                 *     | | | |/ _ \ |/ _ \ __/ _ \
                 *     | |_| |  __/ |  __/ ||  __/
                 *     |____/ \___|_|\___|\__\___|
                 *
                 */
                final JButton btnDelete = new JButton(SYSConst.icon22delete);
                btnDelete.setPressedIcon(SYSConst.icon22deletePressed);
                btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnDelete.setContentAreaFilled(false);
                btnDelete.setBorder(null);
                btnDelete.setToolTipText(SYSTools.xx("admin.residents.cash.btndelete.tooltip"));
                btnDelete.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.delete1") + "<br/><i>" + allowance.getText()
                                        + "&nbsp;" + cf.format(allowance.getAmount()) + "</i><br/>"
                                        + SYSTools.xx("misc.questions.delete2"),
                                SYSConst.icon48delete, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                Allowance myAllowance = em.merge(allowance);
                                                em.lock(em.merge(myAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);

                                                Allowance theOtherOne = null;
                                                // Check for special cases
                                                if (myAllowance.isReplacement()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacementFor());
                                                    theOtherOne.setReplacedBy(null);
                                                    theOtherOne.setEditedBy(null);
                                                    myAllowance.setEditPit(null);
                                                }
                                                if (myAllowance.isReplaced()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacedBy());
                                                    theOtherOne.setReplacementFor(null);
                                                }

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

                                                DateTime txDate = new DateTime(myAllowance.getPit());
                                                final String keyMonth = myAllowance.getResident().getRID() + "-"
                                                        + txDate.getYear() + "-" + txDate.getMonthOfYear();

                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(myAllowance);
                                                if (theOtherOne != null) {
                                                    cashmap.get(keyMonth).remove(theOtherOne);
                                                    cashmap.get(keyMonth).add(theOtherOne);
                                                    Collections.sort(cashmap.get(keyMonth));
                                                }

                                                // only to update the carrysums. myAllowance will be discarded soon.
                                                myAllowance.setAmount(myAllowance.getAmount().negate());
                                                updateCarrySums(myAllowance);

                                                createCP4(myAllowance.getResident());

                                                try {
                                                    if (cpMap.containsKey(keyMonth)) {
                                                        cpMap.get(keyMonth).setCollapsed(false);
                                                    }
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                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(btnDelete);
            }
            pnlMonth.add(cptitle.getMain());
            linemap.put(allowance, cptitle.getMain());

            rowsum = rowsum.subtract(allowance.getAmount());
        }

        JLabel lblBOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMinimumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.startofmonth")
                + "</td>" + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        lblBOM.setBackground(getBG(resident, 11));
        pnlMonth.add(lblBOM);
        contentmap.put(key, pnlMonth);
    }

    return contentmap.get(key);
}

From source file:org.cesecore.audit.impl.queued.AuditLogProcessQueue.java

/**
 * Aborts one audit log process and adjusts sequence numbers.
 * //ww  w .  j a v  a 2s . c  o  m
 * @param process
 * @param em
 */
public void abort(final AuditLogProcess process, final EntityManager em) {
    synchronized (pushLock) {
        synchronized (pullLock) {
            //decrement last sequence number
            lastSequenceNumber--;
            final AuditLogData auditLogData = process.getAuditLogData();
            final Long abortSequenceNumber = auditLogData.getSequenceNumber();
            //remove log from processing
            if (processing.remove(process)) {
                //decrement in process counter when reset is in progress
                if (LogServiceState.INSTANCE.isDisabled()) {
                    inProcess.countDown();
                }
            }
            final List<AuditLogProcess> consumersToBeNotified = process.getWaiting();
            for (final AuditLogProcess proc : consumersToBeNotified) {
                //decrement sequence number in each dependent log
                final Long seqNumber = proc.getAuditLogData().getSequenceNumber();
                auditLogData.setSequenceNumber(seqNumber - 1);
                proc.setAuditLogData(auditLogData);

                proc.getDepsCount().countDown();
            }
            //decrement sequence number in already processed logs (not signed yet)
            for (final AuditLogData auditLog : logs) {
                final Long seqNumber = auditLog.getSequenceNumber();
                if (seqNumber > abortSequenceNumber) {
                    auditLog.setSequenceNumber(seqNumber - 1);
                    em.merge(auditLog);
                }
            }
        }
    }
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public PropField savePropField(PropField propField) throws ImmutableObjectException {

    //strict must be set
    if (propField.getValueType() == null) {
        throw new ApaException("Please specify a value type");
    }/*from  w ww  . j  a v  a  2  s  .co  m*/

    //strict must be set
    if (propField.getStrict() == null) {
        throw new ApaException("Please specify strict as true or false");
    }

    if (propField.getStrict() && propField.getValueType().equals(ValueType.BOOLEAN)) {
        throw new ApaException("Boolean fields cannot be marked as strict");
    }

    if (propField.getStrict() && propField.getValueType().equals(ValueType.TEXT)) {
        throw new ApaException("Text fields cannot be marked as strict");
    }

    //check for immutability
    if (propField.getId() != null) {
        PropField oldPropField = getPropField(propField.getId());
        checkExists(oldPropField);
        checkImmutability(propField, oldPropField);
    } else {
        checkForDuplicatePropField(propField.getName());
    }
    checkForDuplicatePropValue(propField);

    EntityManager em = this.emf.createEntityManager();
    try {
        em.getTransaction().begin();
        propField.setId(LongUserType.massageToLong(propField.getId()));
        // loop through propValue ids to massage to long
        Collection<PropValue> propValues = propField.getPropValues();
        if (propValues != null) {
            for (PropValue propValue : propValues) {
                propValue.setId(LongUserType.massageToLong(propValue.getId()));
                propValue.setPropField(propField);
            }
        }
        propField = (PropField) em.merge(propField);

        if (propField.getPropValues() == null) {
            propField.setPropValues(new ArrayList<PropValue>());
        }

        em.getTransaction().commit();
        return propField;
    } finally {
        cleanup(em);
    }
}

From source file:op.controlling.PnlControlling.java

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

    /***/*from   w  ww  .  j  a va  2s.c o  m*/
     *      ____                      ____            _             _   _     _     _
     *     |  _ \ _ __ _   _  __ _   / ___|___  _ __ | |_ _ __ ___ | | | |   (_)___| |_
     *     | | | | '__| | | |/ _` | | |   / _ \| '_ \| __| '__/ _ \| | | |   | / __| __|
     *     | |_| | |  | |_| | (_| | | |__| (_) | | | | |_| | | (_) | | | |___| \__ \ |_
     *     |____/|_|   \__,_|\__, |  \____\___/|_| |_|\__|_|  \___/|_| |_____|_|___/\__|
     *                       |___/
     */
    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.controlling.PnlControlling.java

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

    if (tabMain.getSelectedIndex() == TAB_QMSPLAN) {

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
            JideButton addButton = GUITools.createHyperlinkButton(SYSTools.xx("misc.commands.new"),
                    new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png")), new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            new DlgQMSPlan(new Qmsplan(""), new Closure() {
                                @Override
                                public void execute(Object qmsplan) {
                                    if (qmsplan != null) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();
                                            final Qmsplan myQMSPlan = (Qmsplan) em.merge(qmsplan);
                                            em.getTransaction().commit();
                                            //                                        pnlQMSPlan.getListQMSPlans().add(myQMSPlan);
                                            pnlQMSPlan.reload();
                                            prepareSearchArea();
                                        } catch (OptimisticLockException ole) {
                                            OPDE.warn(ole);
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                                OPDE.getMainframe().emptyFrame();
                                                OPDE.getMainframe().afterLogin();
                                            } else {
                                                reload();
                                            }
                                        } catch (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }// w  w w.  j  a  v a  2 s  .  c  om
                                }
                            });
                        }
                    });
            list.add(addButton);
        }
    }
    return list;
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Retrieves the current model and checks if its lifetime is already exceeded.
 * In this case the model's TaskState will be set to {@code failed} and a {@link FailedException} is thrown,
 * which will stop the the main loop in {@code execute()}.
 *
 * Otherwise, the model's TaskState is set to {@code newState} and {@link #transit(TaskState, AbstractTask)}
 * will be invoked,//from w  w w  .  ja  va  2 s.  co m
 * which calls a method corresponding to the TaskState {@code newState} and throws a {@code TransitException} after its
 * execution specifying the next TaskSate value for the model.
 *
 * The model is made persistent by the EntityManager and the changed model will be 
 * commited to the database.
 * If something goes wrong while commiting the new model, a stable rollback is assured.
 *
 * @param newState the new TaskState for the model
 */
@SuppressWarnings({ "CaughtExceptionImmediatelyRethrown", "ThrowableInstanceNeverThrown" })
private void transit(final TaskState newState) {

    if (getCancelled()) {
        log.debug("cancelled");
        throw new StopException(TaskState.IN_PROGRESS_UNKNOWN);
    }

    EntityManager em = getEntityManager();
    @NotNull
    AbstractTask model = getModel();

    // this throws a stop exception on timeout
    if (!(TaskState.FINISHED.equals(newState) || TaskState.FAILED.equals(newState)))
        checkTimeout(model, em);

    try {
        em.getTransaction().begin();
        if (newState != null) {
            if (!em.contains(model)) {
                log.debug("model not in EntityManager");
                try {
                    try {
                        em.persist(model);
                    } catch (EntityExistsException e) {
                        log.debug("persisting failed merging", e);
                        rewindTransaction(em.getTransaction());
                        em.merge(model);
                    }
                } catch (RuntimeException e2) {
                    log.debug("probably persisting and merging failed", e2);
                    rewindTransaction(em.getTransaction());
                    final @NotNull AbstractTask newModel = em.find(AbstractTask.class, model.getId());
                    model.mold(newModel);
                    newModel.refresh(em);
                    setModel(newModel);
                    model = getModel();
                    log.debug("completed renewing of model");
                }
            }
        }

        model.transit(newState);

        boolean committed = false;
        try {
            em.getTransaction().commit();
            //                em.flush( );
            committed = true;
        } catch (Exception e) {
            log.debug("commit of transit (" + newState.name() + ") model failed ", e);
            try {
                rewindTransaction(em.getTransaction());
                // if this point is reached s.th. is terribly foobared
                // restore backup and fail
                model = Copier.copy(false, backup);
                em.merge(model);
                // backup should be clean so commit mustn't fail.
                model.fail(e);
                em.getTransaction().commit();
            } catch (Exception e2) {
                log.debug("restoring previous version failed", e2);
                try {
                    // refresh em for final commit
                    EntityManagerAux.rollbackAndClose(em);
                } catch (RuntimeException e3) {
                    log.debug("rollback old em failed", e3);
                }

                EntityManager nem = emf.createEntityManager();
                TxFrame tx = new TxFrame(nem);
                try {
                    log.debug("loading fresh model");
                    model = nem.find(model.getClass(), backup.getId());
                    boolean unkown = (model == null);
                    model = Copier.copy(false, backup);
                    model.fail(e2);
                    if (unkown)
                        nem.persist(model);
                    //     else
                    //         nem.merge( model );
                    tx.commit();
                    setModel(model);
                } catch (RuntimeException e3) {
                    log.debug("exception during refresh: ", e3);
                    throw e3;
                } finally {
                    tx.finish();
                    setOwnEntityManager(nem);
                    em = nem;
                }
            }
        }

        // if model could be commited it has a clean state
        // refresh backup
        if (committed)
            setBackup(Copier.copy(false, model));

        final TaskState modelState = model.getState();
        refreshTaskResource();
        //noinspection HardcodedFileSeparator
        trace("on" + modelState + "()", null);
        transit(modelState, model);
    }
    // for debugging
    catch (RuntimeException e) {
        throw e;
    } finally {
        try {
            // for debuggin'
            boolean ta = em.getTransaction().isActive();
            if (ta) {
                log.debug("final rollback");
                em.getTransaction().rollback();
            }
        } catch (Exception e) {
            log.debug("final rollback failed", e);
        }
    }
}

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

/**
 * Set the {@link DataSet#setMostRecentVersion(boolean) most recent version flags} for all data sets with the
 * specified uuid. Please note that this method
 * <strong>does not open a separate transaction</strong>.
 * /*from w ww.  ja  v a2  s .com*/
 * @param uuid
 *            uuid of the data sets
 */
@SuppressWarnings("unchecked")
protected boolean setMostRecentVersionFlags(String uuid) {
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();
    try {
        Query q = em.createQuery("SELECT a FROM " + this.getJpaName()
                + " a WHERE a.uuid.uuid=:uuid ORDER BY a.version.majorVersion desc, a.version.minorVersion desc, a.version.subMinorVersion desc");
        q.setParameter("uuid", uuid);
        List<T> res = q.getResultList();
        if (!res.isEmpty()) {
            t.begin();
            // get first element and mark it as most recent version (correct order is taken care of in query!)
            T tmp = res.get(0);
            tmp.setMostRecentVersion(true);
            tmp = em.merge(tmp);

            // set "false" for all other elements if required
            final int size = res.size();
            if (size > 1) {
                for (int i = 1; i < size; i++) {
                    tmp = res.get(i);
                    if (tmp.isMostRecentVersion()) {
                        tmp.setMostRecentVersion(false);
                        tmp = em.merge(tmp);
                    }
                }
            }
            t.commit();
            return true;
        } else {
            DataSetDao.LOGGER.warn("Most recent version flag was called for non-existent UUID: " + uuid);
            return false;
        }
    } catch (Exception e) {
        DataSetDao.LOGGER.error("Could not set most recent version flag for UUID: " + uuid);
        if (t.isActive()) {
            t.rollback();
        }
        return false;
    }
}