Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

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

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

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

/**
 * {@inheritDoc}/*from   w w w.j  av a 2  s. 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.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*  ww w.j  a v a 2s  .  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:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

public void commit() throws PersistenceCommitException {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }/*from  w  w w. j a va2  s .  c om*/

    // commit transaction
    EntityTransaction transaction = entityManager.getTransaction();
    if (transaction.isActive()) {
        try {
            transaction.commit();
        } catch (RollbackException re) {
            throw new PersistenceCommitException("Transaction commit exception: " + re, re);
        } catch (OptimisticLockException ole) {
            throw new PersistenceCommitException("Transaction locking/version commit exception: " + ole, ole);
        }
    }
}

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  a  v  a2 s . co  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: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 .ja va2  s  .  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.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@PUT
@Path("{username}.json")
@RestQuery(name = "roleupdate", description = "Updates a user's roles", returnDescription = "No content", restParameters = @RestParameter(name = "roles", type = TEXT, isRequired = true, description = "The user roles as a json array"), pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = {
        @RestResponse(responseCode = SC_NO_CONTENT, description = "The user roles have been updated.") })
public Response updateUserFromJson(@PathParam("username") String username, @FormParam("roles") String roles) {
    JSONArray rolesArray = (JSONArray) JSONValue.parse(roles);
    EntityManager em = null;/*  w w  w.  j  a  v  a2 s .c o m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Find the existing user
        Query q = em.createNamedQuery("user");
        q.setParameter("u", username);
        q.setParameter("o", securityService.getOrganization().getId());
        JpaUser jpaUser = null;
        try {
            jpaUser = (JpaUser) q.getSingleResult();
            jpaUser.roles.clear();
            for (Object role : rolesArray) {
                jpaUser.roles.add((String) role);
            }
            em.merge(jpaUser);
        } catch (NoResultException e) {
            return null; // this will be translated into a 404
        }
        tx.commit();
        return Response.noContent().build();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

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

/**
 * {@inheritDoc}//from   w  w  w  .  ja va 2  s .  c om
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#finish(String)
 */
@Override
public void finish(final String sessionId) throws DeltaIndexingSessionException, DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final DataSourceDao dao = assertSession(sessionId);
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao unlockedDao = new DataSourceDao(dao.getDataSourceId(), null);
            em.merge(unlockedDao);
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("finished session " + sessionId + " with data source: " + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error finishing delta indexing for data source: " + dao.getDataSourceId(), e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

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

/**
 * {@inheritDoc}/*from  w w w.  ja  va2 s .c  o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasources()
 */
@Override
public void unlockDatasources() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_ALL_SESSIONS);
            query.executeUpdate();
            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("removed all delta indexing sessions and unlocked all data sources");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error unlocking delta indexing data sources", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

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

@SuppressWarnings("unchecked")
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage {
    try {//from   w  w  w .j  a  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;
}

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

public static ImageInfo createFromDeviceMapping(final UserFullName userFullName, final String imageName,
        final String imageDescription, final ImageMetadata.Platform platform, String eki, String eri,
        final String rootDeviceName, final List<BlockDeviceMappingItemType> blockDeviceMappings)
        throws EucalyptusCloudException {
    final ImageMetadata.Architecture imageArch = ImageMetadata.Architecture.x86_64;//TODO:GRZE:OMGFIXME: track parent vol info; needed here 
    final ImageMetadata.Platform imagePlatform = platform;
    if (ImageMetadata.Platform.windows.equals(imagePlatform)) {
        eki = null;//from   ww w  .j  av  a 2s.  co  m
        eri = null;
    }
    // Block device mappings have been verified before control gets here. 
    // If anything has changed with regard to the snapshot state, it will be caught while data structures for the image.
    final BlockDeviceMappingItemType rootBlockDevice = Iterables.find(blockDeviceMappings,
            findEbsRoot(rootDeviceName), null);
    if (rootBlockDevice == null) {
        throw new EucalyptusCloudException(
                "Failed to create image, root device mapping not found: " + rootDeviceName);
    }

    final String snapshotId = ResourceIdentifiers.tryNormalize()
            .apply(rootBlockDevice.getEbs().getSnapshotId());
    Snapshot snap;
    try {
        snap = Transactions.one(Snapshot.named(userFullName.asAccountFullName(), snapshotId),
                RestrictedTypes.filterPrivileged(), Functions.<Snapshot>identity());
    } catch (NoSuchElementException ex) {
        throw new EucalyptusCloudException("Failed to create image from specified block device mapping: "
                + rootBlockDevice + " because of: Snapshot not found " + snapshotId);
    } catch (TransactionExecutionException ex) {
        throw new EucalyptusCloudException("Failed to create image from specified block device mapping: "
                + rootBlockDevice + " because of: " + ex.getMessage());
    } catch (ExecutionException ex) {
        LOG.error(ex, ex);
        throw new EucalyptusCloudException("Failed to create image from specified block device mapping: "
                + rootBlockDevice + " because of: " + ex.getMessage());
    }

    final Integer suppliedVolumeSize = rootBlockDevice.getEbs().getVolumeSize() != null
            ? rootBlockDevice.getEbs().getVolumeSize()
            : snap.getVolumeSize();
    final Long imageSizeBytes = suppliedVolumeSize * 1024l * 1024l * 1024l;
    final Boolean targetDeleteOnTermination = Boolean.TRUE
            .equals(rootBlockDevice.getEbs().getDeleteOnTermination());
    final String imageId = ResourceIdentifiers.generateString(ImageMetadata.Type.machine.getTypePrefix());

    final boolean mapRoot = DEFAULT_PARTITIONED_ROOT_DEVICE.equals(rootDeviceName);
    BlockStorageImageInfo ret = new BlockStorageImageInfo(userFullName, imageId, imageName, imageDescription,
            imageSizeBytes, imageArch, imagePlatform, eki, eri, snap.getDisplayName(),
            targetDeleteOnTermination, mapRoot ? DEFAULT_ROOT_DEVICE : rootDeviceName);
    final EntityTransaction tx = Entities.get(BlockStorageImageInfo.class);
    try {
        ret = Entities.merge(ret);
        Iterables.addAll(ret.getDeviceMappings(),
                Iterables.transform(blockDeviceMappings,
                        Images.deviceMappingGenerator(ret, suppliedVolumeSize, mapRoot
                                ? Collections.singletonMap(DEFAULT_PARTITIONED_ROOT_DEVICE, DEFAULT_ROOT_DEVICE)
                                : Collections.<String, String>emptyMap())));
        ret.setImageFormat(ImageMetadata.ImageFormat.fulldisk.toString());
        ret.setState(ImageMetadata.State.available);
        tx.commit();
        LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + userFullName);
    } catch (Exception e) {
        throw new EucalyptusCloudException(
                "Failed to register image using snapshot: " + snapshotId + " because of: " + e.getMessage(), e);
    } finally {
        if (tx.isActive())
            tx.rollback();
    }

    return ret;
}