Example usage for javax.persistence EntityManager getCriteriaBuilder

List of usage examples for javax.persistence EntityManager getCriteriaBuilder

Introduction

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

Prototype

public CriteriaBuilder getCriteriaBuilder();

Source Link

Document

Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.

Usage

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getOrgMemberships(java.lang.String)
 *//*from   w  ww .jav  a 2  s .c  o m*/
@Override
public Set<RoleMembershipBean> getOrgMemberships(String organizationId) throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("organizationId"), organizationId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getUserMemberships(java.lang.String, java.lang.String)
 *//* ww w. ja  v a2 s .  c o  m*/
@Override
public Set<RoleMembershipBean> getUserMemberships(String userId, String organizationId)
        throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId),
                builder.equal(from.get("organizationId"), organizationId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getPermissions(java.lang.String)
 *///from w  w w .j  a  v a  2  s .com
@Override
public Set<PermissionBean> getPermissions(String userId) throws StorageException {
    Set<PermissionBean> permissions = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        typedQuery.setMaxResults(500);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        for (RoleMembershipBean membership : resultList) {
            RoleBean role = getRoleInternal(membership.getRoleId());
            String qualifier = membership.getOrganizationId();
            for (PermissionType permission : role.getPermissions()) {
                PermissionBean p = new PermissionBean();
                p.setName(permission);
                p.setOrganizationId(qualifier);
                permissions.add(p);
            }
        }
        return permissions;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * Acquire a List of records in pending ("Submitted") state, to be approved
 * for indexing and searching./*  w w  w . j  av a  2 s  .c om*/
 *
 * JSON response is of the form:
 *
 * {"records":[{"code_id":n, ...} ],
 *  "start":0, "rows":20, "total":100}
 *
 * Where records is an array of DOECodeMetadata JSON, start is the beginning
 * row number, rows is the number requested (or total if less available),
 * and total is the total number of rows matching the filter.
 *
 * Return Codes:
 * 200 - OK, JSON is returned as above
 * 401 - Unauthorized, login is required
 * 403 - Forbidden, insufficient privileges (role required)
 * 500 - unexpected error
 *
 * @param start the starting row number (from 0)
 * @param rows number of rows desired (0 is unlimited)
 * @param siteCode (optional) a SITE OWNERSHIP CODE to filter by site
 * @param state the WORKFLOW STATE if desired (default Submitted and Announced). One of
 * Approved, Saved, Submitted, or Announced, if supplied.
 * @return JSON of a records response
 */
@GET
@Path("/projects/pending")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response listProjectsPending(@QueryParam("start") int start, @QueryParam("rows") int rows,
        @QueryParam("site") String siteCode, @QueryParam("state") String state) {
    EntityManager em = DoeServletContextListener.createEntityManager();

    try {
        // get a JPA CriteriaBuilder instance
        CriteriaBuilder cb = em.getCriteriaBuilder();
        // create a CriteriaQuery for the COUNT
        CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
        Root<DOECodeMetadata> md = countQuery.from(DOECodeMetadata.class);
        countQuery.select(cb.count(md));

        Expression<String> workflowStatus = md.get("workflowStatus");
        Expression<String> siteOwnershipCode = md.get("siteOwnershipCode");

        // default requested STATE; take Submitted and Announced as the default values if not supplied
        List<DOECodeMetadata.Status> requestedStates = new ArrayList();
        String queryState = (StringUtils.isEmpty(state)) ? "" : state.toLowerCase();
        switch (queryState) {
        case "approved":
            requestedStates.add(DOECodeMetadata.Status.Approved);
            break;
        case "saved":
            requestedStates.add(DOECodeMetadata.Status.Saved);
            break;
        case "submitted":
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            break;
        case "announced":
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        default:
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        }

        Predicate statusPredicate = workflowStatus.in(requestedStates);
        ParameterExpression<String> site = cb.parameter(String.class, "site");

        if (null == siteCode) {
            countQuery.where(statusPredicate);
        } else {
            countQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }
        // query for the COUNT
        TypedQuery<Long> cq = em.createQuery(countQuery);
        cq.setParameter("status", requestedStates);
        if (null != siteCode)
            cq.setParameter("site", siteCode);

        long rowCount = cq.getSingleResult();
        // rows count should be less than 100 for pagination; 0 is a special case
        rows = (rows > 100) ? 100 : rows;

        // create a CriteriaQuery for the ROWS
        CriteriaQuery<DOECodeMetadata> rowQuery = cb.createQuery(DOECodeMetadata.class);
        rowQuery.select(md);

        if (null == siteCode) {
            rowQuery.where(statusPredicate);
        } else {
            rowQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }

        TypedQuery<DOECodeMetadata> rq = em.createQuery(rowQuery);
        rq.setParameter("status", requestedStates);
        if (null != siteCode)
            rq.setParameter("site", siteCode);
        rq.setFirstResult(start);
        if (0 != rows)
            rq.setMaxResults(rows);

        RecordsList records = new RecordsList(rq.getResultList());
        records.setTotal(rowCount);
        records.setStart(start);

        return Response.ok().entity(mapper.valueToTree(records).toString()).build();
    } finally {
        em.close();
    }
}