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.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Saves publisher(s) to the persistence layer. This method is specific
 * to jUDDI. Administrative privilege required.
 *
 * @param body//from   ww w  .ja v  a2 s  .  co  m
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage
 */
public PublisherDetail savePublisher(SavePublisher body) throws DispositionReportFaultMessage {

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

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

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

        PublisherDetail result = new PublisherDetail();

        List<org.apache.juddi.api_v3.Publisher> apiPublisherList = body.getPublisher();
        for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) {

            org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher();

            MappingApiToModel.mapPublisher(apiPublisher, modelPublisher);

            Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelPublisher);

            result.getPublisher().add(apiPublisher);
        }

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

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BindingTemplate uddiEntity,
        UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);/*from  www  .j  a v  a2  s  .  c om*/
    uddiEntity.setModifiedIncludingChildren(now);

    if (!isChild) {
        org.apache.juddi.model.BusinessService parent = em.find(org.apache.juddi.model.BusinessService.class,
                uddiEntity.getBusinessService().getEntityKey());
        parent.setModifiedIncludingChildren(now);
        em.persist(parent);

        // JUDDI-421:  now the businessEntity parent will have it's modifiedIncludingChildren set
        org.apache.juddi.model.BusinessEntity businessParent = em
                .find(org.apache.juddi.model.BusinessEntity.class, parent.getBusinessEntity().getEntityKey());
        businessParent.setModifiedIncludingChildren(now);
        em.persist(businessParent);
    }

    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.BindingTemplate existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from www .  j  a  v a 2s  . co m
        // get ID
        logger.log(Level.INFO, "doDelete(" + req.getPathInfo() + ")");
        String pathParts[] = getPathParts(req);
        if (pathParts.length < discardPathParts) {
            throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not enough part in path ("
                    + pathParts.length + " vs " + discardPathParts + ") for " + req.getPathInfo());
        }
        if (pathParts.length == discardPathParts) {
            throw new RequestException(HttpServletResponse.SC_BAD_REQUEST,
                    "Cannot PUT to collection " + req.getPathInfo());
        }
        // possible filtered query...
        String id = pathParts[discardPathParts];
        Key key = idToKey(id);
        if (key == null) {
            throw new RequestException(HttpServletResponse.SC_NOT_FOUND,
                    getObjectClass().getSimpleName() + " " + id + " could not map to key");
        }
        if (pathParts.length > discardPathParts + 1) {
            String childScope = pathParts[discardPathParts + 1];
            CRUDServlet childScopeServlet = getChildScopeServlet(id, childScope);
            childScopeServlet.doDelete(req, resp);
            return;
        }

        EntityManager em = EMF.get().createEntityManager();
        try {
            // check that object exists
            Class clazz = getObjectClass();
            Object obj = em.find(clazz, key);
            if (obj == null) {
                throw new RequestException(HttpServletResponse.SC_NOT_FOUND,
                        getObjectClass().getSimpleName() + " " + id + " not found");
            }
            // check (if required) that object is owned by requestor
            if (filterByCreator) {
                String creator = getCreator(obj);
                String requestCreator = getRequestCreator(req);
                if (!requestCreator.equals(creator))
                    throw new RequestException(HttpServletResponse.SC_UNAUTHORIZED,
                            "Requestor is not creator of " + getObjectClass().getSimpleName() + " " + id);
            }
            // validate delete
            validateDelete(obj);
            // perform update
            em.remove(obj);

            // write back old value?
            resp.setCharacterEncoding(ENCODING);
            resp.setContentType(JSON_MIME_TYPE);
            Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
            JSONWriter jw = new JSONWriter(w);
            writeObject(jw, obj);
            w.close();
        } catch (RequestException re) {
            throw re;
        } catch (Exception e) {
            logger.log(Level.WARNING, "Deleting object " + id + " of type " + getObjectClass(), e);
            throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        } finally {
            em.close();
        }
    } catch (RequestException re) {
        resp.sendError(re.getErrorCode(), re.getMessage());
        return;
    }
}

From source file:cn.buk.hotel.dao.HotelDaoImpl.java

@Override
@Transactional//from  ww w .  j a  v a  2s  . c  om
public int createHotelRatePlans(List<HotelRatePlan> ratePlans) {
    if (ratePlans == null || ratePlans.size() == 0)
        return 0;

    EntityManager em = getEm();

    List<HotelRatePlan> ratePlans0 = em
            .createQuery("select o from HotelRatePlan o where o.hotelInfo = :hotelInfo")
            .setParameter("hotelInfo", ratePlans.get(0).getHotelInfo()).getResultList();

    /**
     * ???RatePlan
     */
    boolean beDeleted;
    for (HotelRatePlan ratePlan0 : ratePlans0) {
        beDeleted = true;
        for (HotelRatePlan ratePlan : ratePlans) {
            if (ratePlan.getRatePlanCode() == ratePlan0.getRatePlanCode()) {
                beDeleted = false;
                break;
            }
        }
        if (beDeleted)
            em.remove(ratePlan0);
    }

    for (HotelRatePlan ratePlan : ratePlans) {
        createHotelRatePlan(ratePlan);
    }

    return 1;
}

From source file:org.apache.oozie.test.XTestCase.java

private void cleanUpDBTablesInternal() throws StoreException {
    EntityManager entityManager = Services.get().get(JPAService.class).getEntityManager();
    entityManager.setFlushMode(FlushModeType.COMMIT);
    entityManager.getTransaction().begin();

    Query q = entityManager.createNamedQuery("GET_WORKFLOWS");
    List<WorkflowJobBean> wfjBeans = q.getResultList();
    int wfjSize = wfjBeans.size();
    for (WorkflowJobBean w : wfjBeans) {
        entityManager.remove(w);
    }/*from w w w  .ja va  2 s .c  o m*/

    q = entityManager.createNamedQuery("GET_ACTIONS");
    List<WorkflowActionBean> wfaBeans = q.getResultList();
    int wfaSize = wfaBeans.size();
    for (WorkflowActionBean w : wfaBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_COORD_JOBS");
    List<CoordinatorJobBean> cojBeans = q.getResultList();
    int cojSize = cojBeans.size();
    for (CoordinatorJobBean w : cojBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_COORD_ACTIONS");
    List<CoordinatorActionBean> coaBeans = q.getResultList();
    int coaSize = coaBeans.size();
    for (CoordinatorActionBean w : coaBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_BUNDLE_JOBS");
    List<BundleJobBean> bjBeans = q.getResultList();
    int bjSize = bjBeans.size();
    for (BundleJobBean w : bjBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_BUNDLE_ACTIONS");
    List<BundleActionBean> baBeans = q.getResultList();
    int baSize = baBeans.size();
    for (BundleActionBean w : baBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_SLA_EVENTS");
    List<SLAEventBean> slaBeans = q.getResultList();
    int slaSize = slaBeans.size();
    for (SLAEventBean w : slaBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createQuery("select OBJECT(w) from SLARegistrationBean w");
    List<SLARegistrationBean> slaRegBeans = q.getResultList();
    int slaRegSize = slaRegBeans.size();
    for (SLARegistrationBean w : slaRegBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createQuery("select OBJECT(w) from SLASummaryBean w");
    List<SLASummaryBean> sdBeans = q.getResultList();
    int ssSize = sdBeans.size();
    for (SLASummaryBean w : sdBeans) {
        entityManager.remove(w);
    }

    entityManager.getTransaction().commit();
    entityManager.close();
    log.info(wfjSize + " entries in WF_JOBS removed from DB!");
    log.info(wfaSize + " entries in WF_ACTIONS removed from DB!");
    log.info(cojSize + " entries in COORD_JOBS removed from DB!");
    log.info(coaSize + " entries in COORD_ACTIONS removed from DB!");
    log.info(bjSize + " entries in BUNDLE_JOBS removed from DB!");
    log.info(baSize + " entries in BUNDLE_ACTIONS removed from DB!");
    log.info(slaSize + " entries in SLA_EVENTS removed from DB!");
    log.info(slaRegSize + " entries in SLA_REGISTRATION removed from DB!");
    log.info(ssSize + " entries in SLA_SUMMARY removed from DB!");

}

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

public void deletePublisherAssertions(DeletePublisherAssertions body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from  www . java  2  s. co m
        tx.begin();

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

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

        List<org.uddi.api_v3.PublisherAssertion> entityList = body.getPublisherAssertion();
        for (org.uddi.api_v3.PublisherAssertion entity : entityList) {
            org.apache.juddi.model.PublisherAssertionId pubAssertionId = new org.apache.juddi.model.PublisherAssertionId(
                    entity.getFromKey(), entity.getToKey());
            Object obj = em.find(org.apache.juddi.model.PublisherAssertion.class, pubAssertionId);
            em.remove(obj);
        }

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

From source file:org.rhq.enterprise.server.alert.AlertDefinitionWithComplexNotificationsTest.java

private void removeNoExceptions(final Object o) {
    try {//from  www  .j av  a2 s.  co  m
        executeInTransaction(false, new TransactionCallback() {
            public void execute() {
                EntityManager em = getEntityManager();
                Object o2 = em.merge(o);

                if (o2 instanceof Resource) {
                    ResourceTreeHelper.deleteResource(em, (Resource) o2);
                } else {
                    em.remove(o2);
                }

                em.flush();
            }
        });
    } catch (Exception e) {
        LOG.error("Failed to DELETE an object from database: " + o, e);
    }
}

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

/**
 * This is a temporary method to undo the messiness of this test in the past. The test will be changed to
 * clean up after itself, however this call will set the state to a clean one for environments that have
 * run the previous incarnation./*w ww.j av  a 2s.c om*/
 *
 * @throws Exception
 */
private void cleanupPreviousTestRuns() throws Exception {
    getTransactionManager().begin();
    EntityManager em = getEntityManager();

    try {
        try {
            Query query;
            List results;

            query = em.createNamedQuery(ContentSource.QUERY_FIND_BY_NAME_AND_TYPENAME);
            query.setParameter("name", "testUpdateContentSource");
            query.setParameter("typeName", "testUpdateContentSourceCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSource deleteMe = (ContentSource) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSource.QUERY_FIND_BY_NAME_AND_TYPENAME);
            query.setParameter("name", "testUpdateContentSource2");
            query.setParameter("typeName", "testUpdateContentSourceCST2");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSource deleteMe = (ContentSource) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSource.QUERY_FIND_BY_NAME_AND_TYPENAME);
            query.setParameter("name", "testConstraintViolation");
            query.setParameter("typeName", "testConstraintViolationCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSource deleteMe = (ContentSource) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSourceType.QUERY_FIND_BY_NAME);
            query.setParameter("name", "testUpdateContentSourceCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSourceType deleteMe = (ContentSourceType) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSourceType.QUERY_FIND_BY_NAME);
            query.setParameter("name", "testUpdateContentSourceCST2");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSourceType deleteMe = (ContentSourceType) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSourceType.QUERY_FIND_BY_NAME);
            query.setParameter("name", "testConstraintViolationCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSourceType deleteMe = (ContentSourceType) results.get(0);
                em.remove(deleteMe);
            }

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

}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

public void deleteTicketProp(TicketProp prop, EntityManager em) {
    boolean useTransaction = (em == null);
    if (em == null) {
        em = this.emf.createEntityManager();
    }// w  w w.j  a  va  2  s . c  o m
    try {
        if (useTransaction) {
            em.getTransaction().begin();
        }
        prop = em.merge(prop);

        if (prop == null) {
            throw new ApaException("Cannot delete prop.  Prop was not found.");
        }

        JpaRecord t = prop.getTicket();

        if (t == null) {
            throw new ApaException("Cannot delete prop.  This prop has not been assigned to a ticket.");
        }
        t.getTicketProps().remove(prop);
        em.remove(prop);
        t = em.merge(t);
        if (useTransaction) {
            em.getTransaction().commit();
        }
    } finally {
        if (useTransaction) {
            cleanup(em);
        }
    }
}

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

public void deleteBinding(DeleteBinding body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

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

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

            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService()
                    .setModifiedIncludingChildren(new Date());
            // JUDDI-421:  now the businessEntity parent will have it's modifiedIncludingChildren set
            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().getBusinessEntity()
                    .setModifiedIncludingChildren(new Date());

            em.remove(obj);
        }

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