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:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Add or update a news article in the db
 *
 * @param entity The NewsItem//  w  ww  .  j  a  v a 2s .co  m
 */
public void add(UXBEntity entity) throws Exception {

    Article art = buildArticle(entity);

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

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", art.getAid());
        query.setParameter("language", art.getLanguage());

        /*
        * If the item exists in the db, we update the content and the title of the existing item
        */
        if (query.getResultList().size() > 0) {
            Article db = (Article) query.getSingleResult();
            db.setContent(art.getContent());
            db.setTitle(art.getTitle());
            db.setUrl(art.getUrl());
            db.setCreated(art.getCreated());
            db.setAid(art.getAid());
            db.setLanguage(art.getLanguage());
            db.setVersion(art.getVersion());
            db.setLastmodified(art.getLastmodified());

            art = db;
        }
        // save to db
        em.persist(art);
        em.flush();

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while writing to the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

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

/**
 * @param s/*from  w ww . j  a v a  2 s. com*/
 *            session
 * @param tx
 *            transaction
 * @throws PMReadException
 *             {@inheritDoc}
 * @throws PMAlreadyLockedException
 *             {@inheritDoc}
 * @throws PMDirtyVersionException
 *             {@inheritDoc}
 * @throws PMException
 *             {@inheritDoc}
 * @throws ProjectDeletedException
 *             if the project was deleted in another instance
 */
public void commitTransaction(EntityManager s, EntityTransaction tx) throws PMReadException,
        PMAlreadyLockedException, PMDirtyVersionException, PMException, ProjectDeletedException {

    Validate.notNull(s);
    Validate.notNull(tx);
    Validate.isTrue(tx.equals(s.getTransaction()), Messages.SessionAndTransactionDontMatch);
    try {
        tx.commit();
    } catch (PersistenceException e) {
        if (s != null && s.equals(GeneralStorage.getInstance().getMasterSession())) {
            PersistenceManager.handleDBExceptionForMasterSession(null, e);
        } else {
            PersistenceManager.handleDBExceptionForAnySession(null, e, s);
        }
    } finally {
        removeLocks(s);
    }
}

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

@Override
public void deleteSeries(String seriesId) throws SeriesServiceDatabaseException, NotFoundException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//w w  w  . j  a  v a  2  s.co  m
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            throw new NotFoundException("Series with ID " + seriesId + " does not exist");
        }
        // Ensure this user is allowed to delete 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);
            }
        }
        em.remove(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete series: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }
}

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

public void deleteTModel(DeleteTModel body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

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

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

        }

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

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

@Override
public UddiEntityPublisher identify(String notusedauthtoken, String notusedusername, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    String http_header_name = null;
    try {/*  w w  w  . j a  va 2 s  . c om*/
        http_header_name = AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_HTTP_HEADER_NAME);
        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);
    }
    if (http_header_name == null) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", "misconfiguration!"));
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;

        MessageContext mc = ctx.getMessageContext();
        HttpServletRequest req = null;
        if (mc != null) {
            req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            user = req.getHeader(http_header_name);
        }

        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:info.dolezel.jarss.rest.v1.FeedsService.java

@DELETE
@Path("{id}")
public Response unsubscribeFeed(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em;/* ww  w  .j  ava2s  .com*/
    EntityTransaction tx;
    User user;
    Feed f;
    FeedData fd;

    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();
    user = (User) context.getUserPrincipal();

    try {
        tx.begin();

        try {
            f = (Feed) em.createQuery("from Feed where id = :id", Feed.class).setParameter("id", feedId)
                    .getSingleResult();
        } catch (NoResultException e) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!f.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        fd = f.getData();
        em.remove(f);

        if (fd.getFeeds().isEmpty())
            em.remove(fd);

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

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

/**
 * Creates or updates an entry in the delta indexing database and sets the visited flag.
 * //from  www.j  av  a2  s .  c  o  m
 * @param em
 *          the EntityManager
 * @param dao
 *          the DeltaIndexingDao if a former entry exists or null
 * @param id
 *          the id of the record (just for logging)
 * @param hash
 *          the delta indexing hash
 * @param isCompound
 *          boolean flag if the record identified by id is a compound record (true) or not (false)
 * @throws DeltaIndexingException
 *           if any error occurs
 */
private void visitNewOrChangedDao(final EntityManager em, DeltaIndexingDao dao, final ConnectivityId id,
        final String hash, final boolean isCompound) throws DeltaIndexingException {
    final EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        if (dao == null) {
            dao = new DeltaIndexingDao(id, hash, isCompound, true);
            em.persist(dao);
            if (_log.isTraceEnabled()) {
                _log.trace("created and visited id: " + id);
            }
        } else {
            dao.modifyAndVisit(hash);
            em.merge(dao);
            if (_log.isTraceEnabled()) {
                _log.trace("visited Id:" + id);
            }
        }
        transaction.commit();
    } catch (final Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new DeltaIndexingException("error visiting id: " + id, e);
    }
}

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

public static void deregisterImage(String imageId) throws NoSuchImageException, InstanceNotTerminatedException {
    EntityTransaction tx = Entities.get(ImageInfo.class);
    try {//from   w  ww. j  a  va  2s .c  o m
        ImageInfo img = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        if (ImageMetadata.State.deregistered.equals(img.getState())
                || ImageMetadata.State.failed.equals(img.getState())) {
            Entities.delete(img);
        } else {
            if (img instanceof MachineImageInfo) {
                final String runManifestLocation = ((MachineImageInfo) img).getRunManifestLocation();
                final String manifestLocation = ((MachineImageInfo) img).getManifestLocation();
                // cleanup system generated buckets if exist
                if (!manifestLocation.equals(runManifestLocation))
                    img.setState(ImageMetadata.State.deregistered_cleanup);
                else
                    img.setState(ImageMetadata.State.deregistered);
            } else
                img.setState(ImageMetadata.State.deregistered);
        }
        tx.commit();
        if (img instanceof ImageMetadata.StaticDiskImage) {
            StaticDiskImages.flush((StaticDiskImage) img);
        }
    } catch (ConstraintViolationException cve) {
        tx.rollback();
        throw new InstanceNotTerminatedException(
                "To deregister " + imageId + " all associated instances must be in the terminated state.");
    } catch (TransactionException ex) {
        tx.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, ex);
    } catch (NoSuchElementException ex) {
        tx.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, ex);
    } finally {
        if (tx.isActive())
            tx.rollback();
    }
}

From source file:ar.com.zauber.commons.repository.closures.OpenEntityManagerClosure.java

/** @see Closure#execute(Object) */
public final void execute(final T t) {
    if (dryrun) {
        //permite evitar que se hagan commit() en el ambiente de test
        target.execute(t);/*from   w  ww. java 2  s  .  c o  m*/
    } else {
        boolean participate = false;
        EntityTransaction transaction = null;

        if (TransactionSynchronizationManager.hasResource(emf)) {
            // Do not modify the EntityManager: just set the participate flag.
            participate = true;
        } else {
            try {
                final EntityManager em = emf.createEntityManager();
                if (openTx) {
                    if (!warningPrinted) {
                        logger.warn(
                                "The OpenEntityManagerClosure has Transactions enabled and is not recommended"
                                        + ". This behaviour will change in the future. Check setOpenTx(), ");
                    }
                    transaction = em.getTransaction();
                    transaction.begin();
                }

                TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
            } catch (PersistenceException ex) {
                throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
            }
        }

        if (transaction != null) {
            try {
                target.execute(t);
                if (transaction.getRollbackOnly()) {
                    transaction.rollback();
                } else {
                    transaction.commit();
                }
            } catch (final Throwable e) {
                if (transaction != null && transaction.isActive()) {
                    transaction.rollback();
                }
                throw new UnhandledException(e);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }
        } else {
            try {
                target.execute(t);
            } finally {
                if (!participate) {
                    final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                            .unbindResource(emf);
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }

        }
    }
}

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 {/*  www . jav a 2  s  . 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();
    }
}