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:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * Get a transaction for a session. If there is already a transaction
 * active, this transaction will be used. Otherwise a new transaction will
 * be started.//from  w  w w.  j av a  2  s.  c om
 * 
 * @param s
 *            Session for this transaction
 * @return A already active or a fresh transaction
 */
public EntityTransaction getTransaction(EntityManager s) {
    EntityTransaction result = s.getTransaction();
    if (result.isActive()) {
        if (log.isDebugEnabled()) {
            log.debug(Messages.JoiningTransaction);
        }
    } else {
        result.begin();
        if (log.isDebugEnabled()) {
            log.debug(Messages.StartingTransaction);
        }
    }

    return result;
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * @param s//from  w w w.  java  2 s . c  o m
 *            session to close
 * @param dropLocks
 *            should I drop LockManager locks?
 * @throws PMException
 *             in case of any db error
 */
private void closeSession(EntityManager s, boolean dropLocks) throws PMException {

    Validate.notNull(s);
    try {
        if (s.isOpen()) {
            try {
                EntityTransaction tx = s.getTransaction();
                if (tx.isActive()) {
                    rollbackTransaction(s, tx);
                }
            } finally {
                s.close();
            }
        }
    } catch (PersistenceException e) {
        log.error(Messages.CloseSessionFailed, e);
    } finally {
        if (dropLocks) {
            removeLocks(s);
        }
        m_sessions.remove(s);
    }
}

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

/**
 * Removes the infrastructure. Delete the infrastructure only if there are
 * not applications associated with it to avoid inconsistency in the DB.
 * <p>/*from w w w  .jav  a2s.c  om*/
 * Infrastructures with associated applications can only be disabled to
 * avoid future execution of applications.
 *
 * @param id Id of the infrastructure to remove
 */
@DELETE
public final void deleteInfra(@PathParam("id") final String id) {
    Infrastructure infra;
    EntityManager em = getEntityManager();
    try {
        infra = em.find(Infrastructure.class, id);
        if (infra == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure")
                    .setParameter("infraId", id).setMaxResults(1).getResultList();
            if (appsForInfra == null || appsForInfra.isEmpty()) {
                em.remove(infra);
            } else {
                throw new WebApplicationException("The infrastructure "
                        + "cannot be removed because there are associated " + "applications",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the infrastructure");
            throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' does not exist!");
    } finally {
        em.close();
    }
}

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

/**
 * {@inheritDoc}/*from   www. ja  va2s.  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: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));
    }/*  w w w.j  ava 2  s .c  om*/

    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:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//  w  ww  .j a  v  a 2 s . co 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: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./*  w  w w.j  a  v  a  2s  .  c o  m*/
 * <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  ww  w  .  j av a2s . com*/

    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:com.eucalyptus.images.Images.java

public static ImageInfo createPendingFromDeviceMapping(UserFullName creator, String imageNameArg,
        String imageDescription, ImageMetadata.Architecture requestArch, ImageMetadata.Platform imagePlatform,
        final List<BlockDeviceMappingItemType> blockDeviceMappings) throws Exception {

    final String imageId = ResourceIdentifiers.generateString(ImageMetadata.Type.machine.getTypePrefix());
    BlockStorageImageInfo ret = new BlockStorageImageInfo(creator, imageId, imageNameArg, imageDescription,
            new Long(-1), requestArch, imagePlatform, null, null, "snap-EUCARESERVED", false,
            Images.DEFAULT_ROOT_DEVICE);
    /// device with snap-EUCARESERVED is the placeholder to indicate register is for create-image only
    /// actual root device with snapshot is filled in later 
    BlockDeviceMappingItemType toRemove = null;
    for (final BlockDeviceMappingItemType device : blockDeviceMappings) {
        if (Images.findCreateImageRoot().apply(device))
            toRemove = device;// www .ja  va  2  s  . co m
    }
    if (toRemove != null)
        blockDeviceMappings.remove(toRemove);

    final EntityTransaction tx = Entities.get(BlockStorageImageInfo.class);
    try {
        ret = Entities.merge(ret);
        ret.setState(ImageMetadata.State.pending);
        ret.setImageFormat(ImageMetadata.ImageFormat.fulldisk.toString());
        ret.getDeviceMappings()
                .addAll(Lists.transform(blockDeviceMappings, Images.deviceMappingGenerator(ret, -1)));
        tx.commit();
        LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + creator);
    } catch (Exception e) {
        tx.rollback();
        throw new EucalyptusCloudException(
                "Failed to register pending bfebs image because of: " + e.getMessage(), e);
    } finally {
        if (tx.isActive())
            tx.rollback();
    }
    return ret;
}

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

@SuppressWarnings("unchecked")
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage {
    try {/*from  w w w.ja  v  a 2  s. c o  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;
}