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:op.care.supervisor.PnlHandover.java

private CollapsiblePane createCP4Day(final LocalDate day) {
    final String key = DateFormat.getDateInstance().format(day.toDate());
    synchronized (cpMap) {
        if (!cpMap.containsKey(key)) {
            cpMap.put(key, new CollapsiblePane());
            try {
                cpMap.get(key).setCollapsed(true);
            } catch (PropertyVetoException e) {
                e.printStackTrace();/*from   ww  w. j a va 2s. c om*/
            }
        }
    }
    final CollapsiblePane cpDay = cpMap.get(key);
    if (hollidays == null) {
        hollidays = SYSCalendar.getHolidays(day.getYear(), day.getYear());
    }
    String titleDay = "<html><font size=+1>" + dayFormat.format(day.toDate())
            + SYSTools.catchNull(hollidays.get(day), " (", ")") + "</font></html>";
    final DefaultCPTitle titleCPDay = new DefaultCPTitle(titleDay, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                cpDay.setCollapsed(!cpDay.isCollapsed());
            } catch (PropertyVetoException pve) {
                // BAH!
            }
        }
    });

    final JButton btnAcknowledge = new JButton(SYSConst.icon163ledGreenOn);
    btnAcknowledge.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnAcknowledge.setToolTipText(SYSTools.xx("nursingrecords.handover.tooltips.btnAcknowledge"));
    btnAcknowledge.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            EntityManager em = OPDE.createEM();
            try {
                em.getTransaction().begin();

                synchronized (cacheHO) {
                    ArrayList<Handovers> listHO = new ArrayList<Handovers>(cacheHO.get(key));
                    for (final Handovers ho : listHO) {
                        if (!Handover2UserTools.containsUser(em, ho, OPDE.getLogin().getUser())) {
                            Handovers myHO = em.merge(ho);
                            Handover2User connObj = em
                                    .merge(new Handover2User(myHO, em.merge(OPDE.getLogin().getUser())));
                            myHO.getUsersAcknowledged().add(connObj);
                        }
                    }
                }

                synchronized (cacheNR) {
                    ArrayList<NReport> listNR = new ArrayList<NReport>(cacheNR.get(key));
                    for (final NReport nreport : listNR) {
                        if (!NR2UserTools.containsUser(em, nreport, OPDE.getLogin().getUser())) {
                            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();
            }

        }

    });
    titleCPDay.getRight().add(btnAcknowledge);

    cpDay.setTitleLabelComponent(titleCPDay.getMain());
    cpDay.setSlidingDirection(SwingConstants.SOUTH);

    if (hollidays.containsKey(day)) {
        cpDay.setBackground(SYSConst.red1[SYSConst.medium1]);
    } else if (day.getDayOfWeek() == DateTimeConstants.SATURDAY
            || day.getDayOfWeek() == DateTimeConstants.SUNDAY) {
        cpDay.setBackground(SYSConst.red1[SYSConst.light3]);
    } else {
        cpDay.setBackground(SYSConst.orange1[SYSConst.light3]);
    }
    cpDay.setOpaque(true);

    cpDay.setHorizontalAlignment(SwingConstants.LEADING);
    cpDay.setStyle(CollapsiblePane.PLAIN_STYLE);
    cpDay.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            createContentPanel4Day(day, cpDay);
            btnAcknowledge.setEnabled(true);
        }

        @Override
        public void paneCollapsed(CollapsiblePaneEvent collapsiblePaneEvent) {
            btnAcknowledge.setEnabled(false);
        }
    });

    btnAcknowledge.setEnabled(!cpDay.isCollapsed());
    if (!cpDay.isCollapsed()) {
        createContentPanel4Day(day, cpDay);
    }

    return cpDay;
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public Widgetprofile updateWidgetProfile(String uri, String name, String description, String icon) {
    EntityManager em = getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();//from ww w .  jav a  2s  .  com
    Query wpQuery = em.createNamedQuery("Widgetprofile.findByUri");
    wpQuery.setParameter("uri", uri);
    Widgetprofile widgetprofile = (Widgetprofile) wpQuery.getSingleResult();
    if (widgetprofile != null) {
        widgetprofile.setName(name);
        widgetprofile.setUpdated(new Date());
        WidgetDescription desc = widgetprofile.getDescription();
        if (desc == null) {
            desc = new WidgetDescription();
            desc.setWid_id(widgetprofile.getId());
            widgetprofile.setDescription(desc);
        }
        desc.setDescription(description);
        em.persist(em.merge(widgetprofile));
    }
    em.getTransaction().commit();
    em.close();
    return widgetprofile;
}

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

protected static User checkLoginPreemptiveAuthentication(HttpServletRequest request, EntityManager em) {

    /* Zoek gebruiker via Preemptive authentication */
    User user = null;//from   w w  w  . j av a  2  s . c  om
    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("Fout tijdens encrypten wachtwoord: ", ex);
        }
        try {
            user = (User) em
                    .createQuery("from User u where " + "lower(u.username) = lower(:username) "
                            + "and u.password = :password")
                    .setParameter("username", username).setParameter("password", encpw).getSingleResult();
        } catch (NonUniqueResultException nue) {
            log.error("Meerdere gebruikers gevonden via encrypted wachtwoord.");
            user = null;
        } catch (NoResultException nre) {
            log.debug("Geen gebruiker gevonden via encrypted wachtwoord.");
            user = null;
        }

        /* Controleer ingevuld wachtwoord met db gebruiker wachtwoord */
        if (user == null) {
            try {
                user = (User) em.createQuery("from User u where " + "lower(u.username) = lower(:username) ")
                        .setParameter("username", username).getSingleResult();
            } catch (NoResultException nre) {
                log.debug("Gebruiker " + username + " niet gevonden in db.");
                user = null;
            }

            if (user != null && !user.getPassword().equals(encpw)) {
                user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW);

                em.merge(user);
                em.flush();

                log.debug("Wachtwoord voor gebruiker " + username + " verkeerd...");
                user = null;
            }
        }
    }

    if (user != null) {
        log.debug("Basic authentication gelukt voor gebruiker: " + user.getName());
        user.setLastLoginStatus(null);
    }
    return user;
}

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

/**
 * {@inheritDoc}//from   w ww .  j  a v a  2s  .  com
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#deleteMediaPackage(String, Date)
 */
@Override
public void deleteMediaPackage(String mediaPackageId, Date deletionDate)
        throws SearchServiceDatabaseException, NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        SearchEntity searchEntity = getSearchEntity(mediaPackageId, em);
        if (searchEntity == null)
            throw new NotFoundException("No media package with id=" + mediaPackageId + " exists");

        // Ensure this user is allowed to delete this episode
        String accessControlXml = searchEntity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString()))
                throw new UnauthorizedException(
                        currentUser + " is not authorized to delete media package " + mediaPackageId);

            searchEntity.setDeletionDate(deletionDate);
            em.merge(searchEntity);
        }
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete episode {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public Message removeTagFromWidget(Widgetprofile widgetProfile, Tag tag) {
    EntityManager entityManager = getEntityManagerFactory().createEntityManager();

    List<Tag> tags = widgetProfile.getTags();
    //int index = tags.indexOf(tag);
    //if ( index != -1 ) {
    //   tags.remove(index);
    //}/*  www .  j  a  va 2 s .  c om*/
    // for some reason the tag is not found in the list so  going to do this manually
    boolean found = false;
    int index = -1;
    for (int i = 0; i < tags.size(); i++) {
        Tag aTag = tags.get(i);
        index++;
        if (aTag.getId() == tag.getId()) {
            found = true;
            break;
        }
    }
    if (found) {
        entityManager.getTransaction().begin();
        tags.remove(index);
        widgetProfile.setTags(tags);
        entityManager.merge(widgetProfile);
        entityManager.getTransaction().commit();
    }

    Message msg = new Message();
    if (found) {
        msg.setMessage("OK");
    } else {
        msg.setMessage("Link between widget: " + widgetProfile.getId() + " and tag: " + tag.getTagtext()
                + " could not be deleted");
    }

    entityManager.close();
    return msg;
    /*
    EntityManager entityManager = getEntityManagerFactory()
    .createEntityManager();
            
    entityManager.getTransaction().begin();
            
    Query q = entityManager.createQuery("DELETE FROM widgetprofiles_tags WHERE widgetprofile_id=?1 AND tag_id=?2");
    q.setParameter(1, widgetProfile.getId());
    q.setParameter(2, tag.getId());
    int n = q.executeUpdate();
    Message msg = new Message();
    if ( n == 1 ) {
       msg.setMessage("OK");
    }
    else if ( n == 0 ) {
       msg.setMessage("Link between widget: "+widgetProfile.getId()+" and tag: "+tag.getTagtext()+" could not be deleted");
    }
    else {
       msg.setMessage("Serious internal error, too many tags deleted");
    }
    entityManager.getTransaction().commit();
    entityManager.close();
    return msg;*/
}

From source file:op.care.values.PnlValues.java

private JPanel getMenu(final ResValue resValue) {

    final ResValueTypes vtype = resValue.getType();

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

    boolean doesNotBelongToResInfos = ResInfoTools.getInfosFor(resValue).isEmpty();

    if (doesNotBelongToResInfos && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***/*from w  w w . ja  v a 2 s  .co  m*/
         *      _____    _ _ _
         *     | ____|__| (_) |_
         *     |  _| / _` | | __|
         *     | |__| (_| | | |_
         *     |_____\__,_|_|\__|
         *
         */
        final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.vitalparameters.btnEdit.tooltip",
                SYSConst.icon22edit3, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgValue(resValue.clone(), DlgValue.MODE_EDIT, 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 ResValue newValue = em.merge((ResValue) o);
                                ResValue oldValue = em.merge(resValue);

                                em.lock(oldValue, LockModeType.OPTIMISTIC);
                                newValue.setReplacementFor(oldValue);

                                for (SYSVAL2FILE oldAssignment : oldValue.getAttachedFilesConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldValue.getAttachedFilesConnections().clear();
                                for (SYSVAL2PROCESS oldAssignment : oldValue.getAttachedProcessConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldValue.getAttachedProcessConnections().clear();

                                oldValue.setEditedBy(em.merge(OPDE.getLogin().getUser()));
                                oldValue.setEditDate(new Date());
                                oldValue.setReplacedBy(newValue);

                                em.getTransaction().commit();

                                DateTime dt = new DateTime(newValue.getPit());
                                final String keyType = vtype.getID() + ".xtypes";
                                final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                        + ".year";

                                synchronized (mapType2Values) {
                                    mapType2Values.get(key).remove(resValue);
                                    mapType2Values.get(key).add(oldValue);
                                    mapType2Values.get(key).add(newValue);
                                    Collections.sort(mapType2Values.get(key));
                                }

                                createCP4Year(vtype, dt.getYear());

                                try {
                                    synchronized (cpMap) {
                                        cpMap.get(keyType).setCollapsed(false);
                                        cpMap.get(key).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();
                            }

                        }
                    }
                });
            }
        });
        btnEdit.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnEdit);

        /***
         *      ____       _      _
         *     |  _ \  ___| | ___| |_ ___
         *     | | | |/ _ \ |/ _ \ __/ _ \
         *     | |_| |  __/ |  __/ ||  __/
         *     |____/ \___|_|\___|\__\___|
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton(
                "nursingrecords.vitalparameters.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().format(resValue.getPit()) + "</i><br/>"
                        + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o.equals(JOptionPane.YES_OPTION)) {

                                    EntityManager em = OPDE.createEM();
                                    try {

                                        em.getTransaction().begin();

                                        ResValue myValue = em.merge(resValue);
                                        myValue.setDeletedBy(em.merge(OPDE.getLogin().getUser()));

                                        for (SYSVAL2FILE file : myValue.getAttachedFilesConnections()) {
                                            em.remove(file);
                                        }
                                        myValue.getAttachedFilesConnections().clear();

                                        // Vorgangszuordnungen entfernen
                                        for (SYSVAL2PROCESS connObj : myValue.getAttachedProcessConnections()) {
                                            em.remove(connObj);
                                        }
                                        myValue.getAttachedProcessConnections().clear();
                                        myValue.getAttachedProcesses().clear();
                                        em.getTransaction().commit();

                                        DateTime dt = new DateTime(myValue.getPit());
                                        final String keyType = vtype.getID() + ".xtypes";

                                        final String key = vtype.getID() + ".xtypes."
                                                + Integer.toString(dt.getYear()) + ".year";

                                        synchronized (mapType2Values) {
                                            mapType2Values.get(key).remove(resValue);
                                            mapType2Values.get(key).add(myValue);
                                            Collections.sort(mapType2Values.get(key));
                                        }

                                        createCP4Year(vtype, dt.getYear());

                                        try {
                                            synchronized (cpMap) {
                                                cpMap.get(keyType).setCollapsed(false);
                                                cpMap.get(key).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();
                                    }

                                }
                            }
                        });
            }
        });
        btnDelete.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnDelete);

        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) {
                new DlgFiles(resValue, new Closure() {
                    @Override
                    public void execute(Object o) {
                        EntityManager em = OPDE.createEM();
                        final ResValue myValue = em.find(ResValue.class, resValue.getID());
                        em.close();

                        DateTime dt = new DateTime(myValue.getPit());
                        final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                + ".year";

                        synchronized (mapType2Values) {
                            mapType2Values.get(key).remove(resValue);
                            mapType2Values.get(key).add(myValue);
                            Collections.sort(mapType2Values.get(key));
                        }

                        buildPanel();
                    }
                });
            }
        });
        btnFiles.setEnabled(!resValue.isObsolete() && 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(resValue, 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);
                            ResValue myValue = em.merge(resValue);
                            em.lock(myValue, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSVAL2PROCESS> attached = new ArrayList<SYSVAL2PROCESS>(
                                    resValue.getAttachedProcessConnections());
                            for (SYSVAL2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getResValue().getAttachedProcessConnections().remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + myValue.getTitle() + " ID: " + myValue.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(myValue)) {
                                    QProcess myQProcess = em.merge(qProcess);
                                    SYSVAL2PROCESS myLinkObject = em
                                            .merge(new SYSVAL2PROCESS(myQProcess, myValue));
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                    + myValue.getTitle() + " ID: " + myValue.getID(),
                                            PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                    qProcess.getAttachedResValueConnections().add(myLinkObject);
                                    myValue.getAttachedProcessConnections().add(myLinkObject);
                                }
                            }

                            em.getTransaction().commit();

                            DateTime dt = new DateTime(myValue.getPit());
                            final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                    + ".year";

                            synchronized (mapType2Values) {
                                mapType2Values.get(key).remove(resValue);
                                mapType2Values.get(key).add(myValue);
                                Collections.sort(mapType2Values.get(key));
                            }

                            createCP4Year(vtype, dt.getYear());

                            buildPanel();
                            //GUITools.flashBackground(contentmap.get(keyMonth), 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();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (RollbackException ole) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });
            }
        });
        btnProcess.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnProcess);
    }
    return pnlMenu;
}

From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@Override
public boolean storeSeriesAccessControl(String seriesId, AccessControlList accessControl)
        throws NotFoundException, SeriesServiceDatabaseException {
    if (accessControl == null) {
        logger.error("Access control parameter is <null> for series '{}'", seriesId);
        throw new IllegalArgumentException("Argument for updating ACL for series " + seriesId + " is null");
    }// w w  w . j  ava  2s . c  o  m

    String serializedAC;
    try {
        serializedAC = AccessControlParser.toXml(accessControl);
    } catch (Exception e) {
        logger.error("Could not serialize access control parameter: {}", e.getMessage());
        throw new SeriesServiceDatabaseException(e);
    }
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    boolean updated = false;
    try {
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            throw new NotFoundException("Series with ID " + seriesId + " does not exist.");
        }
        if (entity.getAccessControl() != null) {
            // Ensure this user is allowed to update this series
            String accessControlXml = entity.getAccessControl();
            if (accessControlXml != null) {
                AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
                User currentUser = securityService.getUser();
                Organization currentOrg = securityService.getOrganization();
                if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, EDIT_SERIES_PERMISSION)) {
                    throw new UnauthorizedException(
                            currentUser + " is not authorized to update ACLs on series " + seriesId);
                }
            }
            updated = true;
        }
        entity.setAccessControl(serializedAC);
        em.merge(entity);
        tx.commit();
        return updated;
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not update series: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }
}

From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //logger.log(Level.INFO, "doPost("+req.getContextPath()+")");
    try {//from  w  ww  .j ava2  s.com
        // get ID
        logger.log(Level.INFO, "doPut(" + req.getPathInfo() + ")");
        String pathParts[] = getPathParts(req);
        if (pathParts.length < discardPathParts) {
            throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not enough part in path ("
                    + pathParts.length + " vs " + discardPathParts + ") for " + req.getPathInfo());
        }
        if (pathParts.length == discardPathParts) {
            throw new RequestException(HttpServletResponse.SC_BAD_REQUEST,
                    "Cannot PUT to collection " + req.getPathInfo());
        }
        // possible filtered query...
        String id = pathParts[discardPathParts];
        Key key = idToKey(id);
        if (key == null) {
            throw new RequestException(HttpServletResponse.SC_NOT_FOUND,
                    getObjectClass().getSimpleName() + " " + id + " could not map to key");
        }
        if (pathParts.length > discardPathParts + 1) {
            String childScope = pathParts[discardPathParts + 1];
            CRUDServlet childScopeServlet = getChildScopeServlet(id, childScope);
            childScopeServlet.doPut(req, resp);
            return;
        }
        // parse new value
        Object newobj = parseObject(req);

        EntityManager em = EMF.get().createEntityManager();
        try {
            // check that object exists
            Class clazz = getObjectClass();
            Object obj = em.find(clazz, key);
            if (obj == null) {
                throw new RequestException(HttpServletResponse.SC_NOT_FOUND,
                        getObjectClass().getSimpleName() + " " + id + " not found");
            }
            // check (if required) that object is owned by requestor
            if (filterByCreator) {
                String creator = getCreator(obj);
                String requestCreator = getRequestCreator(req);
                if (!requestCreator.equals(creator))
                    throw new RequestException(HttpServletResponse.SC_UNAUTHORIZED,
                            "Requestor is not creator of " + getObjectClass().getSimpleName() + " " + id);
                // set creator
                setCreator(newobj, creator);
            }
            // validate update
            validateUpdate(newobj, obj);
            // perform update
            em.merge(newobj);

            resp.setCharacterEncoding(ENCODING);
            resp.setContentType(JSON_MIME_TYPE);
            Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
            JSONWriter jw = new JSONWriter(w);
            writeObject(jw, newobj);
            w.close();
        } catch (RequestException re) {
            throw re;
        } catch (Exception e) {
            logger.log(Level.WARNING, "Updating object " + id + " of type " + getObjectClass(), e);
            throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        } finally {
            em.close();
        }
    } catch (RequestException re) {
        resp.sendError(re.getErrorCode(), re.getMessage());
        return;
    }
}

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

/**
 * Save the category element of a question choice element.
 * /*w w w. ja v a 2s  .  c o m*/
 * @param categoryElement
 *            the category element to save.
 * @param em
 *            the entity manager.
 */
private void saveProjectModelCategoryElement(CategoryElement categoryElement, EntityManager em,
        HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport) {
    if (!modelesImport.contains(categoryElement)) {
        modelesImport.add(categoryElement);

        if (!modelesReset.containsKey(categoryElement)) {
            CategoryElement key = categoryElement;
            categoryElement.setId(null);

            CategoryType parentType = categoryElement.getParentType();
            if (!modelesImport.contains(parentType)) {
                modelesImport.add(parentType);

                if (!modelesReset.containsKey(parentType)) {
                    CategoryType parentKey = parentType;
                    parentType.setId(null);

                    List<CategoryElement> elements = parentType.getElements();
                    if (elements != null) {
                        parentType.setElements(null);
                        em.persist(parentType);
                        for (CategoryElement element : elements) {
                            categoryElement.setParentType(parentType);
                            saveProjectModelCategoryElement(element, em, modelesReset, modelesImport);
                        }
                        parentType.setElements(elements);
                        em.merge(parentType);
                    } else {
                        em.persist(parentType);
                    }
                    modelesReset.put(parentKey, parentType);
                } else {
                    parentType = (CategoryType) modelesReset.get(parentType);
                }
            }
            categoryElement.setParentType(parentType);
            em.persist(categoryElement);
            modelesReset.put(key, categoryElement);
        } else {
            categoryElement = (CategoryElement) modelesReset.get(categoryElement);
        }
    }
}

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

public JpaRecord updateTicketFromClientTicket(String type, PTicket clientTicket, Object idToUpdate)
        throws InvalidPropException, InvalidValueException {

    EntityManager em = this.emf.createEntityManager();

    try {//from w w  w  .  ja va 2  s  .  c o  m
        em.getTransaction().begin();
        JpaRecord existingTicket = getTicket(em, type, idToUpdate);
        deletePropsFromRecord(existingTicket, clientTicket, em);
        List<TicketProp> propsToSave = buildProps(type, existingTicket, clientTicket, em);

        for (TicketProp prop : propsToSave) {

            //TODO: This should be done when we're building the prop
            enforceStrict(prop.getPropField(), prop.getValueAsString());
            prop = (TicketProp) em.merge(prop);
            existingTicket.addTicketProp(prop);
        }
        existingTicket = saveRecord(existingTicket, em);
        em.getTransaction().commit();
        addToIndex(existingTicket.toClientTicket());
        return existingTicket;
    } catch (ApaException e) {
        em.getTransaction().rollback();
        throw e;
    } finally {
        cleanup(em);
    }
}