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:it.infn.ct.futuregateway.apiserver.v1.ApplicationService.java

/**
 * Removes the application. Delete the application only if there are not
 * tasks associated with it because tasks must be associated with an
 * application./*from   w ww  . j  a  v a  2s. c o m*/
 * <p>
 * Applications with associated tasks can only be disabled to avoid future
 * execution of new tasks. Nevertheless, a task can be associated with a
 * disabled application and in this case will stay waiting until the
 * application is enabled.
 *
 * @param id Id of the application to remove
 */
@DELETE
public final void deleteApp(@PathParam("id") final String id) {
    Application app;
    EntityManager em = getEntityManager();
    try {
        app = em.find(Application.class, id);
        if (app == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> taskForApp = em.createNamedQuery("tasks.forApplication").setParameter("appId", id)
                    .setMaxResults(1).getResultList();
            if (taskForApp == null || taskForApp.isEmpty()) {
                em.remove(app);
            } else {
                log.info("Application " + id + " has tasks and cannot be" + " deleted");
                throw new WebApplicationException(
                        "The application cannot " + "be removed because there are associated tasks",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the application");
            throw new InternalServerErrorException("Error to remove " + "the application " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the application list");
        log.error(re);
        throw new BadRequestException("Application '" + id + "' " + "does not exist!");
    } finally {
        em.close();
    }
}

From source file:com.jada.admin.contactus.ContactUsMaintAction.java

public ActionForward remove(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Throwable {

    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    Site site = getAdminBean(request).getSite();
    ContactUsMaintActionForm form = (ContactUsMaintActionForm) actionForm;
    ContactUs contactUs = ContactUsDAO.load(site.getSiteId(), Format.getLong(form.getContactUsId()));
    em.remove(contactUs);
    ActionForward actionForward = actionMapping.findForward("removeSuccess");
    return actionForward;
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletCookieDaoImpl.java

@Override
@PortalTransactional/* w  w w . j  a  va  2 s .  c  o m*/
public IPortalCookie addOrUpdatePortletCookie(IPortalCookie portalCookie, Cookie cookie) {
    final Set<IPortletCookie> portletCookies = portalCookie.getPortletCookies();

    boolean found = false;
    final String name = cookie.getName();
    final EntityManager entityManager = this.getEntityManager();
    for (final Iterator<IPortletCookie> portletCookieItr = portletCookies.iterator(); portletCookieItr
            .hasNext();) {
        final IPortletCookie portletCookie = portletCookieItr.next();
        if (name.equals(portletCookie.getName())) {
            //Delete cookies with a maxAge of 0
            if (cookie.getMaxAge() == 0) {
                portletCookieItr.remove();
                entityManager.remove(portletCookie);
            } else {
                portletCookie.updateFromCookie(cookie);
            }

            found = true;
            break;
        }
    }

    if (!found) {
        IPortletCookie newPortletCookie = new PortletCookieImpl(portalCookie, cookie);
        portletCookies.add(newPortletCookie);
    }

    entityManager.persist(portalCookie);

    return portalCookie;
}

From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * {@inheritDoc}/*from   w w w . java2  s  .  c o  m*/
 */
@Override
public void removeRecord(final String id) throws RecordStorageException {
    if (id == null) {
        throw new RecordStorageException("parameter id is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final RecordDao dao = findRecordDao(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 RecordStorageException(e, "error removing record id: " + id);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove record id: " + id + ". no record with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:it.infn.ct.futuregateway.apiserver.v1.InfrastructureService.java

/**
 * Removes the infrastructure. Delete the infrastructure only if there are
 * not applications associated with it to avoid inconsistency in the DB.
 * <p>//from  ww  w .ja v  a2s  .c om
 * Infrastructures with associated applications can only be disabled to
 * avoid future execution of applications.
 *
 * @param id Id of the infrastructure to remove
 */
@DELETE
public final void deleteInfra(@PathParam("id") final String id) {
    Infrastructure infra;
    EntityManager em = getEntityManager();
    try {
        infra = em.find(Infrastructure.class, id);
        if (infra == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure")
                    .setParameter("infraId", id).setMaxResults(1).getResultList();
            if (appsForInfra == null || appsForInfra.isEmpty()) {
                em.remove(infra);
            } else {
                throw new WebApplicationException("The infrastructure "
                        + "cannot be removed because there are associated " + "applications",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the infrastructure");
            throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' does not exist!");
    } finally {
        em.close();
    }
}

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward remove(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Throwable {

    Site site = getAdminBean(request).getSite();
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;
    try {//from w  ww  .  ja  v  a2 s.  c  o m
        CustomAttributeGroup customAttributeGroup = CustomAttributeGroupDAO.load(site.getSiteId(),
                Format.getLong(form.getCustomAttribGroupId()));
        em.remove(customAttributeGroup);
        em.getTransaction().commit();
    } catch (Exception e) {
        if (Utility.isConstraintViolation(e)) {
            ActionMessages errors = new ActionMessages();
            errors.add("error", new ActionMessage("error.remove.customAttributeGroup.constraint"));
            saveMessages(request, errors);
            return actionMapping.findForward("error");
        }
        throw e;
    }

    ActionForward actionForward = actionMapping.findForward("removeSuccess");
    return actionForward;
}

From source file:org.apache.camel.component.jpa.JpaConsumer.java

protected DeleteHandler<Object> createDeleteHandler() {
    // look for @Consumed to allow custom callback when the Entity has been consumed
    Class<?> entityType = getEndpoint().getEntityType();
    if (entityType != null) {
        List<Method> methods = ObjectHelper.findMethodsWithAnnotation(entityType, Consumed.class);
        if (methods.size() > 1) {
            throw new IllegalArgumentException(
                    "Only one method can be annotated with the @Consumed annotation but found: " + methods);
        } else if (methods.size() == 1) {
            final Method method = methods.get(0);

            return new DeleteHandler<Object>() {
                public void deleteObject(EntityManager entityManager, Object entityBean) {
                    ObjectHelper.invokeMethod(method, entityBean);
                }//from  w w w  . ja  v  a  2 s. co m
            };
        }
    }
    if (getEndpoint().isConsumeDelete()) {
        return new DeleteHandler<Object>() {
            public void deleteObject(EntityManager entityManager, Object entityBean) {
                entityManager.remove(entityBean);
            }
        };
    } else {
        return new DeleteHandler<Object>() {
            public void deleteObject(EntityManager entityManager, Object entityBean) {
                // do nothing
            }
        };
    }
}

From source file:fr.amapj.service.services.saisiepermanence.PermanenceService.java

@DbWrite
public void updateorCreateDistribution(PermanenceDTO dto, boolean create) {
    EntityManager em = TransactionHelper.getEm();

    DatePermanence d = null;/*from   w  w w .  ja  v a2 s .  co  m*/

    if (create) {
        d = new DatePermanence();
        d.setDatePermanence(dto.datePermanence);
        em.persist(d);
    } else {
        d = em.find(DatePermanence.class, dto.id);

        List<DatePermanenceUtilisateur> dus = getAllDateDistriUtilisateur(em, d);
        for (DatePermanenceUtilisateur du : dus) {
            em.remove(du);
        }
    }

    for (PermanenceUtilisateurDTO distriUtilisateur : dto.permanenceUtilisateurs) {
        DatePermanenceUtilisateur du = new DatePermanenceUtilisateur();
        du.setDatePermanence(d);
        du.setUtilisateur(em.find(Utilisateur.class, distriUtilisateur.idUtilisateur));
        du.setNumSession(distriUtilisateur.numSession);
        em.persist(du);
    }

}

From source file:nl.b3p.viewer.config.services.GeoService.java

@PreRemove
public void removeAllLayers() {
    EntityManager em = Stripersist.getEntityManager();
    List<Layer> allLayers = em.createQuery("from Layer where service = :this").setParameter("this", this)
            .getResultList();/*from w  w w.  j  av  a  2 s .  com*/

    for (Layer l : allLayers) {
        l.getChildren().clear();
        em.remove(l);
    }
}

From source file:org.eclipse.smila.binarystorage.persistence.jpa.JPABinaryPersistence.java

/**
 * {@inheritDoc}//from  w  w  w .  j  a v  a 2s  .  com
 *
 * @see org.eclipse.smila.binarystorage.internal.impl.persistence.BinaryPersistence#deleteBinary(java.lang.String)
 */
@Override
public void deleteBinary(final String key) throws BinaryStorageException {
    if (key == null) {
        throw new BinaryStorageException("parameter key is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final BinaryStorageDao dao = findBinaryStorageDao(em, key);
            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 BinaryStorageException(e, "error removing record id: " + key);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove id: " + key + ". no binary object with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}