Example usage for javax.persistence EntityTransaction isActive

List of usage examples for javax.persistence EntityTransaction isActive

Introduction

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

Prototype

public boolean isActive();

Source Link

Document

Indicate whether a resource transaction is in progress.

Usage

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;/*from w  ww  .j a va2  s.c  o  m*/
    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:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

/**
 * {@inheritDoc}//from ww  w . j  a  v  a2 s.  c  o  m
 *
 * @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:org.apache.juddi.api.impl.UDDIInquiryImpl.java

public OperationalInfos getOperationalInfo(GetOperationalInfo body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from w  w  w . ja  v a2s  .c  o  m
        new ValidateInquiry(null).validateGetOperationalInfo(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        OperationalInfos result = new OperationalInfos();

        List<String> entityKeyList = body.getEntityKey();
        for (String entityKey : entityKeyList) {
            org.apache.juddi.model.UddiEntity modelUddiEntity = null;
            try {
                modelUddiEntity = em.find(org.apache.juddi.model.UddiEntity.class, entityKey);
            } catch (ClassCastException e) {
            }
            if (modelUddiEntity == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.EntityNotFound", entityKey));

            org.uddi.api_v3.OperationalInfo apiOperationalInfo = new org.uddi.api_v3.OperationalInfo();

            MappingModelToApi.mapOperationalInfo(modelUddiEntity, apiOperationalInfo);

            result.getOperationalInfo().add(apiOperationalInfo);
        }

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

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

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

public void deleteTModel(DeleteTModel 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).validateDeleteTModel(em, body);

        // tModels are only lazily deleted!
        List<String> entityKeyList = body.getTModelKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey);
            ((org.apache.juddi.model.Tmodel) obj).setDeleted(true);

        }

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

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. ja  va 2s. c  om*/

    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:org.apache.juddi.api.impl.UDDIInquiryImpl.java

public BusinessDetail getBusinessDetail(GetBusinessDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//w  w w  . ja v  a2  s  .c  o  m
        new ValidateInquiry(null).validateGetBusinessDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        BusinessDetail result = new BusinessDetail();

        List<String> businessKeyList = body.getBusinessKey();
        for (String businessKey : businessKeyList) {
            org.apache.juddi.model.BusinessEntity modelBusinessEntity = null;
            try {
                modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey);
            } catch (ClassCastException e) {
            }
            if (modelBusinessEntity == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey));

            org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity();

            MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

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

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

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

public ServiceDetail getServiceDetail(GetServiceDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from   w w  w  . j av a2s.c  o  m
        new ValidateInquiry(null).validateGetServiceDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        ServiceDetail result = new ServiceDetail();

        List<String> serviceKeyList = body.getServiceKey();
        for (String serviceKey : serviceKeyList) {
            org.apache.juddi.model.BusinessService modelBusinessService = null;
            try {
                modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey);
            } catch (ClassCastException e) {
            }
            if (modelBusinessService == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey));

            org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService();

            MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService);

            result.getBusinessService().add(apiBusinessService);
        }

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

        return result;

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

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

public BindingDetail getBindingDetail(GetBindingDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from ww w .ja  va  2 s .co  m
        new ValidateInquiry(null).validateGetBindingDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        BindingDetail result = new BindingDetail();

        List<String> bindingKeyList = body.getBindingKey();
        for (String bindingKey : bindingKeyList) {
            org.apache.juddi.model.BindingTemplate modelBindingTemplate = null;
            try {
                modelBindingTemplate = em.find(org.apache.juddi.model.BindingTemplate.class, bindingKey);
            } catch (ClassCastException e) {
            }
            if (modelBindingTemplate == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", bindingKey));

            org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate();

            MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate);

            result.getBindingTemplate().add(apiBindingTemplate);
        }

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

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

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * handle the update and save process./*from w  w  w .  j a v  a  2 s  .c o m*/
 *
 * @param entity the newsdrilldown entity
 * @throws Exception the exception
 */
private void handle(UXBEntity entity) throws Exception {
    /**
     * Due to a hibernate problem when updating or saving a newsdrilldown with
     * related categories we have to perform these step for saving the newsdrilldown
     *
     * 1. save/update all categories and remove them from the newsdrilldown
     *    1.1 save/update all metaCategories and remove them from the categories
     *    1.2 save the categories
     *    1.3 read all metaCategories to the categories
     *    1.4 save the categories again to create the relations
     * 2. save the newsdrilldown
     * 3. read all categories to the newsdrilldown
     */

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        News news = buildNews(entity);
        List<Long> categories = new ArrayList<Long>();

        /*
        * 1. update or save all categories
        * Steps 1.1 - 1.4
        */
        if (news.getCategories() != null && !news.getCategories().isEmpty()) {
            for (NewsCategory cat : news.getCategories()) {
                cat = saveNewsCategory(cat);
                if (!categories.contains(cat.getFs_id())) {
                    categories.add(cat.getFs_id());
                }
            }
            news.setCategories(new ArrayList<NewsCategory>());
        }

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        // 2. save the newsdrilldown
        news = saveNews(news, em);

        // 3. read all categories to the newsdrilldown
        if (!categories.isEmpty()) {
            for (Long cat : categories) {
                NewsCategory ncat = getNewsCategory(cat, news.getLanguage(), em);
                news.getCategories().add(ncat);
            }
        }

        tx.commit();

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

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

public void execute(JobExecutionContext executionContext) throws JobExecutionException {
    final JobDataMap dataMap = executionContext.getJobDetail().getJobDataMap();
    final EntityManager em = (EntityManager) dataMap.get("em");
    final Log log = (Log) dataMap.get("log");
    final Injector injector = (Injector) dataMap.get("injector");
    EntityTransaction tx = null;

    try {//  w  w  w .  j  av a  2s . c  om

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

        final GlobalExportDAO exportDAO = new GlobalExportHibernateDAO(em);

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

            /*
             * Check for auto delete schedule 
             */

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

            final Calendar scheduledCalendar = Calendar.getInstance();
            // subtract months from current date 
            scheduledCalendar.add(Calendar.MONTH, 0 - setting.getAutoDeleteFrequency().intValue());

            // get older exports
            List<GlobalExport> exports = exportDAO.getOlderExports(scheduledCalendar.getTime(),
                    setting.getOrganization());
            //delete exports and their contents
            for (final GlobalExport export : exports) {
                final List<GlobalExportContent> contents = export.getContents();
                for (GlobalExportContent content : contents) {
                    em.remove(content);
                }
                em.remove(export);
            }

        }
        tx.commit();

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

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