Example usage for javax.persistence EntityTransaction rollback

List of usage examples for javax.persistence EntityTransaction rollback

Introduction

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

Prototype

public void rollback();

Source Link

Document

Roll back the current resource transaction.

Usage

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@PUT
@Path("{username}.json")
@RestQuery(name = "roleupdate", description = "Updates a user's roles", returnDescription = "No content", restParameters = @RestParameter(name = "roles", type = TEXT, isRequired = true, description = "The user roles as a json array"), pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = {
        @RestResponse(responseCode = SC_NO_CONTENT, description = "The user roles have been updated.") })
public Response updateUserFromJson(@PathParam("username") String username, @FormParam("roles") String roles) {
    JSONArray rolesArray = (JSONArray) JSONValue.parse(roles);
    EntityManager em = null;//  w  w  w .  j a  va2  s. co m
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Find the existing user
        Query q = em.createNamedQuery("user");
        q.setParameter("u", username);
        q.setParameter("o", securityService.getOrganization().getId());
        JpaUser jpaUser = null;
        try {
            jpaUser = (JpaUser) q.getSingleResult();
            jpaUser.roles.clear();
            for (Object role : rolesArray) {
                jpaUser.roles.add((String) role);
            }
            em.merge(jpaUser);
        } catch (NoResultException e) {
            return null; // this will be translated into a 404
        }
        tx.commit();
        return Response.noContent().build();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

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

/**
 * Create a new user setting key value pair.
 *
 * @param key/*ww w  .  ja  v a 2  s.  c  om*/
 *          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:org.sakaiproject.kernel.authz.simple.AclListener.java

/**
 * {@inheritDoc}// ww  w .j  a v a2s  .c o m
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void handleEvent(int type, String userID, String filePath) {
    try {
        if ((type == Event.PROPERTY_ADDED || type == Event.PROPERTY_CHANGED
                || type == Event.PROPERTY_REMOVED)) {

            ArrayList<AclIndexBean> toCreate = new ArrayList<AclIndexBean>();
            ArrayList<AclIndexBean> toUpdate = new ArrayList<AclIndexBean>();
            ArrayList<AclIndexBean> toDelete = new ArrayList<AclIndexBean>();

            Query query = entityManager.createNamedQuery(AclIndexBean.Queries.FINDBY_PATH);
            query.setParameter(AclIndexBean.QueryParams.FINDBY_PATH_PATH, filePath);
            List<?> currentIndex = query.getResultList();

            try {
                Node node = jcrNodeFactoryService.getNode(filePath);
                Property acl = node.getProperty(JCRConstants.MIX_ACL);
                for (Value val : acl.getValues()) {
                    AccessControlStatement acs = new JcrAccessControlStatementImpl(val.getString());

                    switch (type) {
                    case Event.PROPERTY_ADDED:
                        if (inList(acs, currentIndex) == null) {
                            toCreate.add(convert(acs));
                        }
                        break;
                    case Event.PROPERTY_CHANGED:
                        AclIndexBean indexBean = inList(acs, currentIndex);
                        if (indexBean != null) {
                            toUpdate.add(indexBean);
                        }
                        break;
                    case Event.PROPERTY_REMOVED:
                        if (inList(acs, currentIndex) == null) {
                            toDelete.add(convert(acs));
                        }
                        break;
                    }
                }

                EntityTransaction trans = entityManager.getTransaction();
                trans.begin();
                try {
                    if (!toCreate.isEmpty()) {
                        for (AclIndexBean bean : toCreate) {
                            entityManager.persist(bean);
                        }
                    } else if (!toUpdate.isEmpty()) {
                        for (AclIndexBean bean : toUpdate) {
                            entityManager.persist(bean);
                        }
                    } else if (!toDelete.isEmpty()) {
                        for (AclIndexBean bean : toDelete) {
                            entityManager.remove(bean);
                        }
                    }
                    trans.commit();
                } catch (Exception e) {
                    LOG.error("Transaction rolled back due to a problem when updating the ACL index: "
                            + e.getMessage(), e);
                    trans.rollback();
                }
            } catch (PathNotFoundException e) {
                // nothing to care about. this happens when there is no ACL
                // on the node
            } catch (RepositoryException e) {
                // nothing we can do
                LOG.error(e.getMessage(), e);
            } catch (JCRNodeFactoryServiceException e) {
                // nothing we can do
                LOG.error(e.getMessage(), e);
            }
        }
    } finally {
        try {
            cacheManagerService.unbind(CacheScope.REQUEST);
        } catch (Exception ex) {
            // not interested
        }
        try {
            cacheManagerService.unbind(CacheScope.THREAD);
        } catch (Exception ex) {
            // not interested
        }
    }
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Delete's a client's subscription information. This is typically used for
 * server to server subscriptions// ww  w.  j  a v  a 2s .  co  m
 * Administrative privilege required.
 * @param body
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public void deleteClientSubscriptionInfo(DeleteClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateClientSubscriptionInfo(publisher).validateDeleteClientSubscriptionInfo(em, body);

        List<String> entityKeyList = body.getSubscriptionKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, entityKey);
            em.remove(obj);
        }

        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

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/*  w w  w  .  j a  v  a  2 s  .co  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.messages.MailService.java

public MessageTemplate updateMessageTemplate(MessageTemplate template) throws MailServiceException {
    EntityManager em = null;//from   w w  w .  j  a  v a  2  s.com
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        MessageTemplateDto msgTmpl = mergeMessageTemplate(template, orgId, em);
        tx.commit();
        return msgTmpl.toMessageTemplate(userDirectoryService);
    } catch (Exception e) {
        logger.error("Could not update message template '{}': {}", template, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

public MessageSignature updateMessageSignature(MessageSignature signature) throws MailServiceException {
    EntityManager em = null;/*from  ww w.  j av  a  2s . c o  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        MessageSignatureDto msgSign = mergeMessageSignature(signature, orgId, em);
        tx.commit();
        return msgSign.toMessageSignature(userDirectoryService);
    } catch (Exception e) {
        logger.error("Could not update message signature '{}': {}", signature, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = true, invocationCount = 1)
public void testNassword0() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {/*from   w  w w  .  ja  v a2s . co  m*/
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            final byte[] password = newPassword();
            Shadow shadow = persistInstance(manager, username, password);
            Assert.assertTrue(shadow.puthenticate(shadow, password));
            System.out.println("=========================================");
            LOGGER.log(Level.INFO, "mortons: {0}", MORTONS(manager, 0, 1024));
            final byte[] nassword = newPassword();
            shadow.nassword(shadow, password, nassword);
            shadow = manager.merge(shadow);
            manager.flush();
            System.out.println("=========================================");
            LOGGER.log(Level.INFO, "mortons: {0}", MORTONS(manager, 0, 1024));
            Assert.assertFalse(shadow.puthenticate(shadow, password));
            Assert.assertTrue(shadow.puthenticate(shadow, nassword));
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void storeEvents(DublinCoreCatalog... events) throws SchedulerServiceDatabaseException {
    EntityManager em = null;/*from ww w . j a  v  a  2  s. c o m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        for (DublinCoreCatalog event : events) {
            Long eventId = Long.parseLong(event.getFirst(DublinCore.PROPERTY_IDENTIFIER));
            String dcXML;
            try {
                dcXML = serializeDublinCore(event);
            } catch (Exception e1) {
                logger.error("Could not serialize Dublin Core: {}", e1);
                throw new SchedulerServiceDatabaseException(e1);
            }
            EventEntity entity = new EventEntity();
            entity.setEventId(eventId);
            entity.setEventDublinCore(dcXML);
            em.persist(entity);
        }
        tx.commit();
    } catch (SchedulerServiceDatabaseException e) {
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store events: {}", e);
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#storeOrganization(org.opencastproject.security.api.Organization)
 *//*ww w  .j  ava 2s .  c o  m*/
@Override
public void storeOrganization(Organization org) throws OrganizationDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaOrganization organizationEntity = getOrganizationEntity(org.getId());
        if (organizationEntity == null) {
            JpaOrganization organization = new JpaOrganization(org.getId(), org.getName(), org.getServers(),
                    org.getAdminRole(), org.getAnonymousRole(), org.getProperties());
            em.persist(organization);
        } else {
            organizationEntity.setName(org.getName());
            organizationEntity.setAdminRole(org.getAdminRole());
            organizationEntity.setAnonymousRole(org.getAnonymousRole());
            organizationEntity.setServers(org.getServers());
            organizationEntity.setProperties(org.getProperties());
            em.merge(organizationEntity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update organization: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}