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.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//from www .  j  av a 2 s  .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:uk.ac.ebi.bioinvindex.utils.datasourceload.DataSourceLoader.java

private void persistLocations(ReferenceSource isaTabSource, Collection<AssayTypeDataLocation> locations) {
    EntityTransaction transaction = getEntityManager().getTransaction();

    Timestamp ts = new Timestamp(System.currentTimeMillis());
    DaoFactory daoFactory = DaoFactory.getInstance(getEntityManager());

    DataLocationPersister locPersister = new DataLocationPersister(daoFactory, ts);
    ReferenceSourcePersister srcPersister = new ReferenceSourcePersister(daoFactory, ts);

    IdentifiableDAO<AssayTypeDataLocation> dao = daoFactory.getIdentifiableDAO(AssayTypeDataLocation.class);

    List<AssayTypeDataLocation> dataLocations = dao.getAll();

    boolean needsCommit = false;
    for (AssayTypeDataLocation dataLocation : dataLocations) {
        // TODO: Playing this way with serialize transactions is dangerous and we should fix this
        // PLEASE LEAVE THIS transaction commands here until we find a workaround, THEY ARE NEEDED in the ISATAB loader 
        if (!transaction.isActive())
            transaction.begin();/*w  w  w  .  j  a  v  a 2  s  .c  o m*/
        UnloadManager unloadManager = new UnloadManager(daoFactory, dataLocation.getSubmissionTs());
        unloadManager.queue(dataLocation);
        unloadManager.delete();
        needsCommit = true;
    }

    if (needsCommit)
        transaction.commit();
    if (!transaction.isActive())
        transaction.begin();

    needsCommit = false;
    for (AssayTypeDataLocation location : locations) {
        locPersister.persist(location);
        needsCommit = true;
    }

    if (needsCommit)
        transaction.commit();
    if (!transaction.isActive())
        transaction.begin();

    // Gets the old isaTabSource and replace with the new one in case it's already there
    // 
    AccessibleDAO<ReferenceSource> daoRef = DaoFactory.getInstance(entityManager)
            .getAccessibleDAO(ReferenceSource.class);
    ReferenceSource oldIsaTabSrc = daoRef.getByAcc(ReferenceSource.ISATAB_METADATA);
    if (oldIsaTabSrc != null) {
        UnloadManager unloadManager = new UnloadManager(DaoFactory.getInstance(entityManager),
                oldIsaTabSrc.getSubmissionTs());
        unloadManager.queue(oldIsaTabSrc);

        unloadManager.delete();
        transaction.commit();
        // At the end we have another initiated transaction
        transaction.begin();
    }

    srcPersister.persist(isaTabSource);
    transaction.commit();

    // Leave an opened transaction, so that it's possible to rejoin the one opened by an invoker
    // TODO: Playing this way to serialize transactions is dangerous and we should fix this
    // 
    transaction.begin();
}

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  w w  .  j  ava2s.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();
    }
}

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;//from   w  w w.  ja v  a 2  s . com
    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.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Create a new user setting key value pair.
 *
 * @param key/*from  w  w w .j  ava  2  s.co m*/
 *          The key to use for the current user setting.
 * @param value
 *          The value of the user setting.
 * @return A new user setting object
 * @throws UserSettingsServiceException
 */
public UserSetting addUserSetting(String key, String value) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    String orgId = "";
    String username = "";
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        orgId = securityService.getOrganization().getId();
        username = securityService.getUser().getUsername();
        UserSettingDto userSettingDto = new UserSettingDto();
        userSettingDto.setKey(key);
        userSettingDto.setValue(value);
        userSettingDto.setUsername(username);
        userSettingDto.setOrganization(orgId);
        em.persist(userSettingDto);
        tx.commit();
        return userSettingDto.toUserSetting();
    } catch (Exception e) {
        logger.error("Could not update user setting username '%s' org:'%s' key:'%s' value:'%s':%s", username,
                orgId, key, value, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

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

/**
 * Delete's a client's subscription information. This is typically used for
 * server to server subscriptions/*from   w w w  .  j a  v a  2  s.c  o m*/
 * Administrative privilege required.
 * @param body
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public void deleteClientSubscriptionInfo(DeleteClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {

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

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

        new ValidateClientSubscriptionInfo(publisher).validateDeleteClientSubscriptionInfo(em, body);

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

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

}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Update a user setting that currently exists using its unique id to find it.
 * @param id The id for the user setting.
 * @param key The key for the user setting.
 * @param value The value for the user setting.
 * @return The updated {@link UserSetting}.
 * @throws UserSettingsServiceException//w  ww  . j  a v a 2s  .  c om
 */
public UserSetting updateUserSetting(long id, String key, String value) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    String orgId = "";
    String username = "";
    logger.debug("Updating user setting id: %d key: %s value: %s", id, key, value);
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        orgId = securityService.getOrganization().getId();
        username = securityService.getUser().getUsername();
        UserSettingDto userSettingDto = em.find(UserSettingDto.class, id);
        em.persist(userSettingDto);
        userSettingDto.setKey(key);
        userSettingDto.setValue(value);
        tx.commit();
        return userSettingDto.toUserSetting();
    } catch (Exception e) {
        logger.error("Could not update user setting username '%s' org:'%s' id:'%d' key:'%s' value:'%s':\n%s",
                username, orgId, id, key, value, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.opencastproject.messages.MailService.java

public MessageTemplate updateMessageTemplate(MessageTemplate template) throws MailServiceException {
    EntityManager em = null;/*from  w w  w  . j  a v a  2 s . co  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        MessageTemplateDto msgTmpl = mergeMessageTemplate(template, orgId, em);
        tx.commit();
        return msgTmpl.toMessageTemplate(userDirectoryService);
    } catch (Exception e) {
        logger.error("Could not update message template '{}': {}", template, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

public MessageSignature updateMessageSignature(MessageSignature signature) throws MailServiceException {
    EntityManager em = null;/*from w  w w .jav  a2  s  .  c om*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        MessageSignatureDto msgSign = mergeMessageSignature(signature, orgId, em);
        tx.commit();
        return msgSign.toMessageSignature(userDirectoryService);
    } catch (Exception e) {
        logger.error("Could not update message signature '{}': {}", signature, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void storeEvents(DublinCoreCatalog... events) throws SchedulerServiceDatabaseException {
    EntityManager em = null;/* w  ww . j av  a2  s.co  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        for (DublinCoreCatalog event : events) {
            Long eventId = Long.parseLong(event.getFirst(DublinCore.PROPERTY_IDENTIFIER));
            String dcXML;
            try {
                dcXML = serializeDublinCore(event);
            } catch (Exception e1) {
                logger.error("Could not serialize Dublin Core: {}", e1);
                throw new SchedulerServiceDatabaseException(e1);
            }
            EventEntity entity = new EventEntity();
            entity.setEventId(eventId);
            entity.setEventDublinCore(dcXML);
            em.persist(entity);
        }
        tx.commit();
    } catch (SchedulerServiceDatabaseException e) {
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store events: {}", e);
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}