Example usage for javax.persistence EntityManager remove

List of usage examples for javax.persistence EntityManager remove

Introduction

In this page you can find the example usage for javax.persistence EntityManager remove.

Prototype

public void remove(Object entity);

Source Link

Document

Remove the entity instance.

Usage

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

/**
 * Insert a child and persist to DB//from w ww .  ja  v a 2s  .  c  om
 * 
 * @param parent
 *            parent of child to insert
 * @param child
 *            child to insert
 * @param pos
 *            where to insert the child. if null insert after end
 * @param handler
 *            Command for adding and removing a child
 * @param doAdd
 *            specifies if an add operation should be performed. If false,
 *            the child node is removed.
 * @throws PMException in case of rollback failed
 * @throws ProjectDeletedException if the project was deleted in another
 * instance
 */
private static void processAndPersistChildNode(INodePO parent, INodePO child, Integer pos,
        AbstractCmdHandleChild handler, boolean doAdd) throws PMException, ProjectDeletedException {
    EntityTransaction tx = null;
    IPersistentObject lockedObj = null;
    GeneralStorage gs = GeneralStorage.getInstance();
    final EntityManager sess = gs.getMasterSession();
    IProjectPO currentProject = gs.getProject();
    final Persistor persistor = Persistor.instance();
    if (parent == ISpecObjContPO.TCB_ROOT_NODE) {
        lockedObj = currentProject.getSpecObjCont();
    } else if (parent == IExecObjContPO.TSB_ROOT_NODE) {
        lockedObj = currentProject.getExecObjCont();
    } else {
        lockedObj = parent;
    }
    try {
        tx = persistor.getTransaction(sess);
        persistor.lockPO(sess, lockedObj);
        if (!doAdd) { // don't lock newly created POs 
            lockedObj = child;
            persistor.lockPO(sess, lockedObj);
        }
    } catch (PersistenceException e) {
        PersistenceManager.handleDBExceptionForMasterSession(lockedObj, e);
    }
    if (doAdd) {

        handler.add(parent, child, pos);
    } else {
        handler.delete(parent, child);
    }
    try {
        if (!doAdd) {
            sess.remove(child);
        }
        persistor.commitTransaction(sess, tx);
    } catch (PersistenceException e) {
        PersistenceManager.handleDBExceptionForMasterSession(null, e);
    }
}

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/* w  ww .  j ava2  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:org.opencastproject.messages.MailService.java

public void deleteMessageTemplate(Long id) throws MailServiceException, NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;/*from w  w  w . ja  va2 s  .  c  o  m*/
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        Option<MessageTemplateDto> templateOption = findMessageTemplateById(id, orgId, em);
        if (templateOption.isNone())
            throw new NotFoundException();
        em.remove(templateOption.get());
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete message template '{}': {}", id, 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 void deleteMessageSignature(Long id) throws MailServiceException, NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;//ww  w.java 2s .co  m
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        Option<MessageSignatureDto> signatureOption = findMessageSignatureById(id, orgId, em);
        if (signatureOption.isNone())
            throw new NotFoundException();
        em.remove(signatureOption.get());
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete message signature '{}': {}", id, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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 a2  s . c om*/
@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;
    }
}

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

/**
 * {@inheritDoc}//w w w  . ja v  a  2s .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:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes every item older than the creationTime of the UXBEntity.
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *//*from w ww.j a v  a  2s .c  o  m*/
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        // Remove old newsdrilldown
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM news x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                News art = (News) obj;
                em.remove(art);
            }
        }

        // Remove old newsCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM category x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsCategory art = (NewsCategory) obj;
                em.remove(art);
            }
        }

        // Remove old newsMetaCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM metaCategory x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsMetaCategory art = (NewsMetaCategory) obj;
                em.remove(art);
            }
        }

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

From source file:portal.api.impl.PortalJpaController.java

public void deleteInstalledVxF(final InstalledVxF message) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//  ww  w  .  j a v a2s.c o  m

    entityManager.remove(message);

    entityTransaction.commit();
}

From source file:org.rhq.enterprise.server.content.test.ContentUIManagerBeanEligiblePackagesTest.java

private void tearDownTestEnvironment() throws Exception {
    getTransactionManager().begin();/*from  w  w w . jav a  2  s. com*/
    EntityManager em = getEntityManager();

    try {
        try {
            Query q = em.createNamedQuery(RepoPackageVersion.DELETE_BY_REPO_ID);
            q.setParameter("repoId", repo1.getId());
            q.executeUpdate();

            q = em.createNamedQuery(ResourceRepo.DELETE_BY_RESOURCE_ID);
            q.setParameter("resourceId", resource.getId());
            q.executeUpdate();

            getTransactionManager().commit();
        } catch (Exception e) {
            e.printStackTrace();
            getTransactionManager().rollback();
            throw e;
        }
    } finally {
        em.close();
    }

    getTransactionManager().begin();
    em = getEntityManager();

    try {
        try {
            resource = em.find(Resource.class, resource.getId());
            for (InstalledPackage ip : resource.getInstalledPackages()) {
                em.remove(ip);
            }

            package1 = em.find(Package.class, package1.getId());
            em.remove(package1);

            package2 = em.find(Package.class, package2.getId());
            em.remove(package2);

            package3 = em.find(Package.class, package3.getId());
            em.remove(package3);

            package4 = em.find(Package.class, package4.getId());
            em.remove(package4);

            packageType1 = em.find(PackageType.class, packageType1.getId());
            em.remove(packageType1);

            ResourceTreeHelper.deleteResource(em, resource);

            repo1 = em.find(Repo.class, repo1.getId());
            em.remove(repo1);

            repo2 = em.find(Repo.class, repo2.getId());
            em.remove(repo2);

            productVersion1 = em.find(ProductVersion.class, productVersion1.getId());
            em.remove(productVersion1);

            productVersion2 = em.find(ProductVersion.class, productVersion2.getId());
            em.remove(productVersion2);

            resourceType = em.find(ResourceType.class, resourceType.getId());
            em.remove(resourceType);

            getTransactionManager().commit();
        } catch (Exception e) {
            e.printStackTrace();
            getTransactionManager().rollback();
            throw e;
        }
    } finally {
        em.close();
    }
}