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.search.impl.persistence.SearchServiceDatabaseImpl.java

/**
 * {@inheritDoc}//from  w w w  . ja  v  a2s  .c  o m
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getOrganizationId(String)
 */
@Override
public String getOrganizationId(String mediaPackageId)
        throws NotFoundException, SearchServiceDatabaseException {
    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 read this media package
        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, READ.toString()))
                throw new UnauthorizedException(
                        currentUser + " is not authorized to read media package " + mediaPackageId);
        }
        return searchEntity.getOrganization();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

public TModelDetail getTModelDetail(GetTModelDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/* w  w  w.ja  v  a  2s . co m*/
        new ValidateInquiry(null).validateGetTModelDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        TModelDetail result = new TModelDetail();

        List<String> tmodelKeyList = body.getTModelKey();
        for (String tmodelKey : tmodelKeyList) {
            org.apache.juddi.model.Tmodel modelTModel = null;
            try {
                modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
            } catch (ClassCastException e) {
            }
            if (modelTModel == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.TModelNotFound", tmodelKey));

            org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel();

            MappingModelToApi.mapTModel(modelTModel, apiTModel);

            result.getTModel().add(apiTModel);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.SUCCESS, procTime);

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

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

/**
 * {@inheritDoc}//from   w  ww  . ja  va  2 s  . c om
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getModificationDate(String)
 */
@Override
public Date getModificationDate(String mediaPackageId)
        throws NotFoundException, SearchServiceDatabaseException {
    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 read this media package
        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, READ.toString()))
                throw new UnauthorizedException(
                        currentUser + " is not authorized to read media package " + mediaPackageId);
        }
        return searchEntity.getModificationDate();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get modification date {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

/**
 * Saves publisher(s) to the persistence layer. This method is specific
 * to jUDDI. Administrative privilege required.
 *
 * @param body/*from   w w w  .ja  v a 2 s  .c o m*/
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage
 */
public PublisherDetail savePublisher(SavePublisher body) throws DispositionReportFaultMessage {

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

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

        new ValidatePublish(publisher).validateSavePublisher(em, body);

        PublisherDetail result = new PublisherDetail();

        List<org.apache.juddi.api_v3.Publisher> apiPublisherList = body.getPublisher();
        for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) {

            org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher();

            MappingApiToModel.mapPublisher(apiPublisher, modelPublisher);

            Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelPublisher);

            result.getPublisher().add(apiPublisher);
        }

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

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

/**
 * {@inheritDoc}//from   ww w.j a va  2  s. c o m
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getDeletionDate(String)
 */
@Override
public Date getDeletionDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException {
    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 read this media package
        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, READ.toString()))
                throw new UnauthorizedException(
                        currentUser + " is not authorized to read media package " + mediaPackageId);
        }
        return searchEntity.getDeletionDate();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

/** Checks wether an user, given his username and password, is allowed to use the system.
 *
 * @param username String representing the username.
 * @param password String representing the password.
 *
 * @return a principal object containing the user if he has been found as a registered user. Otherwise this object wil be empty (null).
 *//* w w  w  .ja  v a 2 s.  c  o  m*/
@Override
public Principal authenticate(String username, String password) {

    String encpw = null;
    try {
        encpw = KBCrypter.encryptText(password);
    } catch (Exception ex) {
        log.error("error encrypting password: ", ex);
    }
    Object identity = null;
    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 " + "u.timeout > :nu "
                            + "and lower(u.username) = lower(:username) " + "and u.password = :password")
                    .setParameter("nu", new Date()).setParameter("username", username)
                    .setParameter("password", encpw).getSingleResult();
            // if we get a result, this means successful login
            // set lastloginstatus to null to indicate success
            user.setLastLoginStatus(null);

            return user;
        } catch (NoResultException nre) {
            log.debug("No results using encrypted password");
        }
        // if login not succesful, set userstate to LOGIN_STATE_WRONG_PASSW
        User wrong_password_user = (User) em
                .createQuery(
                        "from User u where " + "u.timeout > :nu " + "and lower(u.username) = lower(:username) ")
                .setParameter("nu", new Date()).setParameter("username", username).getSingleResult();
        wrong_password_user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW_OR_ACCOUNT_EXPIRED);
        em.flush();
        log.warn("Login failure for username " + username);
    } catch (Exception e) {
        log.error("Exception checking user credentails", 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.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Retrieves publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required. 
 * @param body//from  w ww . ja v a2  s . c  o m
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage 
 */
public PublisherDetail getPublisherDetail(GetPublisherDetail body) throws DispositionReportFaultMessage {

    new ValidatePublisher(null).validateGetPublisherDetail(body);

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

        this.getEntityPublisher(em, body.getAuthInfo());

        PublisherDetail result = new PublisherDetail();

        List<String> publisherIdList = body.getPublisherId();
        for (String publisherId : publisherIdList) {
            org.apache.juddi.model.Publisher modelPublisher = null;
            try {
                modelPublisher = em.find(org.apache.juddi.model.Publisher.class, publisherId);
            } catch (ClassCastException e) {
            }
            if (modelPublisher == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.PublisherNotFound", publisherId));
            }

            org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher();

            MappingModelToApi.mapPublisher(modelPublisher, apiPublisher);

            result.getPublisher().add(apiPublisher);
        }

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

}

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

public void deleteBusiness(DeleteBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from  w w w.j  a  v  a  2s .  c  o  m*/
        tx.begin();

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

        new ValidatePublish(publisher).validateDeleteBusiness(em, body);

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

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Path("{id}/markAllRead")
public Response markAllRead(@Context SecurityContext context, @PathParam("id") int feedId,
        @QueryParam("allBefore") long timeMillis) {
    EntityManager em;/*  w  ww .ja  v  a  2 s.  com*/
    EntityTransaction tx;
    User user;
    Feed feed;
    Date newDate;

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();

    tx.begin();

    try {
        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!feed.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        newDate = new Date(timeMillis);
        if (feed.getReadAllBefore() == null || feed.getReadAllBefore().before(newDate)) {
            feed.setReadAllBefore(newDate);
            em.persist(feed);
        }

        em.createQuery(
                "delete from FeedItem fi where fi.feed = :feed and fi.data.date < :date and not fi.starred and not fi.exported and size(fi.tags) = 0")
                .setParameter("feed", feed).setParameter("date", newDate).executeUpdate();

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves an annotationStatus//from ww  w. j a va2s .c  om
 * @param id
 * @return
 */
public AnnotationStatus retrieveAnnotationStatus(long id) {
    //   EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        AnnotationStatus _synchro = em.find(AnnotationStatus.class, id);
        tx.commit();
        if (_synchro != null)
            return _synchro;
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " id : " + id);
        return new AnnotationStatus();
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " id : " + id + " cause : " + e.getMessage());
        return new AnnotationStatus();
    }
}