Example usage for javax.persistence TypedQuery setParameter

List of usage examples for javax.persistence TypedQuery setParameter

Introduction

In this page you can find the example usage for javax.persistence TypedQuery setParameter.

Prototype

TypedQuery<X> setParameter(int position, Object value);

Source Link

Document

Bind an argument value to a positional parameter.

Usage

From source file:org.openmeetings.app.data.conference.PollManagement.java

public boolean hasVoted(Long room_id, Long userid) {
    try {//from   ww  w  .  j  a  va2  s .c om
        log.debug(" :: hasVoted :: " + room_id + ", " + userid);
        TypedQuery<RoomPollAnswers> q = em.createQuery("SELECT rpa FROM RoomPollAnswers rpa "
                + "WHERE rpa.roomPoll.room.rooms_id = :room_id AND rpa.votedUser.user_id = :userid AND rpa.roomPoll.archived = :archived",
                RoomPollAnswers.class);
        q.setParameter("room_id", room_id);
        q.setParameter("userid", userid);
        q.setParameter("archived", false);
        q.getSingleResult();
        return true;
    } catch (NoResultException nre) {
        //expected
    } catch (Exception err) {
        log.error("[getPoll]", err);
    }
    return false;
}

From source file:org.openmeetings.app.data.user.dao.UsersDaoImpl.java

/**
 * /*from w w  w.j a  v a 2  s . c o  m*/
 * @param user_id
 * @return
 */
public Users getUser(Long user_id) {
    if (user_id != null && user_id > 0) {
        try {
            TypedQuery<Users> query = em.createQuery("select c from Users as c where c.user_id = :user_id",
                    Users.class);
            query.setParameter("user_id", user_id);

            Users users = null;
            try {
                users = query.getSingleResult();
            } catch (NoResultException ex) {
            }
            return users;
        } catch (Exception ex2) {
            log.error("getUser", ex2);
        }
    } else {
        log.info("[getUser] " + "Info: No USER_ID given");
    }
    return null;
}

From source file:edu.sabanciuniv.sentilab.sare.models.setcover.DocumentSetCover.java

@Override
public Iterable<byte[]> getDocumentIds(EntityManager em) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");

    TypedQuery<byte[]> query = em.createQuery(
            "SELECT scd.id FROM SetCoverDocument scd " + "WHERE scd.store=:sc " + "AND scd.flag=true",
            byte[].class);
    query.setParameter("sc", this);
    return query.getResultList();
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}/*from  w  ww .  j  a va 2 s.  co m*/
 */
@Override
public List<LoginHistory> getRealLoginHistory(User user, Campaign campaign) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    Date startDate = new Date(Long.parseLong(campaign.getMeta(MetaKey.CAMPAIGN_START_TIME)));
    List<Round> rounds = campaign.getSortedRoundsAsList();
    Date endDate = rounds.get(rounds.size() - 1).getEndDate();
    TypedQuery<LoginHistory> q = em.createQuery(
            "select lh from LoginHistory lh where lh.user = :user and lh.loginDate between :start and :end",
            LoginHistory.class);
    q.setParameter("user", user);
    q.setParameter("start", startDate, TemporalType.TIMESTAMP);
    q.setParameter("end", endDate, TemporalType.TIMESTAMP);
    return q.getResultList();
}

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

/**
 * Get a list of tags.//w w  w  .  j av a  2  s  .  co m
 * @param _groupId The id of the group containing the tags.
 * @param _changedSince Limits the request to elements that changed since the given date. ISO
 *                      8601 time e.g. 2016-01-19T11:54:07+0100. Optional.
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getTags(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    Instant changedSince = null;
    try {
        if (_changedSince != null)
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
    } catch (ParseException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    List<Tag> tags;
    List<DeletedObject> deletedTags;
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (changedSince != null) {
        TypedQuery<Tag> tagQuery = manager.createQuery(
                "select t from Tag t where " + "t.group = :group and t.updated > :updated", Tag.class);
        tagQuery.setParameter("group", group);
        tagQuery.setParameter("updated", changedSince);
        tags = tagQuery.getResultList();

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("updated", changedSince);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG);
        deletedTags = deletedRecipesQuery.getResultList();
    } else {
        tags = new ArrayList<Tag>(group.getTags());

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG);
        deletedTags = deletedRecipesQuery.getResultList();
    }
    manager.close();

    ArrayList<TagInfo> rtn = new ArrayList<TagInfo>(tags.size() + deletedTags.size());
    for (Tag current : tags) {
        TagInfo toAdd = new TagInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : deletedTags) {
        TagInfo toAdd = new TagInfo().withDeleted(true);
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

@Test
public void testPostTag() throws Exception {
    String url = "/groups/%d/tags";
    TagInfo newTag = new TagInfo().withUUID(mTag.getUUID()).withName("tag3");
    Instant preInsert = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request()
            .post(Entity.json(newTag));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").post(Entity.json(newTag));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newTag));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newTag));
    assertEquals(409, goneResponse.getStatus());
    mManager.refresh(mTag);//from   w w w  . ja  v a  2  s .  c  o m
    assertEquals("tag1", mTag.getName());

    newTag.setUUID(UUID.randomUUID());
    Response okResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newTag));
    assertEquals(201, okResponse.getStatus());
    TypedQuery<Tag> savedTagQuery = mManager
            .createQuery("select t from Tag t where " + "t.group = :group and t.UUID = :uuid", Tag.class);
    savedTagQuery.setParameter("group", mGroup);
    savedTagQuery.setParameter("uuid", UUID.fromString(newTag.getUUID()));
    List<Tag> savedTags = savedTagQuery.getResultList();
    assertEquals(1, savedTags.size());
    assertEquals("tag3", savedTags.get(0).getName());
    assertTrue(preInsert.isBefore(savedTags.get(0).getUpdated()));
}

From source file:eu.clarin.cmdi.virtualcollectionregistry.VirtualCollectionRegistryMaintenanceImpl.java

protected void allocatePersistentIdentifiers(EntityManager em, final Date nowDateAlloc) {
    em.getTransaction().begin();/*from  w  ww  . j a v a2s  .  com*/
    TypedQuery<VirtualCollection> q = em.createNamedQuery("VirtualCollection.findAllByStates",
            VirtualCollection.class);
    List<VirtualCollection.State> states = new LinkedList<>();
    states.add(VirtualCollection.State.PUBLIC_PENDING);
    states.add(VirtualCollection.State.PUBLIC_FROZEN_PENDING);
    q.setParameter("states", states);
    q.setParameter("date", nowDateAlloc);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    for (VirtualCollection vc : q.getResultList()) {
        allocatePersistentIdentifier(em, vc);
    }
    em.getTransaction().commit();
}

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

@Test
public void testDeleteTag() throws Exception {
    String url = "/groups/%d/tags/%s";
    Instant preDelete = mTag.getUpdated();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId(), mTag.getUUID().toString()))
            .request().delete();/*from w  w w .j  av a2s .  co  m*/
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId(), mTag.getUUID().toString())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").delete();
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId(), mNATag.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).delete();
    assertEquals(401, wrongGroupResponse.getStatus());

    Response wrongListResponse = target(String.format(url, mGroup.getId(), mNATag.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).delete();
    assertEquals(404, wrongListResponse.getStatus());

    Response okResponse = target(String.format(url, mGroup.getId(), mTag.getUUID().toString())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).delete();
    assertEquals(200, okResponse.getStatus());

    TypedQuery<Tag> savedTagQuery = mManager
            .createQuery("select t from Tag t where " + "t.group = :group and t.UUID = :uuid", Tag.class);
    savedTagQuery.setParameter("group", mGroup);
    savedTagQuery.setParameter("uuid", mTag.getUUID());
    List<Tag> savedTag = savedTagQuery.getResultList();
    assertEquals(0, savedTag.size());
    TypedQuery<DeletedObject> savedDeletedTagQuery = mManager.createQuery(
            "select do from "
                    + "DeletedObject do where do.group = :group and do.UUID = :uuid and do.type = :type",
            DeletedObject.class);
    savedDeletedTagQuery.setParameter("group", mGroup);
    savedDeletedTagQuery.setParameter("uuid", mTag.getUUID());
    savedDeletedTagQuery.setParameter("type", DeletedObject.Type.TAG);
    List<DeletedObject> savedDeletedTags = savedDeletedTagQuery.getResultList();
    assertEquals(1, savedDeletedTags.size());
    assertTrue(preDelete.isBefore(savedDeletedTags.get(0).getUpdated()));
}

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

@Test
public void testPostUnit() throws Exception {
    String url = "/groups/%d/units";
    UnitInfo newUnit = new UnitInfo().withUUID(mUnit.getUUID()).withName("unit4");
    Instant preInsert = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request()
            .post(Entity.json(newUnit));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").post(Entity.json(newUnit));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newUnit));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newUnit));
    assertEquals(409, goneResponse.getStatus());
    mManager.refresh(mUnit);/*from www  . j av  a 2  s .c o m*/
    assertEquals("unit1", mUnit.getName());

    newUnit.setUUID(UUID.randomUUID());
    Response okResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).post(Entity.json(newUnit));
    assertEquals(201, okResponse.getStatus());
    TypedQuery<Unit> savedUnitQuery = mManager
            .createQuery("select u from " + "Unit u where u.group = :group and u.UUID = :uuid", Unit.class);
    savedUnitQuery.setParameter("group", mGroup);
    savedUnitQuery.setParameter("uuid", UUID.fromString(newUnit.getUUID()));
    List<Unit> savedUnits = savedUnitQuery.getResultList();
    assertEquals(1, savedUnits.size());
    assertEquals("unit4", savedUnits.get(0).getName());
    assertTrue(preInsert.isBefore(savedUnits.get(0).getUpdated()));
}