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.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

@Override
public Theme updateTheme(Theme theme) throws ThemesServiceDatabaseException {
    EntityManager em = null;/* w  w w .  ja va2s.  c  o  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        ThemeDto themeDto = null;
        if (theme.getId().isSome())
            themeDto = getThemeDto(theme.getId().get(), em);

        if (themeDto == null) {
            // no theme stored, create new entity
            themeDto = new ThemeDto();
            themeDto.setOrganization(securityService.getOrganization().getId());
            updateTheme(theme, themeDto);
            em.persist(themeDto);
        } else {
            updateTheme(theme, themeDto);
            em.merge(themeDto);
        }
        tx.commit();
        theme = themeDto.toTheme(userDirectoryService);
        messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue,
                ThemeItem.update(toSerializableTheme(theme)));
        return theme;
    } catch (Exception e) {
        logger.error("Could not update theme {}: {}", theme, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new ThemesServiceDatabaseException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

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

/**
 * {@inheritDoc}/*  w  w w.j a  va  2  s.c om*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasource(String)
 */
@Override
public void unlockDatasource(final String dataSourceID) 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_SESSION);
            query.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dataSourceID);
            query.executeUpdate();
            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("removed delta indexing sessions and unlocked data source " + dataSourceID);
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error unlocking delta indexing data source " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

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 {//from   www  .  jav  a  2s.  co m
        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: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  w  w w . j a  v  a  2 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:info.dolezel.jarss.rest.v1.FeedsService.java

@DELETE
@Path("{id}")
public Response unsubscribeFeed(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em;//w w  w  .ja v  a2s  .c  o m
    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

/**
 * {@inheritDoc}//from  www.j  a v a2s . c  om
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear()
 */
@Override
public void clear() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_ALL);
            diQuery.executeUpdate();
            // delete source
            final Query dsQuery = em.createNamedQuery(DataSourceDao.NAMED_QUERY_DELETE_SOURCES);
            dsQuery.executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves all the existing AnnotationStatus
 * @return//from  w ww .j a  v a  2 s  . c  o m
 */
public List<AnnotationStatus> retrieveAnnotationStatus() {
    //   EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        List<AnnotationStatus> annotationstatus = em.createQuery("from AnnotationStatus").getResultList();
        tx.commit();
        return annotationstatus;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " cause : " + e.getMessage());
        return new ArrayList<AnnotationStatus>();
    }
}

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 av a  2s.  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.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}// www.  ja v a  2 s.c  o  m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear(String)
 */
@Override
public void clear(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();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_BY_SOURCE);
            diQuery.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dao.getDataSourceId())
                    .executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing for sessionId: " + sessionId + " with data source "
                        + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing for session id: " + sessionId, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:de.iai.ilcd.model.dao.SourceDao.java

/**
 * Concrete implementation required for saving of digital files
 *///from  w w  w. j  a  v a  2 s.  com
@Override
public boolean checkAndPersist(Source source, PersistType pType, PrintWriter out) {
    EntityManager em = PersistenceUtil.getEntityManager();

    Source existingSource = this.getByUuid(source.getUuid().getUuid());
    if (existingSource != null) {
        if (pType == PersistType.ONLYNEW) {
            out.println(
                    "Warning: source data set with this uuid already exists in database; will ignore this data set");
            return false;
        }
    }

    EntityTransaction t = em.getTransaction();
    try {
        t.begin();
        if (existingSource != null && (pType == PersistType.MERGE)) {
            // delete first the existing one, we will use the new one
            if (out != null) {
                out.println(
                        "Notice: source data set with this uuid already exists in database; will merge this data set");
            }
            em.remove(existingSource);
            this.deleteDigitalFiles(source);
        }

        em.persist(source);

        t.commit();

        if (!super.setMostRecentVersionFlags(source.getUuidAsString())) {
            return false;
        }

        if (source != null && source.getId() != null) {
            if (!this.saveDigitalFiles(source, out)) {
                if (out != null) {
                    out.println(
                            "Warning: couldn't save all files of this source data set into database file directory: see messages above");
                }
            }
        }
        return true;

    } catch (Exception e) {
        if (out != null) {
            out.println("Can't save source data file to database because of: " + e.getMessage());
        }
        t.rollback();
        return false;
    }
}