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:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes a news article from the db// ww w.  j a  v  a 2s.c  om
 *
 * @param entity The article to delete
 */
public void delete(UXBEntity entity) throws Exception {

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

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

        //         Query query = em.createQuery(new StringBuilder().append("SELECT x FROM Article x WHERE x.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString());
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

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

From source file:org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java

/**
 * Removes an agent from the database./*  w w  w  .  j av  a  2 s.c  o  m*/
 * 
 * @param agentName
 *          The name of the agent you wish to remove.
 */
private void deleteAgentFromDatabase(String agentName) throws NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String org = securityService.getOrganization().getId();
        Agent existing = getAgentEntity(agentName, org, em);
        if (existing == null)
            throw new NotFoundException();
        em.remove(existing);
        tx.commit();
        agentCache.remove(agentName.concat(DELIMITER).concat(org));
    } catch (RollbackException e) {
        logger.warn("Unable to commit to DB in deleteAgent.");
    } finally {
        if (em != null)
            em.close();
    }
}

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

@Override
@PortalTransactional/*ww w . j  a v  a2 s  . c  om*/
public void purgeExpiredCookies(int maxAge) {
    final DateTime now = DateTime.now();

    logger.debug("begin portlet cookie expiration");

    final EntityManager entityManager = this.getEntityManager();
    final Query deletePortletCookieQuery = entityManager.createQuery(this.deletePortletCookieQueryString);
    deletePortletCookieQuery.setParameter(this.nowParameter.getName(), now);
    final int deletedPortletCookies = deletePortletCookieQuery.executeUpdate();
    logger.debug("finished purging {} portlet cookies with expiration before {}", deletedPortletCookies, now);

    final TypedQuery<PortletCookieImpl> expiredByParentCookiesQuery = this
            .createQuery(findExpiredByParentPortletCookiesQuery);
    expiredByParentCookiesQuery.setParameter(this.nowParameter.getName(), now);
    final List<PortletCookieImpl> indirectlyExpiredCookies = expiredByParentCookiesQuery.getResultList();
    for (final PortletCookieImpl portletCookieImpl : indirectlyExpiredCookies) {
        entityManager.remove(portletCookieImpl);
    }
    logger.debug("finished purging {} portlet cookies with parent expiration before {}",
            indirectlyExpiredCookies.size(), now);

    logger.debug("begin portal cookie expiration");

    final Query deletePortalCookieQuery = entityManager.createQuery(this.deletePortalCookieQueryString);
    deletePortalCookieQuery.setParameter(this.nowParameter.getName(), now);
    final int deletedPortalCookies = deletePortalCookieQuery.executeUpdate();
    logger.debug("finished purging {} portal cookies with expiration before {}", deletedPortalCookies, now);

    final Query deleteEmptyPortalCookieQuery = entityManager
            .createQuery(this.deleteEmptyPortalCookieQueryString);
    //Add the maxAge to now and then subtract the emptyCookieMaxAge
    //For example (now + 1 year) - 1 day == the empty-cookie expiration date 
    final DateTime emptyExpiration = now.plusSeconds(maxAge).minusSeconds(emptyCookieMaxAge);
    deleteEmptyPortalCookieQuery.setParameter(this.nowParameter.getName(), emptyExpiration);
    final int deletedEmptyPortalCookies = deleteEmptyPortalCookieQuery.executeUpdate();
    logger.debug("finished purging {} empty portal cookies with expiration before {}",
            deletedEmptyPortalCookies, emptyExpiration);
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public Message deleteWidgetProfileWithId(String widgetId, boolean fullDelete) {
    EntityManager em = getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();/*w  ww.j  a v  a  2 s . c o  m*/
    Widgetprofile widgetProfile = em.find(Widgetprofile.class, widgetId);
    if (fullDelete) {
        em.remove(widgetProfile);
    } else {
        widgetProfile.setDeleted((byte) 1);
    }
    em.getTransaction().commit();
    em.close();
    Message msg = new Message();
    msg.setMessage("OK");
    return msg;

}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionDaoImpl.java

@Override
@Transactional//from   www . j  a  va2 s .co  m
public void deleteSession(Session session) {
    Validate.notNull(session, "session can not be null");

    final SessionImpl sessionImpl = this.getSession(session.getSessionId());
    final EntityManager entityManager = this.getEntityManager();

    final ConferenceUserImpl creator = sessionImpl.getCreator();
    creator.getOwnedSessions().remove(sessionImpl);
    entityManager.persist(creator);

    for (final ConferenceUserImpl user : sessionImpl.getChairs()) {
        user.getChairedSessions().remove(sessionImpl);
        entityManager.persist(user);
    }

    for (final ConferenceUserImpl user : sessionImpl.getNonChairs()) {
        user.getNonChairedSessions().remove(sessionImpl);
        entityManager.persist(user);
    }

    entityManager.remove(sessionImpl);
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

public void edit(Persona persona) throws Exception {
    EntityManager em = null;
    try {//w w w.  j  a va  2 s .  co  m
        em = getEntityManager();
        em.getTransaction().begin();

        Persona personaAntigua = em.find(Persona.class, persona.getId());
        Hibernate.initialize(personaAntigua.getPersonaFirmasCollection());

        //quitar los personaTitulo que no existan en la nueva persona editada
        for (PersonaTitulo perTituloAntiguo : personaAntigua.getPersonaTitulosCollection()) {
            if (!persona.getPersonaTitulosCollection().contains(perTituloAntiguo)) {
                em.remove(perTituloAntiguo);
            }
        }
        //poner en null los ids negativos para que se puedan crear
        for (PersonaTitulo perTitulo : persona.getPersonaTitulosCollection()) {
            if (perTitulo.getId() != null && perTitulo.getId() < 0) {
                perTitulo.setId(null);
            }
            if (perTitulo.getPersona() == null) {
                perTitulo.setPersona(persona);
            }
            Titulo titulo = perTitulo.getTitulo();
            if (titulo.getId() == null || titulo.getId() < 0) {
                titulo.setId(null);
                em.persist(titulo);
            }
            if (perTitulo.getUniversidad().getId() == null || perTitulo.getUniversidad().getId() < 0) {
                perTitulo.getUniversidad().setId(null);
                em.persist(perTitulo.getUniversidad());
            }
            em.merge(perTitulo);
        }

        for (PersonaFirma perFirmaAntiguo : personaAntigua.getPersonaFirmasCollection()) {
            //revisar las firmas que estn en el antigua persona pero ya no en el nuevo editado,
            // por lo tanto si ya no estn en el nuevo editado, hay que borrar las relaciones PersonaFirma
            // pero solo si no tiene PersonaArticulo relacionado (significara que esa firma est actualmente 
            // siendo usada en un artculo, por lo tanto no de debe borrar)
            boolean firmaEnEditado = false;

            //primero revisar si la firma que existia antes de la persona, existe en el nuevo editado
            for (PersonaFirma perFirma : persona.getPersonaFirmasCollection()) {
                if (StringUtils.equalsIgnoreCase(perFirmaAntiguo.getFirma().getNombre(),
                        perFirma.getFirma().getNombre())) {
                    firmaEnEditado = true;
                    break;
                }
            }
            if (!firmaEnEditado) {
                //si es que la firma de la persona sin editar ya no existe en la persona editada, quitar la relacin PersonaFirma

                //primero verificar que la firma no sea usada en ninguna PersonaArticulo
                if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                    Firma firmaBorrar = null;
                    if (perFirmaAntiguo.getFirma().getPersonasFirmaCollection().size() == 1) {
                        //si la firma a borrar esta asignada a solo una persona (que sera la persona actual, variable: persona),
                        // colocarla a la variable para borrarla
                        //Siempre las firmas van a estar asignadas al menos a una persona, caso contrario deben ser borradas
                        //Las firmas de personas desconocidas estn ligadas a una persona: la persona con id=0
                        firmaBorrar = perFirmaAntiguo.getFirma();
                    }
                    //borrar la relacin PersonaFirma
                    em.remove(perFirmaAntiguo);
                    if (firmaBorrar != null) {
                        //borrar la firma solo si estaba asignada a una sola persona
                        firmaBorrar.getPersonasFirmaCollection().clear();
                        em.remove(firmaBorrar);
                    }
                }
            }
            /*
            if (!persona.getPersonaFirmasCollection().contains(perFirmaAntiguo)) {
            if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                em.remove(em);
            }
            }*/
        }
        guardarPersonaFirma(em, persona);

        em.merge(persona);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:op.users.PnlUser.java

private CollapsiblePane createCP4(final Groups group) {
    final String key = group.getGID() + ".xgroups";
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        cpMap.get(key).setSlidingDirection(SwingConstants.SOUTH);

        cpMap.get(key).setBackground(bg);
        cpMap.get(key).setForeground(fg);

        cpMap.get(key).addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
            @Override//  w w w  . j ava 2s .  c  o m
            public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
                if (!contentMap.containsKey(key)) {
                    contentMap.put(key, createContentPanel4(group));
                }
                cpMap.get(key).setContentPane(contentMap.get(key));
            }
        });
        cpMap.get(key).setHorizontalAlignment(SwingConstants.LEADING);
        cpMap.get(key).setOpaque(false);
        try {
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }

    }
    final CollapsiblePane cp = cpMap.get(key);

    DefaultCPTitle cpTitle = new DefaultCPTitle("<html><font size=+1>" + group.getGID().toUpperCase()
            + (group.isQualified() ? ", " + SYSTools.xx("opde.users.qualifiedGroup") : "") + "</font></html>",
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        cp.setCollapsed(!cp.isCollapsed());
                    } catch (PropertyVetoException pve) {
                        // BAH!
                    }
                }
            });

    /***
     *          _      _      _
     *       __| | ___| | ___| |_ ___    __ _ _ __ ___  _   _ _ __
     *      / _` |/ _ \ |/ _ \ __/ _ \  / _` | '__/ _ \| | | | '_ \
     *     | (_| |  __/ |  __/ ||  __/ | (_| | | | (_) | |_| | |_) |
     *      \__,_|\___|_|\___|\__\___|  \__, |_|  \___/ \__,_| .__/
     *                                  |___/                |_|
     */
    final JButton btnDeleteGroup = new JButton(SYSConst.icon22delete);
    btnDeleteGroup.setPressedIcon(SYSConst.icon22deletePressed);
    btnDeleteGroup.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnDeleteGroup.setContentAreaFilled(false);
    btnDeleteGroup.setBorder(null);
    btnDeleteGroup.setToolTipText(SYSTools.xx("opde.users.btnDeleteGroup"));
    btnDeleteGroup.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>" + group.getGID() + "</i><br/>"
                    + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o.equals(JOptionPane.YES_OPTION)) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    Groups myGroup = em.merge(group);
                                    em.remove(myGroup);
                                    em.getTransaction().commit();
                                    lstGroups.remove(group);
                                    cpMap.remove(key);
                                    buildPanel();
                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                            }
                        }
                    });

        }

    });
    btnDeleteGroup.setEnabled(!group.isSystem());
    cpTitle.getRight().add(btnDeleteGroup);

    cp.setTitleLabelComponent(cpTitle.getMain());

    if (!cp.isCollapsed()) {
        if (!contentMap.containsKey(key)) {
            contentMap.put(key, createContentPanel4(group));
        }
        cp.setContentPane(contentMap.get(key));
    }

    return cp;
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public User removeUser(User user) {
    User currentUser = getSessionUser();
    if (currentUser.getAdmin()) {
        EntityManager entityManager = getSessionEntityManager();
        synchronized (entityManager) {
            entityManager.getTransaction().begin();
            try {
                user = entityManager.merge(user);
                user.getDevices().clear();
                entityManager.remove(user);
                entityManager.getTransaction().commit();
                return user;
            } catch (RuntimeException e) {
                entityManager.getTransaction().rollback();
                throw e;
            }/* w w w  .  j av a  2  s . c o m*/
        }
    } else {
        throw new SecurityException();
    }
}

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

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

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);/*  w  ww .  ja v  a  2s  .co  m*/
    uddiEntity.setModifiedIncludingChildren(now);

    uddiEntity.setNodeId(nodeId);

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

    List<org.apache.juddi.model.BusinessService> serviceList = uddiEntity.getBusinessServices();
    for (org.apache.juddi.model.BusinessService service : serviceList)
        setOperationalInfo(em, service, publisher, true);

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

}

From source file:server.Folder.java

/**
 * Set the Metadata on this item. Tries to parse the submitted string
 * and throws an exception if it is not valid XML.<br/>
 * Note: this parses the meta-xml into metasets and stores them as such.
 * This method will unlink existing metasets if they are missing from the metadata,
 * that is, you cannot submit partial metadata to setMetadata. You must set <em>all</em>
 * metadata if you use this method. (see addMetaset to add an individual metaset) 
 * @param metadata the custom metadata/*from w  w w.  j  av a2  s .  c o  m*/
 * @param writePolicy the WritePolicy - how to treat existing metasets.
 */
public void setMetadata(String metadata, WritePolicy writePolicy) {
    EntityManager em = HibernateSession.getLocalEntityManager();
    if (metadata == null || metadata.trim().length() == 0) {
        this.metadata = "<meta/>";
        for (FolderMetaset fm : getFolderMetasets()) {
            em.remove(fm);
        }
    } else {
        MetasetService metasetService = new MetasetService();
        Document doc = ParamParser.parseXmlToDocument(metadata, "error.param.metadata");
        List<Node> sets = doc.selectNodes("//metaset");
        if (sets.size() == 0) {
            this.metadata = metadata;
            if (folderMetasets.size() > 0) {
                // delete obsolete metasets:
                for (Metaset m : fetchMetasets()) {
                    new MetasetService().unlinkMetaset(this, m);
                }
            }
            return;
        }

        Set<MetasetType> currentMetasetMap = new HashSet<MetasetType>();
        for (Metaset metaset : fetchMetasets()) {
            // create a set of the currently existing metasets.
            currentMetasetMap.add(metaset.getType());
        }

        for (Node metasetNode : sets) {
            String content = metasetNode.detach().asXML();
            String metasetTypeName = metasetNode.selectSingleNode("@type").getText();
            log.debug("metasetType: " + metasetTypeName);
            MetasetTypeDAO mtDao = daoFactory.getMetasetTypeDAO(em);
            MetasetType metasetType = mtDao.findByName(metasetTypeName);
            if (metasetType == null) {
                throw new CinnamonException("error.unknown.metasetType", metasetTypeName);
            }
            metasetService.createOrUpdateMetaset(this, metasetType, content, writePolicy);
            currentMetasetMap.remove(metasetType);
        }
        for (MetasetType metasetType : currentMetasetMap) {
            // any metaset that was not found in the metadata parameter will be deleted.                    
            metasetService.unlinkMetaset(this, this.fetchMetaset(metasetType.getName())); // somewhat convoluted.
        }
    }
    // remove legacy metadata
    this.metadata = "<meta />";
}