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.v3.auth.LdapSimpleAuthenticator.java

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }/*from   w ww  .  j a  v a 2s  .c  o  m*/

    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;
        logger.error("config exception! " + authorizedName, ex);
    }
    boolean isLdapUser = false;
    try {
        env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(Context.SECURITY_AUTHENTICATION,
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));
        env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389
        env.put(Context.SECURITY_PRINCIPAL, authorizedName);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher 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();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

From source file:nl.b3p.kaartenbalie.reporting.ReportThread.java

public void run() {

    try {//from  w  w w.  ja v a2s .  c o m
        EntityTransaction tx = em.getTransaction();

        long processStart = System.currentTimeMillis();

        Report report = new Report();
        tx = em.getTransaction();
        tx.begin();
        try {
            /*
             * Store all the parameters in the report...
             */
            report.setOrganization(organization);
            report.setStartDate(startDate);
            report.setEndDate(endDate);
            report.setName(name);
            String mime = (String) CastorXmlTransformer.getContentTypes().get(type);
            report.setReportMime(mime);

            em.persist(report);
            em.flush();
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            throw ex;
        }

        try {
            Parameters parameters = new Parameters();
            parameters.setDateEnd(new org.exolab.castor.types.Date(endDate));
            parameters.setDateStart(new org.exolab.castor.types.Date(startDate));
            parameters.setId(Integer.toString(report.getId().intValue()));
            parameters.setOrganization(organization.getName());
            parameters.setTimeStamp(new Date());

            MonitorReport mr = createMonitorReport();

            Long procTime = new Long(System.currentTimeMillis() - processStart);
            parameters.setProcessingTime(procTime.longValue());
            mr.setParameters(parameters);
            report.setProcessingTime(procTime);

            if (type.equalsIgnoreCase(CastorXmlTransformer.HTML)) {
                CastorXmlTransformer cxt = new CastorXmlTransformer(xsl, MyEMFDatabase.localPath());
                report.setReportXML(cxt.createHtml(mr));
            } else {
                CastorXmlTransformer cxt = new CastorXmlTransformer();
                report.setReportXML(cxt.createXml(mr));
            }
        } catch (Exception e) {
            StringBuffer rerror = new StringBuffer();
            rerror.append("<error>");
            rerror.append(e.getLocalizedMessage());

            StackTraceElement[] ste = e.getStackTrace();
            if (ste.length > 0) {
                rerror.append(" at ");
                rerror.append(ste[0].toString());
            }
            rerror.append("</error>");
            report.setReportXML(rerror.toString());
        }

        tx = em.getTransaction();
        tx.begin();
        try {
            em.merge(report);
            em.flush();
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            throw ex;
        }
    } catch (Exception e) {
        log.error("", e);
    } finally {
        log.debug("Closing local entity manager ......");
        if (em != null && em.isOpen()) {
            em.close();
        }
        em = null;
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//from  w w w. ja  v a 2s . c  o  m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#delete(String, Id)
 */
@Override
public void delete(final String sessionId, final ConnectivityId id)
        throws DeltaIndexingSessionException, DeltaIndexingException {
    if (id == null) {
        throw new DeltaIndexingException("parameter id is null");
    }
    _lock.readLock().lock();
    try {
        assertSession(sessionId, id.getDataSourceId());
        final EntityManager em = createEntityManager();
        try {
            final DeltaIndexingDao dao = findDeltaIndexingDao(em, id);
            if (dao != null) {
                final EntityTransaction transaction = em.getTransaction();
                try {
                    transaction.begin();
                    em.remove(dao);
                    transaction.commit();
                } catch (final Exception e) {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                    throw new DeltaIndexingException("error deleting id: " + id, e);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not delete id: " + id + ". Id does not exist.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationService.java

/**
 * Removes the application. Delete the application only if there are not
 * tasks associated with it because tasks must be associated with an
 * application./*ww w.j a  v  a 2 s .  c  om*/
 * <p>
 * Applications with associated tasks can only be disabled to avoid future
 * execution of new tasks. Nevertheless, a task can be associated with a
 * disabled application and in this case will stay waiting until the
 * application is enabled.
 *
 * @param id Id of the application to remove
 */
@DELETE
public final void deleteApp(@PathParam("id") final String id) {
    Application app;
    EntityManager em = getEntityManager();
    try {
        app = em.find(Application.class, id);
        if (app == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> taskForApp = em.createNamedQuery("tasks.forApplication").setParameter("appId", id)
                    .setMaxResults(1).getResultList();
            if (taskForApp == null || taskForApp.isEmpty()) {
                em.remove(app);
            } else {
                log.info("Application " + id + " has tasks and cannot be" + " deleted");
                throw new WebApplicationException(
                        "The application cannot " + "be removed because there are associated tasks",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the application");
            throw new InternalServerErrorException("Error to remove " + "the application " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the application list");
        log.error(re);
        throw new BadRequestException("Application '" + id + "' " + "does not exist!");
    } finally {
        em.close();
    }
}

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

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }/*from w  w w  . j ava2s.  c o m*/

    boolean isLdapUser = false;

    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;
        logger.error("config exception! " + authorizedName, ex);
    }

    try {
        env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(Context.SECURITY_AUTHENTICATION,
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));

        env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389
        String format = String.format(
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_LDAP_EXPANDED_STR),
                authorizedName);

        env.put(Context.SECURITY_PRINCIPAL, format);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher 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();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

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

/**
 * Completely deletes a tModel from the persistence layer.
 * Administrative privilege required. All entities that reference this tModel
 * will no longer be able to use the tModel if jUDDI Option Enforce referential Integrity is enabled.<br>
 * Required permission, you must be am administrator
 * {@link Property#JUDDI_ENFORCE_REFERENTIAL_INTEGRITY}
 * @param body// w  w w . java 2s .c  o  m
 * @throws DispositionReportFaultMessage 
 */
public void adminDeleteTModel(DeleteTModel body) throws DispositionReportFaultMessage {

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

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

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

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

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

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

@SuppressWarnings("unchecked")
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage {
    try {//from www .ja v a  2s .  co  m
        JAXBContext context = JAXBContext.newInstance(body.getClass());
        Marshaller marshaller = context.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.marshal(body, sw);

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

        @SuppressWarnings("rawtypes")
        NotificationList nl = NotificationList.getInstance();
        nl.getNotifications().add(sw.toString());

        org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = null;

        //find the clerks to go with this subscription
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();

            this.getEntityPublisher(em, body.getAuthInfo());
            String subscriptionKey = body.getSubscriptionResultsList().getSubscription().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));
            }
            apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();
            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);

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

        XRegisterHelper.handle(apiClientSubscriptionInfo.getFromClerk(), apiClientSubscriptionInfo.getToClerk(),
                body.getSubscriptionResultsList());

    } catch (JAXBException jaxbe) {
        logger.error("", jaxbe);
        throw new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client"));
    }

    new ValidateSubscriptionListener().validateNotification(body);

    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);
    return dr;
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//from www  .j  av a2  s  .c  o  m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#checkForUpdate(String, Id, String)
 */
@Override
public boolean checkForUpdate(final String sessionId, final ConnectivityId id, final String hash)
        throws DeltaIndexingSessionException, DeltaIndexingException {
    if (id == null) {
        throw new DeltaIndexingException("parameter id is null");
    }
    if (hash == null) {
        throw new DeltaIndexingException("parameter hash is null");
    }
    _lock.readLock().lock();
    try {
        assertSession(sessionId, id.getDataSourceId());
        final EntityManager em = createEntityManager();
        try {
            final DeltaIndexingDao dao = findDeltaIndexingDao(em, id);
            if (dao == null || !hash.equals(dao.getHash())) {
                return true;
            } else {
                final EntityTransaction transaction = em.getTransaction();
                try {
                    transaction.begin();
                    visitUnchangedDaos(em, dao);
                    transaction.commit();
                } catch (final Exception e) {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                    throw new DeltaIndexingException("error visiting id: " + id, e);
                }
                return false;
            }
        } catch (final Exception e) {
            throw new DeltaIndexingException("error checking for update for id: " + id, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

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

private static void verifyImageNameAndDescription(final String name, final String description)
        throws ComputeException {
    final Context ctx = Contexts.lookup();

    if (name != null) {
        if (!Images.isImageNameValid(name)) {
            throw new ClientComputeException("InvalidAMIName.Malformed",
                    "AMI names must be between 3 and 128 characters long, and may contain letters, numbers, '(', ')', '.', '-', '/' and '_'");
        }//from  w ww  .  j  a  v  a  2  s.co  m

        final EntityTransaction db = Entities.get(ImageInfo.class);
        try {
            final List<ImageInfo> images = Lists.newArrayList(Iterables.filter(
                    Entities.query(Images.exampleWithName(ctx.getUserFullName().asAccountFullName(), name),
                            Entities.queryOptions().withReadonly(true).build()),
                    new Predicate<ImageInfo>() {
                        @Override
                        public boolean apply(ImageInfo arg0) {
                            return ImageMetadata.State.available.name()
                                    .equals(arg0.getState().getExternalStateName())
                                    || ImageMetadata.State.pending.name()
                                            .equals(arg0.getState().getExternalStateName());
                        }
                    }));
            if (images.size() > 0)
                throw new ClientComputeException("InvalidAMIName.Duplicate", String.format(
                        "AMI name %s is already in use by EMI %s", name, images.get(0).getDisplayName()));
        } catch (final ComputeException e) {
            throw e;
        } catch (final Exception ex) {
            LOG.error("Error checking for duplicate image name", ex);
            throw new ComputeException("InternalError", "Error processing request.");
        } finally {
            db.rollback();
        }
    }

    if (description != null && !Images.isImageDescriptionValid(description)) {
        throw new ClientComputeException("InvalidParameter",
                "AMI descriptions must be less than 256 characters long");
    }
}

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 {/*  w  ww  .j a v  a  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();
    }
}