Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

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

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

From source file:com.enioka.jqm.api.HibernateClient.java

private InputStream getJobLog(int jobId, String extension, String param) {
    // 1: retrieve node to address
    EntityManager em = null;
    Node n = null;//from www. j  a v a 2  s .c om
    try {
        em = getEm();
        History h = em.find(History.class, jobId);
        if (h != null) {
            n = h.getNode();
        } else {
            JobInstance ji = em.find(JobInstance.class, jobId);
            if (ji != null) {
                n = ji.getNode();
            } else {
                throw new NoResultException("No history or running instance for this jobId.");
            }
        }
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmInvalidRequestException("No job found with the job ID " + jobId, e);
    }

    if (n == null) {
        throw new JqmInvalidRequestException("cannot retrieve a file from a deleted node");
    }

    // 2: build URL
    URL url = null;
    try {
        url = new URL(
                getFileProtocol(em) + n.getDns() + ":" + n.getPort() + "/ws/simple/" + param + "?id=" + jobId);
        jqmlogger.trace("URL: " + url.toString());
    } catch (MalformedURLException e) {
        throw new JqmClientException("URL is not valid " + url, e);
    } finally {
        em.close();
    }

    return getFile(url.toString());
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * saves or updates a newscategory.//from   w  w  w. j av  a  2s .c o  m
 *
 * @param category the category
 * @return the category with the new id
 * @throws Exception the exception
 */
private NewsCategory saveNewsCategory(NewsCategory category) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // try loading the category for the firstspirit id
        NewsCategory cat = getNewsCategory(category.getFs_id(), category.getLanguage(), em);

        if (cat != null) {

            List<NewsMetaCategory> metaCats = category.getMetaCategories();

            // the already persistent categories
            List<NewsMetaCategory> original_metaCats = cat.getMetaCategories();

            // update existing category
            cat.setMetaCategories(new ArrayList<NewsMetaCategory>());

            for (NewsMetaCategory metaCat : metaCats) {
                metaCat = saveNewsMetaCategory(metaCat, em);
                cat.getMetaCategories().add(metaCat);

                original_metaCats.remove(metaCat);
            }
            for (NewsMetaCategory mc : original_metaCats) {
                mc.setLastmodified(category.getLastmodified());
            }
            cat.getMetaCategories().addAll(original_metaCats);

            cat.setFs_id(category.getFs_id());
            cat.setLanguage(category.getLanguage());
            cat.setName(category.getName());
            cat.setVersion(category.getVersion());
            cat.setLastmodified(category.getLastmodified());

            // update
            category = em.merge(cat);
        } else {
            updateMetaCategories(category, em);
            // save to db
            em.persist(category);
        }

        tx.commit();

        return category;

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        logger.error("", e);
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from w  ww. ja va 2  s .  c o  m
@Path("{id}/headlines")
public Response getArticleHeadlines(@Context SecurityContext context, @PathParam("id") int feedId,
        @QueryParam("skip") int skip, @QueryParam("limit") int limit) {
    EntityManager em;
    List<Object[]> articles;
    Query query;
    ArticleHeadlineData[] result;
    Feed feed;
    User user;

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();

    try {

        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!feed.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        query = em.createQuery(
                "SELECT fid, fi from FeedItemData fid LEFT OUTER JOIN fid.feedItems AS fi where fid.feedData = :fd and (fi is null or fi.feed = :feed) order by fid.date desc",
                Object[].class).setParameter("fd", feed.getData()).setParameter("feed", feed)
                .setFirstResult(skip);

        if (limit > 0)
            query.setMaxResults(limit);

        articles = query.getResultList();

        result = new ArticleHeadlineData[articles.size()];
        for (int i = 0; i < articles.size(); i++) {
            FeedItemData article = (FeedItemData) articles.get(i)[0];
            FeedItem feedItem = (FeedItem) articles.get(i)[1];

            ArticleHeadlineData data = new ArticleHeadlineData();
            String text;

            data.setPublished(article.getDate().getTime());
            data.setTitle(article.getTitle());
            data.setId(article.getId());

            text = StringUtils.html2text(article.getText());

            if (text.length() > 130)
                text = text.substring(0, 130);

            data.setExcerpt(text);
            data.setLink(article.getLink());

            if (feedItem != null) {
                data.setRead(feedItem.isRead());
                data.setStarred(feedItem.isStarred());
            }

            result[i] = data;
        }

        return Response.ok(result).build();
    } finally {
        em.close();
    }
}

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)
 *///  w w w. j  a  v a  2s  .  c om
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:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes a newsdrilldown from the db.//from   w  ww .  j  a v  a2  s .  co  m
 *
 * @param entity The newsdrilldown 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("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString());
        query.setParameter("fs_id", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            News art = (News) query.getSingleResult();
            // delete file from filesystem
            URL url = new URL(art.getUrl());
            File file = new File(webpath + url.getPath());
            if (file.exists()) {
                // Try acquiring the lock without blocking. This method returns
                // null or throws an exception if the file is already locked.
                try {
                    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
                    // Try to lock the file
                    FileLock lock = channel.tryLock();
                    // Delete the file
                    file.delete();
                    // Release the lock
                    lock.release();
                    lock.channel().close();
                } catch (OverlappingFileLockException e) {
                    logger.info("File is already locked in this thread or virtual machine");
                } catch (MalformedURLException e) {
                    logger.info("wrong url", e);
                }
            }
            // remove article from content repository

            em.remove(art);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java

@SuppressWarnings("unchecked")
public List<AchievedTrophy> getAllAchievedTropies() {
    EntityManager em = getHibernateEntityManager();
    try {/*ww  w  . j ava  2  s.c  o  m*/
        List<AchievedTrophy> achievedTrophies = em
                .createQuery("select at " + "from AchievedTrophy at " + "left join fetch at.user")
                .getResultList();
        em.close();
        return achievedTrophies;
    } catch (Exception e) {
        em.close();
        logger.error(e.getMessage());
        return new LinkedList<AchievedTrophy>();
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from  www. ja va2s .c om
public Response subscribeFeed(@Context SecurityContext context, FeedSubscriptionData data) {
    FeedCategory fc = null;
    EntityManager em;
    EntityTransaction tx;
    User user;
    FeedData feedData;
    Feed f;
    boolean createdNewFD = false;

    if (data.getUrl() == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorDescription("Feed URL missing"))
                .build();
    }

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();
    tx.begin();

    try {
        if (data.getCategoryId() != 0) {
            try {
                fc = (FeedCategory) em
                        .createQuery("select fc from FeedCategory fc where fc.id = :id", FeedCategory.class)
                        .setParameter("id", data.getCategoryId()).getSingleResult();
            } catch (NoResultException e) {
                return Response.status(Response.Status.NOT_FOUND)
                        .entity(new ErrorDescription("Feed category not found")).build();
            }

            if (!fc.getUser().equals(user)) {
                return Response.status(Response.Status.FORBIDDEN)
                        .entity(new ErrorDescription("Feed category not owned by user")).build();
            }
        }

        // Try to look up existing FeedData
        try {
            feedData = (FeedData) em.createNamedQuery("FeedData.getByUrl").setParameter("url", data.getUrl())
                    .getSingleResult();
        } catch (NoResultException e) {
            feedData = new FeedData();
            feedData.setUrl(data.getUrl());

            try {
                loadFeedDetails(feedData);
            } catch (Exception ex) {
                e.printStackTrace();
                return Response.status(Response.Status.BAD_GATEWAY)
                        .entity(new ErrorDescription("Cannot fetch the feed")).build();
            }

            em.persist(feedData);
            createdNewFD = true;
        }

        f = new Feed();
        f.setUser(user);
        f.setFeedCategory(fc);
        f.setData(feedData);
        f.setName(feedData.getTitle());

        em.persist(f);

        tx.commit();

        if (createdNewFD)
            FeedsEngine.getInstance().submitFeedRefresh(feedData);

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java

@SuppressWarnings("unchecked")
public List<AchievedTrophy> getAllAchievedTropiesForUser(Integer idUser) {
    EntityManager em = getHibernateEntityManager();
    try {//from  w w  w  .  j a v a  2s  . c o m
        List<AchievedTrophy> achievedTrophies = em.createQuery("select at " + "from AchievedTrophy at "
                + "left join fetch at.user " + "where at.user.idUser = :idUsr").setParameter("idUsr", idUser)
                .getResultList();
        em.close();
        return achievedTrophies;
    } catch (Exception e) {
        em.close();
        logger.error(e.getMessage());
        return new LinkedList<AchievedTrophy>();
    }
}

From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java

public Integer getFlagIdFromQuestionId(Integer idQuestion) {
    EntityManager em = getHibernateEntityManager();
    Integer id = null;/*  w w w.  j  a va 2 s .c o m*/
    try {
        id = (Integer) em.createNativeQuery(
                "SELECT Flag_idFlag FROM flags_flagQuestions WHERE flagQuestionList_idFlagQuestion = :qst")
                .setParameter("qst", idQuestion).getSingleResult();
        em.close();
        return id;
    } catch (Exception e) {
        em.close();
        logger.error(e.getMessage());
        return id;
    }
}

From source file:es.uvigo.ei.sing.rubioseq.gui.util.DBInitializer.java

/**
 * This method is responsible for the initializacion of the BD, that is:
 * - Creating the default RUbioSeqConfiguration.
 * - Creating the default users./* ww  w.j  a  va2 s.  c  om*/
 * - Creating a datastore pointing to "/" for the admin user.
 * 
 * This method also plays a key role in the deployment of the application 
 * since it prints the message "[DBInitializer] DB initialized." which is
 * triggered by the launch-rubioseq-gui.sh in order to know that the app. is
 * deployed and launch a browser.
 * 
 * @author hlfernandez
 */
static void initDatabase() {
    System.out.println("[DBInitializer] Initializing DB ...");

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("rubioseq-database");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        /*
         * Store Global Configuration
         */
        if (em.createQuery("SELECT u FROM RUbioSeqConfiguration u").getResultList().size() == 0) {
            RUbioSeqConfiguration config = new RUbioSeqConfiguration();
            config.setRubioseqCommand("/opt/RUbioSeq3.7/RUbioSeq.pl");
            config.setPrivateDatastoresRootDirectory("/path/to/private/datastores/root");
            config.setCreatePrivateDatastoresOnUserRegistration(false);

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(config);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Users
         */
        if (em.createQuery("SELECT u FROM User u").getResultList().size() == 0) {
            User user = new User();
            user.setUsername("rubiosequser");
            user.setPassword(DigestUtils.md5Hex("rubioseqpass"));
            user.setAdmin(false);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }

            user = new User();
            user.setUsername("admin");
            user.setPassword(DigestUtils.md5Hex("admin"));
            user.setAdmin(true);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Datastores
         */
        boolean createDefaultAdminDatastore = true;
        List<User> adminUsers = getAdminUsers(em);
        @SuppressWarnings("unchecked")
        List<DataStore> datastores = (List<DataStore>) em.createQuery("SELECT d FROM DataStore d")
                .getResultList();
        for (User adminUser : adminUsers) {
            if (datastores.size() == 0) {
                createDefaultAdminDatastore = true;
            } else {
                for (DataStore d : datastores) {
                    if (d.getUser() != null && d.getUser().equals(adminUser) && d.getPath().equals("/")) {
                        createDefaultAdminDatastore = false;
                    }
                }
            }
            if (createDefaultAdminDatastore) {
                DataStore adminDS = new DataStore();
                adminDS.setUser(adminUser);
                adminDS.setPath("/");
                adminDS.setMode(DataStoreMode.Private);
                adminDS.setType(DataStoreType.Input_Output);
                adminDS.setName(adminUser.getUsername() + "_default");

                tx = em.getTransaction();
                try {
                    tx.begin();
                    em.persist(adminDS);
                    tx.commit();
                } finally {
                    if (tx != null && tx.isActive()) {
                        tx.rollback();
                    }
                }
            }
        }
    } finally {
        em.close();
    }

    System.out.println("[DBInitializer] DB initialized.");
}