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.apache.juddi.api.impl.UDDIPublicationImpl.java

public void deleteService(DeleteService body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

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

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

            ((org.apache.juddi.model.BusinessService) obj).getBusinessEntity()
                    .setModifiedIncludingChildren(new Date());

            em.remove(obj);
        }

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

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

public void deleteSubscription(DeleteSubscription body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {// w  w  w. j a v  a2  s . c om
        tx.begin();

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

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

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

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

@Override
public UddiEntityPublisher identify(String authInfoNotused, String authorizedNameNotused, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {//  w w  w.  ja  v a 2s .c om
        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! ", ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;
        if (ctx == null)
            throw new UnknownUserException(
                    new ErrorMessage("errors.auth.NoPublisher", "no web service context!"));
        if (ctx.getUserPrincipal() != null) {
            user = ctx.getUserPrincipal().getName();
        }
        if (user == null) {
            MessageContext mc = ctx.getMessageContext();
            HttpServletRequest req = null;
            if (mc != null) {
                req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            }
            if (req != null && req.getUserPrincipal() != null) {
                user = req.getUserPrincipal().getName();
            }
        }
        if (user == null || user.length() == 0) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher"));
        }
        tx.begin();
        Publisher publisher = em.find(Publisher.class, user);
        if (publisher == null) {
            log.warn("Publisher \"" + user
                    + "\" was not found in the database, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(user);
            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 publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

/**
 * {@inheritDoc}//from   w ww  . j  a v  a  2s  .  c  o m
 * 
 * @see org.opencastproject.series.impl.SeriesServiceDatabase#getSeries(java.lang.String)
 */
@Override
public DublinCoreCatalog getSeries(String seriesId) throws NotFoundException, SeriesServiceDatabaseException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            throw new NotFoundException("No series with id=" + seriesId + " exists");
        }
        // Ensure this user is allowed to read this series
        String accessControlXml = entity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            // There are several reasons a user may need to load a series: to read content, to edit it, or add content
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ_CONTENT_PERMISSION)
                    && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg,
                            CONTRIBUTE_CONTENT_PERMISSION)
                    && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, EDIT_SERIES_PERMISSION)) {
                throw new UnauthorizedException(currentUser + " is not authorized to see series " + seriesId);
            }
        }
        return dcService.load(IOUtils.toInputStream(entity.getDublinCoreXML(), "UTF-8"));
    } 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.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@Override
public DublinCoreCatalog storeSeries(DublinCoreCatalog dc)
        throws SeriesServiceDatabaseException, UnauthorizedException {
    if (dc == null) {
        throw new SeriesServiceDatabaseException("Invalid value for Dublin core catalog: null");
    }//  w w  w .j  av  a2s.c o m
    String seriesId = dc.getFirst(DublinCore.PROPERTY_IDENTIFIER);
    String seriesXML;
    try {
        seriesXML = serializeDublinCore(dc);
    } catch (Exception e1) {
        logger.error("Could not serialize Dublin Core: {}", e1);
        throw new SeriesServiceDatabaseException(e1);
    }
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    DublinCoreCatalog newSeries = null;
    try {
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            // no series stored, create new entity
            entity = new SeriesEntity();
            entity.setOrganization(securityService.getOrganization().getId());
            entity.setSeriesId(seriesId);
            entity.setSeries(seriesXML);
            em.persist(entity);
            newSeries = dc;
        } else {
            // 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 series " + seriesId);
                }
            }
            entity.setSeries(seriesXML);
            em.merge(entity);
        }
        tx.commit();
        return newSeries;
    } 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:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an AnnotationStatus/*from w w w .  j a va  2 s. c  o  m*/
 * @param label
 * @param comment
 * @return
 */
public boolean createAnnotationStatus(String label, String comment, String color, JSONArray descripteur) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        comment = StringOp.deleteBlanks(comment);
        AnnotationStatus _as = new AnnotationStatus();
        _as.setComment(comment);
        _as.setLabel(label);
        _as.setDescripteur(descripteur);
        _as.setColor(color);
        //   EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            AnnotationStatus annotationstatus = (AnnotationStatus) em
                    .createQuery("from AnnotationStatus where label = ?").setParameter(1, label)
                    .getSingleResult();
            tx.commit();
            if (annotationstatus != null) {
                System.out.println(
                        "[CreateAnnotationStatus.createAnnotationStatus] this status already exists. Status : "
                                + label);
                return false;
            }
        } catch (Exception e) {
            tx.rollback();
            System.out.println(
                    "[CreateAnnotationStatus.createAnnotationStatus] this status doesn't already exist. Status : "
                            + label + " is gonna be created.");
        }
        try {
            tx.begin();
            em.persist(_as);
            tx.commit();
            //    em.close();
            return true;
        } catch (Exception e) {
            System.out
                    .println("[CreateAnnotationStatus.createAnnotationStatus] fails to create AnnotationStatus"
                            + " label : " + label + " comment : " + comment + " cause : " + e.getMessage());
            tx.rollback();
            //   em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotationStatus.createAnnotationStatus] unable to persist AnnotationStatus"
                + " not a valid label : " + label);
        return false;
    }
}

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

/**
 * Retrieves clientSubscriptionKey(s) from the persistence layer. This
 * method is specific to jUDDI. Used for server to server subscriptions
 * Administrative privilege required.// w w  w. j a va  2s  .  c  o  m
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage 
 */
public ClientSubscriptionInfoDetail getClientSubscriptionInfoDetail(GetClientSubscriptionInfoDetail body)
        throws DispositionReportFaultMessage {

    new ValidateClientSubscriptionInfo(null).validateGetClientSubscriptionInfoDetail(body);

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

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

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<String> subscriptionKeyList = body.getClientSubscriptionKey();
        for (String subscriptionKey : subscriptionKeyList) {

            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null;
            try {
                modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class,
                        subscriptionKey);
            } catch (ClassCastException e) {
            }
            if (modelClientSubscriptionInfo == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey));
            }

            org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();

            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

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

}

From source file:com.eucalyptus.images.ImageManager.java

public DeregisterImageResponseType deregister(DeregisterImageType request) throws EucalyptusCloudException {
    DeregisterImageResponseType reply = request.getReply();

    EntityTransaction tx = Entities.get(ImageInfo.class);
    try {/*from  w ww. ja  va  2  s . c o m*/
        ImageInfo imgInfo = Entities
                .uniqueResult(Images.exampleWithImageId(imageIdentifier(request.getImageId())));
        if (!canModifyImage(imgInfo)) {
            throw new EucalyptusCloudException("Not authorized to deregister image");
        }
        Images.deregisterImage(imgInfo.getDisplayName());
        tx.commit();
        return reply;
    } catch (NoSuchImageException | NoSuchElementException ex) {
        throw new ClientComputeException("InvalidAMIID.NotFound",
                "The image ID '" + request.getImageId() + "' does not exist");
    } catch (InstanceNotTerminatedException | ConstraintViolationException re) {
        throw new ClientComputeException("InvalidAMIID.Unavailable",
                "The image ID '" + request.getImageId() + "' is no longer available");
    } catch (TransactionException ex) {
        if (ex.getCause() instanceof NoSuchElementException)
            throw new ClientComputeException("InvalidAMIID.NotFound",
                    "The image ID '" + request.getImageId() + "' does not exist");
        else
            throw new EucalyptusCloudException(ex);
    } finally {
        if (tx.isActive())
            tx.rollback();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java

/**
 * Test persistence.//from  ww  w .j a  va2  s  .  co  m
 *
 * @throws Exception the exception
 */
@Test
public void testPersistence() throws Exception {

    long size = countNews();

    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();

        News news = new News();

        news.setContent("Spider-man was seen.");
        news.setHeadline("The amazing spider-man");
        news.setFs_id(1l);
        news.setLanguage("DE");
        news.setTeaser("spider-man");

        NewsCategory sport = new NewsCategory();
        sport.setFs_id(2l);
        sport.setName("Sport");
        sport.setLanguage("DE");

        NewsMetaCategory soccer = new NewsMetaCategory();
        soccer.setFs_id(3l);
        soccer.setLanguage("DE");
        soccer.setName("Fussball");

        if (sport.getMetaCategories() == null) {
            sport.setMetaCategories(new ArrayList<NewsMetaCategory>());
        }
        sport.getMetaCategories().add(soccer);

        if (news.getCategories() == null) {
            news.setCategories(new ArrayList<NewsCategory>());
        }
        news.getCategories().add(sport);

        em.persist(news);
        em.flush();
        tx.commit();

        assertEquals("Entity not filled", size + 1, countNews());

        Query query = em.createQuery("SELECT mc FROM metaCategory mc WHERE fs_id=3");
        NewsMetaCategory metaCat = (NewsMetaCategory) query.getSingleResult();
        assertNotNull(metaCat);

        query = em.createQuery(
                "SELECT c FROM category c join c.metaCategories mc WHERE mc.fs_id=" + metaCat.getFs_id());
        NewsCategory category = (NewsCategory) query.getSingleResult();
        assertNotNull(category);

        query = em.createQuery("SELECT n FROM news n join n.categories c WHERE c.fs_id=" + category.getFs_id());
        News n = (News) query.getSingleResult();
        assertNotNull(n);

    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

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

/**
 * Instructs the registry to perform a synchronous subscription
 * response./*from  w ww. j  a  v  a2  s  .  c om*/
 * @param body
 * @return SyncSubscriptionDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
@SuppressWarnings("unchecked")
public SyncSubscriptionDetail invokeSyncSubscription(SyncSubscription body)
        throws DispositionReportFaultMessage, RemoteException {

    //validate
    SyncSubscriptionDetail syncSubscriptionDetail = new SyncSubscriptionDetail();

    Map<String, org.apache.juddi.api_v3.ClientSubscriptionInfo> clientSubscriptionInfoMap = new HashMap<String, org.apache.juddi.api_v3.ClientSubscriptionInfo>();
    //find the clerks to go with these subscriptions
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        this.getEntityPublisher(em, body.getAuthInfo());
        for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) {
            String subscriptionKey = getSubscriptionResult.getSubscriptionKey();
            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null;
            try {
                modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class,
                        subscriptionKey);
            } catch (ClassCastException e) {
            }
            if (modelClientSubscriptionInfo == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey));
            }
            org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();
            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);
            clientSubscriptionInfoMap.put(apiClientSubscriptionInfo.getSubscriptionKey(),
                    apiClientSubscriptionInfo);
        }

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

    for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) {
        try {
            String subscriptionKey = getSubscriptionResult.getSubscriptionKey();
            Clerk fromClerk = clientSubscriptionInfoMap.get(subscriptionKey).getFromClerk();
            Clerk toClerk = clientSubscriptionInfoMap.get(subscriptionKey).getToClerk();
            String clazz = fromClerk.getNode().getProxyTransport();
            Class<?> transportClass = ClassUtil.forName(clazz, this.getClass());
            Transport transport = (Transport) transportClass.getConstructor(String.class)
                    .newInstance(fromClerk.getNode().getName());
            UDDISubscriptionPortType subscriptionService = transport
                    .getUDDISubscriptionService(fromClerk.getNode().getSubscriptionUrl());
            SubscriptionResultsList list = subscriptionService.getSubscriptionResults(getSubscriptionResult);

            JAXBContext context = JAXBContext.newInstance(list.getClass());
            Marshaller marshaller = context.createMarshaller();
            StringWriter sw = new StringWriter();
            marshaller.marshal(list, sw);

            log.info("Notification received by UDDISubscriptionListenerService : " + sw.toString());

            NotificationList<String> nl = NotificationList.getInstance();
            nl.getNotifications().add(sw.toString());

            //update the registry with the notification list.
            XRegisterHelper.handle(fromClerk, toClerk, list);

            syncSubscriptionDetail.getSubscriptionResultsList().add(list);
        } catch (Exception ce) {
            log.error(ce.getMessage(), ce);
            if (ce instanceof DispositionReportFaultMessage) {
                throw (DispositionReportFaultMessage) ce;
            }
            if (ce instanceof RemoteException) {
                throw (RemoteException) ce;
            }
        }
    }
    //for now sending a clean object back

    return syncSubscriptionDetail;
}