Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction commit.

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

From source file:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java

@Override
public Comment updateComment(String eventId, Comment comment) throws EventCommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from   w  w  w .  j ava 2  s  .c  om
        tx.begin();
        CommentDto updatedComment = CommentDatabaseUtils.mergeComment(comment, em);

        EventCommentDto dto = getEventComment(eventId, updatedComment.getId(), em);
        if (dto == null) {
            dto = new EventCommentDto(eventId, updatedComment, securityService.getOrganization().getId());
            em.persist(dto);
        } else {
            dto.setComment(updatedComment);
            em.merge(dto);
        }
        tx.commit();
        comment = updatedComment.toComment(userDirectoryService);
        sendMessageUpdate(eventId);
        return comment;
    } catch (Exception e) {
        logger.error("Could not update or store comment: {}", ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();

        throw new EventCommentDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteAllUsers() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from   w  w w .j  a v  a 2  s .  c o  m

    Query q = entityManager.createQuery("DELETE FROM BakerUser ");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

From source file:org.apache.juddi.v3.auth.JUDDIAuthenticator.java

/**
* @return the userId that came in on the request providing the user has
 * a publishing account in jUDDI./*from  www  . jav a2s .c  om*/
* @param authorizedName
* @param credential
* @return authorizedName
* @throws AuthenticationException 
*/
public String authenticate(String authorizedName, String credential) throws AuthenticationException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    log.warn("DO NOT USE JUDDI AUTHENTICATOR FOR PRODUCTION SYSTEMS - DOES NOT VALIDATE PASSWORDS, AT ALL!");
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! " + authorizedName, ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null) {
            log.warn("Publisher \"" + authorizedName + "\" was not found, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(authorizedName);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }
        return authorizedName;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteAllInstalledBuns() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from  www  .  java  2 s  .  c o  m*/

    Query q = entityManager.createQuery("DELETE FROM InstalledBun ");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();
}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Update a user setting that currently exists using its unique id to find it.
 * @param id The id for the user setting.
 * @param key The key for the user setting.
 * @param value The value for the user setting.
 * @return The updated {@link UserSetting}.
 * @throws UserSettingsServiceException/*from   w  w  w.java 2s.  c o  m*/
 */
public UserSetting updateUserSetting(long id, String key, String value) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    String orgId = "";
    String username = "";
    logger.debug("Updating user setting id: %d key: %s value: %s", id, key, value);
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        orgId = securityService.getOrganization().getId();
        username = securityService.getUser().getUsername();
        UserSettingDto userSettingDto = em.find(UserSettingDto.class, id);
        em.persist(userSettingDto);
        userSettingDto.setKey(key);
        userSettingDto.setValue(value);
        tx.commit();
        return userSettingDto.toUserSetting();
    } catch (Exception e) {
        logger.error("Could not update user setting username '%s' org:'%s' id:'%d' key:'%s' value:'%s':\n%s",
                username, orgId, id, key, value, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Create a new user setting key value pair.
 *
 * @param key/*from  w  w w  .  jav a 2  s  . c o  m*/
 *          The key to use for the current user setting.
 * @param value
 *          The value of the user setting.
 * @return A new user setting object
 * @throws UserSettingsServiceException
 */
public UserSetting addUserSetting(String key, String value) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    String orgId = "";
    String username = "";
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        orgId = securityService.getOrganization().getId();
        username = securityService.getUser().getUsername();
        UserSettingDto userSettingDto = new UserSettingDto();
        userSettingDto.setKey(key);
        userSettingDto.setValue(value);
        userSettingDto.setUsername(username);
        userSettingDto.setOrganization(orgId);
        em.persist(userSettingDto);
        tx.commit();
        return userSettingDto.toUserSetting();
    } catch (Exception e) {
        logger.error("Could not update user setting username '%s' org:'%s' key:'%s' value:'%s':%s", username,
                orgId, key, value, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteAllSubscribedResources() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from   w  w w  .  j a  v a  2 s .c  o  m

    Query q = entityManager.createQuery("DELETE FROM SubscribedResource ");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

From source file:org.isatools.isatab.ISATABUnloader.java

public void unload() {
    List<Study> studies = new LinkedList<Study>();

    EntityManager emgr = daoFactory.getEntityManager();
    Session session = (Session) emgr.getDelegate();
    EntityTransaction ts = emgr.getTransaction();

    if (studyAcc != null) {
        StudyDAO dao = daoFactory.getStudyDAO();
        Study study = dao.getByAcc(studyAcc);
        if (study == null) {
            log.warn("Study with accession '" + studyAcc + "' not found, no undeletion performed.");
            return;
        }//from w w w  .  j  ava  2  s  .  c o  m
        studies.add(study);

        unloadMgr = new UnloadManager(daoFactory, study.getSubmissionTs());
        StudyUnloader unloader = (StudyUnloader) unloadMgr.getUnloader(Study.class);
        unloader.queueByAcc(studyAcc);
    } else {
        studies.addAll(daoFactory.getStudyDAO().getBySubmissionTs(unloadMgr.getSubmissionTs()));
        unloadMgr.queueAll(studies);
    }

    try {
        if (!ts.isActive()) {
            ts.begin();
        }
        unloadMgr.delete();
        ts.commit();
    } catch (HibernateException e) {
        if (ts.isActive()) {
            ts.rollback();
        }
        throw new TabInternalErrorException("Error while performing the unloading:" + e.getMessage());
    } finally {
        session.flush();
    }

    DataFilesDispatcher fileDispatcher = new DataFilesDispatcher(daoFactory.getEntityManager());
    fileDispatcher.undispatch(studies);
}

From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java

@Override
public Principal getAuthenticatedPrincipal(String username, String password) {
    Object identity = null;/*from   ww w.j a  va  2  s.  c  o  m*/
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM);
        tx = em.getTransaction();
        tx.begin();
        try {
            User user = (User) em.createQuery("from User u where " + "lower(u.username) = lower(:username) ")
                    .setParameter("username", username).getSingleResult();
            return user;
        } catch (NoResultException nre) {
            return null;
        }
    } catch (Exception e) {
        log.error("Exception getting authenticated user from database", e);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
            tx.commit();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM);
    }
    return null;
}

From source file:org.sakaiproject.kernel.authz.simple.UserEnvironmentListener.java

/**
 * {@inheritDoc}/*from  w w  w  . ja va  2  s.  c om*/
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void onEvent(int type, String userID, String filePath, String fileName) {
    if (filePath.startsWith(userEnvironmentBase)) {
        if (fileName.equals(KernelConstants.USERENV)) {
            String userEnvBody = null;
            try {
                userEnvBody = IOUtils.readFully(jcrNodeFactoryService.getInputStream(filePath), "UTF-8");
                if (userEnvBody != null && userEnvBody.length() > 0) {
                    UserEnvironmentBean ue = beanConverter.convertToObject(userEnvBody,
                            UserEnvironmentBean.class);
                    ue.seal();

                    userEnvironmentResolverService.expire(ue.getUser().getUuid());

                    // the user environment bean contains a list of
                    // subjects, which the
                    // users membership of groups
                    Query query = entityManager.createNamedQuery(GroupMembershipBean.FINDBY_USER);
                    query.setParameter(GroupMembershipBean.USER_PARAM, ue.getUser().getUuid());
                    List<?> membershipList = query.getResultList();
                    List<GroupMembershipBean> toAdd = new ArrayList<GroupMembershipBean>();
                    List<GroupMembershipBean> toRemove = new ArrayList<GroupMembershipBean>();

                    for (Object o : membershipList) {
                        GroupMembershipBean groupMembershipBean = (GroupMembershipBean) o;
                        String subjectToken = groupMembershipBean.getSubjectToken();
                        boolean found = false;
                        for (String subject : ue.getSubjects()) {
                            if (subjectToken.equals(subject)) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            toRemove.add(groupMembershipBean);
                        }
                    }

                    for (String subject : ue.getSubjects()) {
                        boolean found = false;
                        for (Object o : membershipList) {
                            GroupMembershipBean groupMembershipBean = (GroupMembershipBean) o;
                            String subjectToken = groupMembershipBean.getSubjectToken();
                            if (subject.equals(subjectToken)) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            toAdd.add(new GroupMembershipBean(ue.getUser().getUuid(), subject));
                        }
                    }

                    UserBean u = ue.getUserBean();

                    Query userQuery = entityManager.createNamedQuery(UserBean.FINDBY_UID);
                    userQuery.setParameter(UserBean.UID_PARAM, u.getUuid());
                    List<?> userBeansByUID = userQuery.getResultList();

                    Query userQuery2 = entityManager.createNamedQuery(UserBean.FINDBY_EID);
                    userQuery2.setParameter(UserBean.EID_PARAM, u.getEid());
                    List<?> userBeansByEID = userQuery.getResultList();
                    boolean foundUserBean = false;
                    List<UserBean> toRemoveUserBeans = new ArrayList<UserBean>();
                    for (Object o : userBeansByUID) {
                        UserBean ub = (UserBean) o;
                        if (!u.getUuid().equals(ub.getUuid()) || !u.getEid().equals(ub.getEid())) {
                            if (!toRemoveUserBeans.contains(ub)) {
                                toRemoveUserBeans.add(ub);
                            }
                        } else {
                            foundUserBean = true;
                        }
                    }
                    for (Object o : userBeansByEID) {
                        UserBean ub = (UserBean) o;
                        if (!u.getUuid().equals(ub.getUuid()) || !u.getEid().equals(ub.getEid())) {
                            if (!toRemoveUserBeans.contains(ub)) {
                                toRemoveUserBeans.add(ub);
                            }
                        } else {
                            foundUserBean = true;
                        }
                    }

                    EntityTransaction transaction = entityManager.getTransaction();
                    transaction.begin();
                    if (!foundUserBean) {
                        UserBean ub = new UserBean(u.getUuid(), u.getEid());
                        entityManager.persist(ub);
                    }
                    for (UserBean ub : toRemoveUserBeans) {
                        entityManager.remove(ub);
                    }
                    for (GroupMembershipBean gm : toRemove) {
                        entityManager.remove(gm);
                    }
                    for (GroupMembershipBean gm : toAdd) {
                        entityManager.persist(gm);
                    }
                    transaction.commit();
                }

            } catch (UnsupportedEncodingException e) {
                LOG.error(e);
            } catch (IOException e) {
                LOG.warn("Failed to read userenv " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (RepositoryException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (JCRNodeFactoryServiceException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            }
        }
    }
}