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.medicaid.mmis.util.CodeMappingLoader.java

/**
 * Reads the code mapping xls and inserts any unmapped row to the legacy mapping table.
 * @throws InvalidFormatException if the input file is not recognized 
 *//*from  w  w w  .ja  va  2s  .  co  m*/
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException, PortalServiceException, InvalidFormatException {
    PropertyConfigurator.configure("log4j.properties");
    logger = Logger.getLogger(CodeMappingLoader.class);
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cms-data-load");
    EntityManager em = emf.createEntityManager();

    Workbook workbook = WorkbookFactory.create(new File("mapping/CodeMapping.xlsx"));
    SequenceGeneratorBean sequence = new SequenceGeneratorBean();
    sequence.setEm(em);

    try {
        em.getTransaction().begin();
        List<LegacySystemMapping> rs = em.createQuery("Select l from LegacySystemMapping l").getResultList();
        for (LegacySystemMapping mapping : rs) {
            em.remove(mapping);
        }
        importSheet(em, sequence, workbook, "ENROLLMENT_STATUS");
        importSheet(em, sequence, workbook, "RISK_LEVEL");
        importSheet(em, sequence, workbook, "SPECIALTY_CODE");
        importSheet(em, sequence, workbook, "LICENSE_TYPE");
        importSheet(em, sequence, workbook, "ISSUING_BOARD");
        importSheet(em, sequence, workbook, "PROVIDER_TYPE");
        importSheet(em, sequence, workbook, "COUNTY_CODE");
        importSheet(em, sequence, workbook, "BEN_OWNER_TYPE");
        importSheet(em, sequence, workbook, "LICENSE_STATUS");
        importSheet(em, sequence, workbook, "COS");
        em.getTransaction().commit();
    } catch (Throwable t) {
        em.getTransaction().rollback();
        logger.error("Could not complete import", t);
        throw new PortalServiceException("Error during import", t);
    }
}

From source file:ch.entwine.weblounge.bridge.oaipmh.harvester.LastHarvested.java

/**
 * Remove all URLs from the table that do not exist in <code>keepUrls</code>.
 */// w  w  w .  j  a  va  2s . com
public static void cleanup(PersistenceEnv penv, final String[] keepUrls) {
    penv.tx(new Function<EntityManager, Void>() {
        public Void apply(EntityManager em) {
            List<LastHarvested> lhs = em.createNamedQuery("findAll").getResultList();
            for (LastHarvested lh : lhs) {
                if (!ArrayUtils.contains(keepUrls, lh.getUrl())) {
                    em.remove(lh);
                }
            }
            return null;
        }
    });
}

From source file:org.opencastproject.oaipmh.harvester.LastHarvested.java

/**
 * Remove all URLs from the table that do not exist in <code>keepUrls</code>.
 *//*from w  ww  . j  ava 2  s.  c  o  m*/
public static void cleanup(PersistenceEnv penv, final String[] keepUrls) {
    penv.tx(new Function<EntityManager, Void>() {
        @Override
        public Void apply(EntityManager em) {
            List<LastHarvested> lhs = em.createNamedQuery("findAll").getResultList();
            for (LastHarvested lh : lhs) {
                if (!ArrayUtils.contains(keepUrls, lh.getUrl())) {
                    em.remove(lh);
                }
            }
            return null;
        }
    });
}

From source file:actors.SessionCleaner.java

public static boolean clean(WebSession session, boolean timedout, boolean forceCleanup) {
    if (session == null) {
        return false;
    }//from w  w  w .  j a  v  a 2 s  .c o m

    Logger.info("deleting session " + UuidUtils.normalize(session.getId()));
    List<ProgressObserverToken> poTokens = ProgressObserverToken.find.where().eq("session", session).findList();
    for (ProgressObserverToken poToken : poTokens) {
        poToken.delete();
    }

    if (session.getStatus() == SessionStatus.ALIVE || forceCleanup) {
        session.setStatus(timedout ? SessionStatus.TIMEDOUT : SessionStatus.KILLED);
        session.update();

        // if the session is not authenticated, delete all stores owned.
        if (!SessionedAction.isAuthenticated(session)) {
            EntityManager em = SareTransactionalAction.createEntityManager();
            em.getTransaction().begin();

            // delete all owned stores.
            for (String uuid : new PersistentDocumentStoreController().getAllUuids(em,
                    UuidUtils.normalize(session.getId()))) {
                Logger.info("deleting store " + uuid + " owned by " + UuidUtils.normalize(session.getId()));
                PersistentDocumentStore store = em.find(PersistentDocumentStore.class, UuidUtils.toBytes(uuid));
                if (store != null) {
                    em.remove(store);
                }
            }

            em.getTransaction().commit();
            em.close();
        }
    }

    return true;
}

From source file:entity.files.SYSFilesTools.java

public static boolean deleteFile(SYSFiles sysfile) {
    boolean success = false;
    EntityManager em = OPDE.createEM();

    try {//from w  ww  . j  a va  2s.  c o  m
        em.getTransaction().begin();
        SYSFiles mySYSFile = em.merge(sysfile);
        em.remove(mySYSFile);
        em.getTransaction().commit();
        success = true;
    } 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());
        success = false;
    } catch (Exception ex) {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        success = false;
    } finally {
        em.close();
    }

    if (success) {
        try {
            FileTransferClient ftp = getFTPClient();
            ftp.deleteFile(sysfile.getRemoteFilename());
            ftp.disconnect();
            OPDE.info("DELETING FILE FROM FTPSERVER: " + sysfile.getFilename() + " (" + sysfile.getMd5() + ")");
        } catch (Exception e) {
            OPDE.error(e);
            success = false;
        }
    }

    return success;
}

From source file:entity.files.SYSFilesTools.java

public static void detachFiles(SYSFiles[] files, SYSFilesContainer sysFilesContainer) {

    FileTransferClient ftp = getFTPClient();

    if (ftp != null) {
        EntityManager em = OPDE.createEM();
        try {/*from  ww w  .  j ava2  s.c o  m*/
            em.getTransaction().begin();

            for (SYSFiles sysfile : files) {
                SYSFilesLink link = em.merge(sysFilesContainer.detachFile(sysfile));
                em.remove(link);
            }

            em.getTransaction().commit();
        } 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 ex) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            OPDE.fatal(ex);
        } finally {
            em.close();
            try {
                ftp.disconnect();
            } catch (Exception e) {
                OPDE.error(e);
            }
        }
    }
}

From source file:uk.co.threeonefour.ifictionary.web.user.dao.JpaUserDao.java

@Transactional
@Override
public void remove(String id) {

    EntityManager em = entityManager;
    em.remove(get(id));
    em.flush();
}

From source file:models.RememberMeInfo.java

/**
 * ?<br>//from ww  w.  j  a  va  2  s.  com
 * ?? ?cookie??<br>
 * ???
 */
public static void rememberMeAutoLogin(Request request, final Response response, final Session session) {
    String path = request.path();
    // ?tell/poll??, forgetMe??
    if (StringUtils.isNotBlank(path) && (isMsgTellPollUrl(path) || path.startsWith("/forgetMe"))) {
        return;
    }

    // ?? ?cookie??
    if (!UserAuthService.isLogin(session)) {
        Cookie cookie = request.cookie(Constants.COOKIE_REMEMBER_ME);
        if (null != cookie && StringUtils.isNotBlank(cookie.value())) {
            final String cookieValue = cookie.value();

            JPAUtil.indieTransaction(new IndieTransactionCall() {

                @Override
                public void call(EntityManager em) {
                    @SuppressWarnings("unchecked")
                    List<RememberMeInfo> entityList = em.createQuery(
                            "from RememberMeInfo rm left join fetch rm.user where rm.cookieValue = :cookieValue ")
                            .setParameter("cookieValue", cookieValue).getResultList();

                    if (CollectionUtils.isNotEmpty(entityList)) {

                        RememberMeInfo entity = entityList.get(0);
                        User user = entity.user;

                        Calendar expires = Calendar.getInstance();
                        expires.add(Calendar.SECOND, -REMEMBER_ME_EXPIRES);

                        // ?
                        if (entity.beginTime.before(expires.getTime())) {

                            em.remove(entity);
                            response.discardCookie(Constants.COOKIE_REMEMBER_ME);

                        } else if (user.lastRMLoginTime != null && user.lastRMLoginTime.getTime()
                                + AUTO_LOGIN_INTERVAL * 1000 > System.currentTimeMillis()) { // ?

                            em.remove(entity);
                            response.discardCookie(Constants.COOKIE_REMEMBER_ME);

                        } else { // 
                            ObjectNodeResult loginObjectNodeResult = null;
                            try {
                                loginObjectNodeResult = User.loginByEncryptedPassword(user.getEmail(),
                                        user.getEncryptedPassword(), false, UsernameType.EMAIL);
                            } catch (Exception e) {
                                LOGGER.error("fail to loginByEncryptedPassword.", e);
                            }

                            if (null == loginObjectNodeResult || !loginObjectNodeResult.isSuccess()) {
                                em.remove(entity);
                                response.discardCookie(Constants.COOKIE_REMEMBER_ME);
                            } else {
                                User.refreshCurrentLastRMLoginTime(session);
                            }
                        }

                    } else {
                        response.discardCookie(Constants.COOKIE_REMEMBER_ME);
                    }
                }
            });
        }
    }
}

From source file:de.berlios.jhelpdesk.dao.jpa.TicketFilterDAOJpa.java

@Transactional(readOnly = false)
public void delete(final TicketFilter filter) {
    this.jpaTemplate.execute(new JpaCallback<TicketFilter>() {
        public TicketFilter doInJpa(EntityManager em) throws PersistenceException {
            em.remove(filter);
            return null;
        }//  w ww .j  av  a2 s  .  c  om
    });
}

From source file:com.romb.hashfon.helper.Helper.java

public void removeObject(EntityManager em, Object o, Long id) {
    em.getTransaction().begin();
    em.remove(o);
    em.getTransaction().commit();
}