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.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java

/**
 * Before test.// ww  w.ja  va 2  s .  c  o  m
 *
 * @throws Exception the exception
 */
@Before
public void beforeTest() throws Exception {
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction et = em.getTransaction();
        et.begin();
        Query query = em.createQuery(new StringBuilder().append("SELECT x FROM news x").toString());
        List<News> newsList = query.getResultList();
        for (News news : newsList) {
            em.remove(news);
        }

        query = em.createQuery(new StringBuilder().append("SELECT x FROM category x").toString());
        List<NewsCategory> catList = query.getResultList();
        for (NewsCategory temp : catList) {
            em.remove(temp);
        }

        query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x").toString());
        List<NewsMetaCategory> metaList = query.getResultList();
        for (NewsMetaCategory temp : metaList) {
            em.remove(temp);
        }
        et.commit();
    } finally {
        em.close();
    }

}

From source file:elaborate.editor.publish.PublishTask.java

private ExportedEntryData exportEntryData(ProjectEntry projectEntry, int entryNum,
        List<String> projectEntryMetadataFields, Map<String, String> typographicalAnnotationMap) {
    // String entryFilename = entryFilename(entryNum);
    String entryFilename = projectEntry.getId() + ".json";
    File json = new File(jsonDir, entryFilename);
    EntityManager entityManager = HibernateUtil.getEntityManager();
    entityManager.merge(projectEntry);//from   w  w w  .j ava  2s .c  o  m
    Map<String, Object> entryData = getProjectEntryData(projectEntry, projectEntryMetadataFields,
            typographicalAnnotationMap);
    Multimap<String, AnnotationIndexData> annotationDataMap = (Multimap<String, AnnotationIndexData>) entryData
            .remove("annotationDataMap");
    entityManager.close();
    exportJson(json, entryData);

    List<String> thumbnailUrls = Lists.newArrayList();
    for (Map<String, String> map : (List<Map<String, String>>) entryData.get("facsimiles")) {
        thumbnailUrls.add(map.get("thumbnail"));
    }

    ExportedEntryData exportedEntryData = new ExportedEntryData();
    exportedEntryData.thumbnailUrls = thumbnailUrls;
    exportedEntryData.annotationDataMap = annotationDataMap;
    return exportedEntryData;
}

From source file:op.care.med.inventory.DlgCloseStock.java

private void initDialog() {
    String text = SYSTools.xx("nursingrecords.prescription.dlgCloseStock.youWantToClose1a") + medStock.getID()
            + SYSTools.xx("nursingrecords.prescription.dlgCloseStock.youWantToClose1b");
    text += "<br/>" + MedStockTools.getTextASHTML(medStock) + "</br>";
    text += "<br/>" + SYSTools.xx("nursingrecords.prescription.dlgCloseStock.chooseAReason") + ":";
    txtInfo.setContentType("text/html");
    txtInfo.setText(SYSTools.toHTML(SYSConst.html_div(text)));

    EntityManager em = OPDE.createEM();
    Query query = em.createQuery(" " + " SELECT b FROM MedStock b "
            + " WHERE b.inventory = :inventory AND b.out = :out AND b.opened = :opened "
            + " ORDER BY b.in, b.id ");

    query.setParameter("inventory", medStock.getInventory());
    query.setParameter("out", SYSConst.DATE_UNTIL_FURTHER_NOTICE);
    query.setParameter("opened", SYSConst.DATE_UNTIL_FURTHER_NOTICE);
    DefaultComboBoxModel dcbm = new DefaultComboBoxModel(query.getResultList().toArray());
    dcbm.insertElementAt(SYSTools.xx("misc.msg.none"), 0);
    cmbBestID.setModel(dcbm);//  w  w w.j a  va  2  s.  c  om
    cmbBestID.setRenderer(new ListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList jList, Object o, int i, boolean b, boolean b1) {
            String text = o instanceof MedStock ? ((MedStock) o).getID().toString() : o.toString();
            return new JLabel(text);
        }
    });
    em.close();

    int index = Math.min(2, cmbBestID.getItemCount());
    cmbBestID.setSelectedIndex(index - 1);

    lblEinheiten.setText(SYSConst.UNITS[medStock.getTradeForm().getDosageForm().getPackUnit()] + " "
            + SYSTools.xx("misc.msg.usedup"));
    txtLetzte.setText("");
    txtLetzte.setEnabled(false);
    // Das mit dem Vorabstellen nur bei Formen, die auf Stck basieren also APV = 1
    rbStellen.setEnabled(medStock.getTradeForm().getDosageForm().getUPRState() == DosageFormTools.STATE_UPR1);
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@PUT
@Path("{username}.json")
@RestQuery(name = "roleupdate", description = "Updates a user's roles", returnDescription = "No content", restParameters = @RestParameter(name = "roles", type = TEXT, isRequired = true, description = "The user roles as a json array"), pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = {
        @RestResponse(responseCode = SC_NO_CONTENT, description = "The user roles have been updated.") })
public Response updateUserFromJson(@PathParam("username") String username, @FormParam("roles") String roles) {
    JSONArray rolesArray = (JSONArray) JSONValue.parse(roles);
    EntityManager em = null;
    EntityTransaction tx = null;//from   w  w w  . j  ava2s.c om
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Find the existing user
        Query q = em.createNamedQuery("user");
        q.setParameter("u", username);
        q.setParameter("o", securityService.getOrganization().getId());
        JpaUser jpaUser = null;
        try {
            jpaUser = (JpaUser) q.getSingleResult();
            jpaUser.roles.clear();
            for (Object role : rolesArray) {
                jpaUser.roles.add((String) role);
            }
            em.merge(jpaUser);
        } catch (NoResultException e) {
            return null; // this will be translated into a 404
        }
        tx.commit();
        return Response.noContent().build();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:BO.UserHandler.java

public boolean respondFriendRequest(VUser user) {
    EntityManager em;

    EntityManagerFactory emf;// w  ww.  jav a  2  s.co m
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        System.out.println("Receiving friend: " + user.getEmail());
        System.out.println("Sending friend: " + user.getFriendToAdd());

        Friendship f = (Friendship) em
                .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 "
                        + "AND f.sendingFriend.email LIKE :email2")
                .setParameter("email1", user.getEmail()).setParameter("email2", user.getFriendToAdd())
                .getSingleResult();
        f.setDidRespond(true);
        f.setDidAccept(user.isDidAccept());
        em.persist(f);
        em.flush();
        em.getTransaction().commit();
        return true;
    } catch (Exception e) {
        System.out.println(e);
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:edu.kit.dama.rest.sharing.services.impl.SharingRestServiceImpl.java

@Override
public IEntityWrapper<? extends IDefaultGrant> updateGrant(Long pId, String pGroupId, String pRole,
        HttpContext hc) {/*from  www.j a  v a  2 s .c o m*/
    IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(pGroupId));
    //Hack using EM directly...other way?
    EntityManager em = PU.entityManager();
    try {
        LOGGER.debug("Finding grant for id " + pId);
        Grant grant = FindUtil.findGrant(em, pId);
        LOGGER.debug("Updating grant for id " + pId);
        Role newRole = Role.valueOf(pRole);
        ResourceServiceLocal.getSingleton().changeGrant(
                grant.getGrants().getResource().getSecurableResourceId(),
                new UserId(grant.getGrantee().getUserId()), newRole, ctx);
        grant.setGrantedRole(newRole);
        return new GrantWrapper(grant);
    } catch (UnauthorizedAccessAttemptException ex) {
        LOGGER.error("Failed to update grant with id " + pId, ex);
        throw new WebApplicationException(401);
    } catch (EntityNotFoundException ex) {
        LOGGER.error("EntityNotFoundException caught while obtaining Grant for id " + pId
                + ". Probably, there is no grant for this id.", ex);
        throw new WebApplicationException(404);
    } finally {
        em.close();
    }
}

From source file:org.noorganization.instalist.server.api.CategoriesResource.java

/**
 * Get a list of categories./*from  w  ww  .ja  v a 2s. c om*/
 *
 * @param _groupId The id of the group.
 * @param _categoryUUID The uuid of the category to fetch.
 */
@GET
@TokenSecured
@Path("{categoryuuid}")
@Produces({ "application/json" })
public Response getCategory(@PathParam("groupid") int _groupId, @PathParam("categoryuuid") String _categoryUUID)
        throws Exception {
    UUID categoryUUID;
    try {
        categoryUUID = UUID.fromString(_categoryUUID);
    } catch (IllegalArgumentException e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    TypedQuery<Category> categoriesQuery = manager.createQuery(
            "select c from Category c " + "where c.group = :groupid and c.UUID = :uuid", Category.class);
    categoriesQuery.setParameter("groupid", group);
    categoriesQuery.setParameter("uuid", categoryUUID);
    List<Category> categories = categoriesQuery.getResultList();
    if (categories.size() != 1) {
        TypedQuery<DeletedObject> deletedCategoriesQuery = manager
                .createQuery("select do " + "from DeletedObject do where do.group = :groupid and "
                        + "do.type = :type and do.UUID = :uuid", DeletedObject.class);
        deletedCategoriesQuery.setParameter("groupid", group);
        deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY);
        deletedCategoriesQuery.setParameter("uuid", categoryUUID);
        List<DeletedObject> deletedCategories = deletedCategoriesQuery.getResultList();
        manager.close();
        if (deletedCategories.size() == 1) {
            CategoryInfo catInfo = new CategoryInfo();
            catInfo.setDeleted(true);
            catInfo.setLastChanged(Date.from(deletedCategories.get(0).getUpdated()));
            catInfo.setUUID(categoryUUID);
            return ResponseFactory.generateGone(catInfo);
        } else {
            return ResponseFactory.generateNotFound(new Error().withMessage("Category was not" + " found."));
        }
    }
    manager.close();
    CategoryInfo catInfo = new CategoryInfo();
    catInfo.setDeleted(false);
    catInfo.setLastChanged(Date.from(categories.get(0).getUpdated()));
    catInfo.setName(categories.get(0).getName());
    catInfo.setUUID(categoryUUID);

    return ResponseFactory.generateOK(catInfo);
}

From source file:com.impetus.client.couchdb.crud.CouchDBClientTest.java

@Test
@PerfTest(invocations = 10)/*ww w.  j a v  a2s  .c  o  m*/
public void testCRUDWithBatch() {
    Map<String, String> batchProperty = new HashMap<String, String>(1);
    batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, "5");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(_PU, batchProperty);
    EntityManager em = emf.createEntityManager();
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    CouchDBClient client = (CouchDBClient) clients.get(_PU);
    Assert.assertEquals(5, ((Batcher) client).getBatchSize());

    final String originalName = "vivek";

    for (int i = 0; i < 9; i++) {
        PersonCouchDB object = new PersonCouchDB();
        object.setAge(32);
        object.setPersonId(ROW_KEY + i);
        object.setPersonName(originalName);
        em.persist(object);

        if (i >= 5) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNull(result);
        } else if (i > 0 && i % 4 == 0) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNotNull(result);
            Assert.assertEquals(result.getPersonId(), object.getPersonId());
            Assert.assertEquals(result.getAge(), object.getAge());
            Assert.assertEquals(result.getPersonName(), object.getPersonName());
        }
    }
    em.flush();
    em.clear();
    em.close();
    em = null;
}

From source file:info.dolezel.jarss.rest.v1.ws.UnreadNotificationEndpoint.java

@OnWebSocketMessage
public void onMessage(Session session, String text) {
    EntityManager em = null;
    EntityTransaction tx = null;/*w w  w .jav  a  2  s  .co m*/
    try {
        JsonReader reader;
        JsonObject object;
        Token token;

        em = HibernateUtil.getEntityManager();
        tx = em.getTransaction();

        tx.begin();

        reader = Json.createReader(new StringReader(text));
        object = reader.readObject();

        token = Token.loadToken(em, object.getString("token"));
        if (token == null) {
            tx.rollback();

            Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.WARNING,
                    "Invalid token provided over WebSocket");
            session.close();
        } else {
            synchronized (sessions) {
                sessions.put(session, token.getUser());
            }
            synchronized (userSessions) {
                userSessions.put(token.getUser(), session);
            }
        }

        tx.commit();
    } catch (Exception ex) {
        if (tx != null)
            tx.rollback();

        Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.SEVERE,
                "Error processing incoming WebSocket message", ex);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Returns a list of all {@link org.globus.wsrf.Resource}s, which are managed by an EntityManager, corresponding to
 * the given EntityManagerFactory and/* w ww.ja  va 2  s.  c  om*/
 * which are managed by the {@code GNDMPersistentServiceHome} {@link de.zib.gndms.infra.system.GNDMSystemDirectory#getHome(Class)}    
 *
 * @param emg the factory to create the EntityManager, used for the {@code list all} query
 * @param clazz the class, whose corresponding GNDMPersistentServiceHome will be used for the query.(See {@link de.zib.gndms.infra.system.GNDMSystemDirectory#homes})
 * @param <M> the model type
 * @return  a list of all {@code Resources}, corresponding to a specific EntityManager and GNDMPersistentServiceHome.
 */
public final @NotNull <M extends GridResource> List<String> listAllResources(
        final @NotNull EntityManagerFactory emg, final @NotNull Class<M> clazz) {
    final EntityManager manager = emg.createEntityManager();
    List<String> retList = null;
    try {
        try {
            manager.getTransaction().begin();
            retList = listAllResources(getInstanceDir().getHome(clazz), manager);
            manager.getTransaction().commit();
        } finally {
            if (manager.getTransaction().isActive())
                manager.getTransaction().rollback();
        }
    } finally {
        if (manager.isOpen())
            manager.close();
    }
    return retList;
}