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.sigmah.server.servlet.exporter.models.ProjectModelHandler.java

@Override
public void importModel(InputStream inputStream, EntityManager em, User user) throws Exception {
    ObjectInputStream objectInputStream;
    em.getTransaction().begin();//from www  .  j  av  a2s.  co  m
    try {
        objectInputStream = new ObjectInputStream(inputStream);
        ProjectModel projectModel = (ProjectModel) objectInputStream.readObject();

        // Sets the new model as a draft.
        projectModel.setStatus(ProjectModelStatus.DRAFT);

        final HashMap<Object, Object> modelesReset = new HashMap<Object, Object>();
        final HashSet<Object> modelesImport = new HashSet<Object>();

        projectModel.resetImport();
        saveProjectFlexibleElement(projectModel, em, modelesReset, modelesImport, user);

        // Attaching the new model to the current user's organization
        final ProjectModelVisibility visibility = new ProjectModelVisibility();
        visibility.setModel(projectModel);
        visibility.setType(projectModelType);
        visibility.setOrganization(user.getOrganization());

        final ArrayList<ProjectModelVisibility> visibilities = new ArrayList<ProjectModelVisibility>();
        visibilities.add(visibility);
        projectModel.setVisibilities(visibilities);

        // Set the status to DRAFT
        projectModel.setStatus(ProjectModelStatus.DRAFT);

        // TODO ??
        for (PhaseModel pm : projectModel.getPhaseModels()) {
            for (LayoutGroup lg : pm.getLayout().getGroups()) {
                for (LayoutConstraint lc : lg.getConstraints()) {
                    FlexibleElement fe = lc.getElement();
                    System.out.println(fe.getClass() + " id " + fe.getId());
                    if (fe instanceof QuestionElement) {
                        for (QuestionChoiceElement qce : ((QuestionElement) fe).getChoices()) {
                            System.out.println(qce.getClass() + " id " + qce.getId());
                        }
                    }
                }
            }
        }

        em.merge(projectModel);
        em.getTransaction().commit();
        LOG.debug("The project model '" + projectModel.getName() + "' has been imported successfully.");

    } catch (IOException | ClassNotFoundException e) {
        LOG.debug("Error while importing a project model.", e);
        throw new Exception("Error while importing a project model.", e);
    }
}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectModelHandler.java

@Override
public void importModel(InputStream inputStream, EntityManager em, Authentication authentication)
        throws ExportException {
    ObjectInputStream objectInputStream;
    em.getTransaction().begin();//  ww  w  .  ja  va 2  s.c o  m
    try {
        objectInputStream = new ObjectInputStream(inputStream);
        ProjectModel projectModel = (ProjectModel) objectInputStream.readObject();

        // Sets the new model as a draft.
        projectModel.setStatus(ProjectModelStatus.DRAFT);

        final HashMap<Object, Object> modelesReset = new HashMap<Object, Object>();
        final HashSet<Object> modelesImport = new HashSet<Object>();

        projectModel.resetImport(modelesReset, modelesImport);
        saveProjectFlexibleElement(projectModel, em, modelesReset, modelesImport, authentication);

        // Attaching the new model to the current user's organization
        final ProjectModelVisibility visibility = new ProjectModelVisibility();
        visibility.setModel(projectModel);
        visibility.setType(projectModelType);
        visibility.setOrganization(authentication.getUser().getOrganization());

        final ArrayList<ProjectModelVisibility> visibilities = new ArrayList<ProjectModelVisibility>();
        visibilities.add(visibility);
        projectModel.setVisibilities(visibilities);

        // Set the staus to DRAFT
        projectModel.setStatus(ProjectModelStatus.DRAFT);

        for (PhaseModel pm : projectModel.getPhases()) {
            for (LayoutGroup lg : pm.getLayout().getGroups()) {
                for (LayoutConstraint lc : lg.getConstraints()) {
                    FlexibleElement fe = lc.getElement();
                    System.out.println(fe.getClass() + " id " + fe.getId());
                    if (fe instanceof QuestionElement) {
                        for (QuestionChoiceElement qce : ((QuestionElement) fe).getChoices()) {
                            System.out.println(qce.getClass() + " id " + qce.getId());
                        }
                    }
                }
            }
        }

        em.merge(projectModel);
        em.getTransaction().commit();
        LOG.debug("The project model '" + projectModel.getName() + "' has been imported successfully.");

    } catch (Throwable e) {
        LOG.debug("Error while importing a project model.", e);
        throw new ExportException("Error while importing a project model.", e);
    }
}

From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

/**
 * {@inheritDoc}/*from w  ww  . j  a v a2s . c  o  m*/
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#storeMediaPackage(MediaPackage,
 *      AccessControlList, Date)
 */
@Override
public void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now)
        throws SearchServiceDatabaseException, UnauthorizedException {
    String mediaPackageXML = MediaPackageParser.getAsXml(mediaPackage);
    String mediaPackageId = mediaPackage.getIdentifier().toString();
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity entity = getSearchEntity(mediaPackageId, em);
        if (entity == null) {
            // Create new search entity
            SearchEntity searchEntity = new SearchEntity();
            searchEntity.setOrganization(securityService.getOrganization().getId());
            searchEntity.setMediaPackageId(mediaPackageId);
            searchEntity.setMediaPackageXML(mediaPackageXML);
            searchEntity.setAccessControl(AccessControlParser.toXml(acl));
            searchEntity.setModificationDate(now);
            searchEntity.setSeriesId(mediaPackage.getSeries());
            em.persist(searchEntity);
        } else {
            // Ensure this user is allowed to update this media package
            String accessControlXml = entity.getAccessControl();
            if (accessControlXml != null) {
                AccessControlList accessList = AccessControlParser.parseAcl(accessControlXml);
                User currentUser = securityService.getUser();
                Organization currentOrg = securityService.getOrganization();
                if (!AccessControlUtil.isAuthorized(accessList, currentUser, currentOrg, WRITE.toString())) {
                    throw new UnauthorizedException(
                            currentUser + " is not authorized to update media package " + mediaPackageId);
                }
            }
            entity.setOrganization(securityService.getOrganization().getId());
            entity.setMediaPackageId(mediaPackageId);
            entity.setMediaPackageXML(mediaPackageXML);
            entity.setAccessControl(AccessControlParser.toXml(acl));
            entity.setModificationDate(now);
            entity.setSeriesId(mediaPackage.getSeries());
            em.merge(entity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update media package: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

private JPanel getMenu(final NReport nreport) {

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

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

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

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

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

                                em.getTransaction().commit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

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

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

                GUITools.showPopup(popup, SwingConstants.WEST);

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

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

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

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

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

                                    em.getTransaction().commit();

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

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

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

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

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

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

        pnlMenu.add(new JSeparator());

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

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

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

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

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

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

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

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

                        EntityManager em = OPDE.createEM();

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

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

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

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

                            em.getTransaction().commit();

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

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

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

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

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

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

    }
    return pnlMenu;
}

From source file:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java

/**
 * //w w w  .  java 2s.  co  m
 * @param accountTransaction
 * @param user
 * @throws java.lang.Exception
 */
public synchronized void commitTransaction(Transaction accountTransaction, User user) throws Exception {
    if (!enableAccounting) {
        return;
    }

    if (accountTransaction != null) {
        //Create an EntityManager
        log.debug("Getting entity manager ......");
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
        //Get the account and set the current balance. Update the class variable at the same time.
        Account account = (Account) em.find(Account.class, organizationId);
        balance = account.getCreditBalance();
        //Set the account & user for the accountTransaction.
        accountTransaction.setAccount(account);
        accountTransaction.setUser(user);

        try {
            //Run validation (checks what type of transaction is allowed..)
            accountTransaction.validate();

            //Now check if the transaction either has to deposit or withdraw...
            BigDecimal newBalance = null;
            if (accountTransaction.getType() == Transaction.DEPOSIT) {
                newBalance = balance.add(accountTransaction.getCreditAlteration());
            } else if (accountTransaction.getType() == Transaction.WITHDRAW) {
                newBalance = balance.subtract(accountTransaction.getCreditAlteration());
                if (newBalance.doubleValue() < 0) {
                    throw new TransactionDeniedException("Insufficient credits for transaction. "
                            + "Required credits: "
                            + accountTransaction.getCreditAlteration().setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            + ", " + "Current balance: "
                            + balance.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }
            } else {
                log.error("Unsupported transaction type");
                throw new Exception("Unsupported transaction type");
            }

            account.setCreditBalance(newBalance);
            accountTransaction.setMutationDate(new Date());
            accountTransaction.setStatus(Transaction.ACCEPTED);

            Iterator iterPriceComp = accountTransaction.getLayerPriceCompositions().iterator();
            while (iterPriceComp.hasNext()) {
                LayerPriceComposition lpc = (LayerPriceComposition) iterPriceComp.next();
                em.persist(lpc);
            }

            em.merge(accountTransaction);
            em.flush();
            balance = newBalance;
        } catch (TransactionDeniedException tde) {
            accountTransaction.setErrorMessage(tde.getMessage());
            accountTransaction.setStatus(Transaction.REFUSED);
            em.merge(accountTransaction);
            em.flush();
            throw tde;
        }
    }
}

From source file:org.sigmah.server.schedule.export.AutoExportJob.java

public void execute(JobExecutionContext executionContext) throws JobExecutionException {
    final JobDataMap dataMap = executionContext.getJobDetail().getJobDataMap();
    final EntityManager em = (EntityManager) dataMap.get("em");
    final Log log = (Log) dataMap.get("log");
    final Injector injector = (Injector) dataMap.get("injector");
    EntityTransaction tx = null;/*  w ww  .  jav  a  2  s  . co m*/

    try {

        // Open transaction
        /*
         *  NOTE: it is impossible to use @Transactional for this method
         *  The reason is link{TransactionalInterceptor} gets EntityManager 
         *  from the injector which is out of scope 
         */
        tx = em.getTransaction();
        tx.begin();

        final GlobalExportDAO exportDAO = new GlobalExportHibernateDAO(em);
        final GlobalExportDataProvider dataProvider = injector.getInstance(GlobalExportDataProvider.class);

        final List<GlobalExportSettings> settings = exportDAO.getGlobalExportSettings();
        for (final GlobalExportSettings setting : settings) {

            /*
             * Check for auto export schedule 
             */

            //skip if no export schedule is specified
            if (setting.getAutoExportFrequency() == null || setting.getAutoExportFrequency() < 1)
                continue;

            final Calendar systemCalendar = Calendar.getInstance();

            boolean doExport = false;

            if ((setting.getAutoExportFrequency() >= 31) && (setting.getAutoExportFrequency() <= 58)) {
                //Case of Monthly Auto Export
                if ((setting.getAutoExportFrequency() - 30) == systemCalendar.get(Calendar.DAY_OF_MONTH)) {
                    doExport = true;
                }
            } else if ((setting.getAutoExportFrequency() >= 61) && (setting.getAutoExportFrequency() <= 67)) {
                //Case of Weekly Auto Export
                if ((setting.getAutoExportFrequency() - 60) == systemCalendar.get(Calendar.DAY_OF_WEEK)) {
                    doExport = true;
                }

            } else {
                //Regular Auto-Export every N-days

                final Calendar scheduledCalendar = Calendar.getInstance();
                Date lastExportDate = setting.getLastExportDate();
                if (lastExportDate == null) {
                    lastExportDate = systemCalendar.getTime();
                    setting.setLastExportDate(lastExportDate);
                    em.merge(setting);
                } else {
                    scheduledCalendar.setTime(lastExportDate);
                    // add scheduled days to the last exported date
                    scheduledCalendar.add(Calendar.DAY_OF_MONTH, setting.getAutoExportFrequency());
                }

                final Date systemDate = getZeroTimeDate(systemCalendar.getTime());
                final Date scheduledDate = getZeroTimeDate(scheduledCalendar.getTime());

                if (systemDate.compareTo(scheduledDate) >= 0) {
                    doExport = true;
                }
            }

            if (doExport) {
                /*
                 * Start auto export  
                 */

                // persist global export logger
                final GlobalExport globalExport = new GlobalExport();
                globalExport.setOrganization(setting.getOrganization());
                globalExport.setDate(systemCalendar.getTime());
                em.persist(globalExport);

                // generate export content
                final Map<String, List<String[]>> exportData = dataProvider
                        .generateGlobalExportData(setting.getOrganization().getId(), em, setting.getLocale());

                // persist export content
                dataProvider.persistGlobalExportDataAsCsv(globalExport, em, exportData);
            }

        }
        tx.commit();

        log.info("Scheduled EXPORT of global exports fired");

    } catch (Exception ex) {
        if (tx != null && tx.isActive())
            tx.rollback();
        log.error("Scheduled global export job failed : " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java

/**
 * Checks the login session or credentials
 *
 * @param request The incoming request/*www  . j  a  va2s. co m*/
 * @param em The entityManager
 * @param pcode
 * @return The user Principal
 * @throws AccessDeniedException if the user can not be authenticated
 */
protected User checkLogin(HttpServletRequest request, EntityManager em, String pcode)
        throws AccessDeniedException {
    User user = (User) request.getUserPrincipal();

    if (user != null) {
        log.info("Cookie accepted for login, username: " + user.getName());

        return user;
    }

    // Try preemptive basic login
    // attempt to dig out authentication info only if the user has not yet been authenticated
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null) {
        String decoded = decodeBasicAuthorizationString(authorizationHeader);
        String username = parseUsername(decoded);
        String password = parsePassword(decoded);

        String encpw = null;
        try {
            encpw = KBCrypter.encryptText(password);
        } catch (Exception ex) {
            log.error("error encrypting password: ", ex);
        }
        try {
            user = (User) em
                    .createQuery("from User " + "where lower(username) = lower(:username) "
                            + "and password = :password ")
                    .setParameter("username", username).setParameter("password", encpw).getSingleResult();
            em.flush();
        } catch (NonUniqueResultException nue) {
            log.error(
                    "More than one person found for these credentials (to be fixed in database), trying next method.");
            user = null;
        } catch (NoResultException nre) {
            user = null;
            log.debug("No results using encrypted password, trying next method");
        }

        // extra check voor oude non-encrypted passwords
        if (user == null) {
            try {
                user = (User) em
                        .createQuery("from User " + "where lower(username) = lower(:username) "
                                + "and password = :password ")
                        .setParameter("username", username).setParameter("password", encpw).getSingleResult();

                // Volgende keer dus wel encrypted
                user.setPassword(encpw);
                em.merge(user);
                em.flush();

                if (!user.checkRole("beheerder")) {
                    throw new NoResultException("Not a admin");
                }
                log.debug("Cleartext password now encrypted!");
            } catch (NonUniqueResultException nue) {
                log.error(
                        "More than one person found for these (cleartext) credentials (to be fixed in database), trying next method.");
                user = null;
            } catch (NoResultException nre) {
                log.debug("No results using cleartext password, trying next method.");
            }
        }
    }
    if (user != null && user.checkRole("beheerder")) {
        log.info("Basic authentication accepted for login, username: " + user.getName());
        return user;
    } else {
        throw new AccessDeniedException(
                "Authorisation required for this service! No credentials found in Personal url, Authentication header or Cookie, Giving up! ");
    }
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    Map<String, String> persistenceMap = Utils.getInstance().getPersistenceMap();
    EntityManager entityManager = Persistence.createEntityManagerFactory("mg_PU", persistenceMap)
            .createEntityManager();/*from   w w  w.j  a v  a  2  s . co  m*/
    entityManager.getTransaction().begin();
    int suma = 0;
    List<TblTransferencias> listT = (List<TblTransferencias>) entityManager
            .createQuery("select t from TblTransferencias t").getResultList();
    for (TblTransferencias t : listT) {
        Integer sumAtAporte = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
        Integer sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
        if (t.getMontoAporte() < sumAtAporte) {
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (sumAtAporte - t.getTblAsientosTemporalesList().get(i).getMonto()
                            - t.getMontoAporte() == 0) {
                        System.out.println(t.getTblAsientosTemporalesList().get(i).getId());
                        suma += t.getTblAsientosTemporalesList().get(i).getMonto();
                        t.getTblAsientosTemporalesList().get(i).setMonto(0);
                        sumAtAporte = t.getTblAsientosTemporalesList().stream()
                                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
                        System.out.println(suma);
                        entityManager.merge(t);
                    }
                }
            }
        }
        if (t.getMontoDonacion() < sumAtDonacion) {
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (!t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (sumAtDonacion - t.getTblAsientosTemporalesList().get(i).getMonto()
                            - t.getMontoDonacion() == 0) {
                        System.out.println(t.getTblAsientosTemporalesList().get(i).getId());
                        suma += t.getTblAsientosTemporalesList().get(i).getMonto();
                        t.getTblAsientosTemporalesList().get(i).setMonto(0);
                        sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
                        System.out.println(suma);
                        entityManager.merge(t);
                    }
                }
            }
        }

    }
    for (TblTransferencias t : listT) {
        Integer sumAtAporte = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
        Integer sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
        if (t.getMontoAporte() < sumAtAporte) {
            int asientoValido = -1;
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (t.getTblAsientosTemporalesList().get(i).getMonto().equals(t.getMontoAporte())) {
                        asientoValido = t.getTblAsientosTemporalesList().get(i).getId();
                        for (int ii = 0; ii < t.getTblAsientosTemporalesList().size(); ii++) {
                            if (t.getTblAsientosTemporalesList().get(ii).getEsAporte()
                                    && t.getTblAsientosTemporalesList().get(ii).getId() != asientoValido) {
                                suma += t.getTblAsientosTemporalesList().get(ii).getMonto();
                                t.getTblAsientosTemporalesList().get(ii).setMonto(0);
                            }
                        }
                        entityManager.merge(t);
                    }
                }
            }
        }
        if (t.getMontoDonacion() < sumAtDonacion) {
            int asientoValido = -1;
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (!t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (t.getTblAsientosTemporalesList().get(i).getMonto().equals(t.getMontoDonacion())) {
                        asientoValido = t.getTblAsientosTemporalesList().get(i).getId();
                        for (int ii = 0; ii < t.getTblAsientosTemporalesList().size(); ii++) {
                            if (!t.getTblAsientosTemporalesList().get(ii).getEsAporte()
                                    && t.getTblAsientosTemporalesList().get(ii).getId() != asientoValido) {
                                suma += t.getTblAsientosTemporalesList().get(ii).getMonto();
                                t.getTblAsientosTemporalesList().get(ii).setMonto(0);
                            }
                        }
                        entityManager.merge(t);
                    }
                }
            }
        }
    }
    entityManager.getTransaction().commit();
    entityManager.getTransaction().begin();
    JOptionPane.showMessageDialog(null, suma);
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Go through all the children recursively to set them in {@link Status#CANCELED} status
 * //  ww w  . j av  a  2 s  . com
 * @param job
 *          the parent job
 * @param em
 *          the entity manager
 */
private void cancelAllChildren(JobJpaImpl job, EntityManager em) {
    for (JobJpaImpl child : job.getChildJobs()) {
        em.refresh(child);
        if (Status.CANCELED.equals(job.getStatus()))
            continue;
        cancelAllChildren(child, em);
        child.setStatus(Status.CANCELED);
        em.merge(child);
    }
}

From source file:it.drwolf.ridire.session.JobManager.java

private void selectResourceToBeValidated(int amount, int startIdx, int endIdx, EntityManager entityManager2,
        Job j) throws NoSuchAlgorithmException, IOException {
    if (amount < 1) {
        return;/*from ww  w.ja  v  a 2 s . c  o  m*/
    }
    List<Integer> ids = new ArrayList<Integer>();
    Map<String, Integer> hashes = new HashMap<String, Integer>();
    int cursize = hashes.size();
    while (hashes.size() < amount) {
        for (CrawledResource cr : (List<CrawledResource>) entityManager2.createQuery(
                "from CrawledResource cr where cr.job=:j and cr.wordsNumber<:eidx and cr.wordsNumber>=:sidx and cr.deleted=false order by rand()")
                .setParameter("j", j).setParameter("sidx", startIdx).setParameter("eidx", endIdx)
                .setMaxResults(amount).getResultList()) {
            if (cr.getExtractedTextHash() == null) {
                File f = new File(FilenameUtils.getFullPath(cr.getArcFile()) + JobMapperMonitor.RESOURCESDIR
                        + cr.getDigest() + ".txt");
                if (f.exists() && f.canRead()) {
                    cr.setExtractedTextHash(MD5DigestCreator.getMD5Digest(f));
                    entityManager2.merge(cr);
                } else {
                    continue;
                }
            }
            hashes.put(cr.getExtractedTextHash(), cr.getId());
        }
        if (cursize == hashes.size()) {
            break;
        } else {
            cursize = hashes.size();
        }
    }
    ids.addAll(hashes.values());
    if (ids.size() > 0) {
        entityManager2.createQuery("update CrawledResource cr set cr.validation=:v where cr.id in (:ids)")
                .setParameter("ids", ids).setParameter("v", CrawledResource.CHOOSEN_FOR_VALIDATION)
                .executeUpdate();
    }
}