Example usage for javax.persistence TypedQuery setMaxResults

List of usage examples for javax.persistence TypedQuery setMaxResults

Introduction

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

Prototype

TypedQuery<X> setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.springframework.data.jpa.repository.support.SimpleJpaRepository.java

/**
 * Reads the given {@link TypedQuery} into a {@link Page} applying the given {@link Pageable} and
 * {@link Specification}.//  w  ww.  j  a v  a 2 s.com
 * 
 * @param query must not be {@literal null}.
 * @param spec can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return
 */
protected Page<T> readPage(TypedQuery<T> query, Pageable pageable, Specification<T> spec) {

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<T> content = total > pageable.getOffset() ? query.getResultList() : Collections.<T>emptyList();

    return new PageImpl<T>(content, pageable, total);
}

From source file:org.tightblog.service.WeblogEntryManager.java

private List<WeblogEntry> getNextPrevEntries(WeblogEntry current, boolean next) {

    if (current == null || current.getPubTime() == null) {
        return Collections.emptyList();
    }/*  w w  w.j a  v a  2 s  .  c o m*/

    TypedQuery<WeblogEntry> query;

    List<Object> params = new ArrayList<>();
    int size = 0;
    String queryString = "SELECT e FROM WeblogEntry e WHERE ";
    StringBuilder whereClause = new StringBuilder();

    params.add(size++, current.getWeblog());
    whereClause.append("e.weblog = ?").append(size);

    params.add(size++, current.getId());
    whereClause.append(" AND e.id <> ?").append(size);

    params.add(size++, WeblogEntry.PubStatus.PUBLISHED);
    whereClause.append(" AND e.status = ?").append(size);

    params.add(size++, current.getPubTime());
    if (next) {
        whereClause.append(" AND e.pubTime >= ?").append(size);
        whereClause.append(" ORDER BY e.pubTime ASC, e.id ASC");
    } else {
        whereClause.append(" AND e.pubTime <= ?").append(size);
        whereClause.append(" ORDER BY e.pubTime DESC, e.id DESC");
    }

    query = entityManager.createQuery(queryString + whereClause.toString(), WeblogEntry.class);
    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }
    query.setMaxResults(1);

    return query.getResultList();
}

From source file:org.tightblog.service.WeblogEntryManager.java

/**
 * Get WeblogEntries by offset/length as list in reverse chronological order.
 * The range offset and list arguments enable paging through query results.
 *
 * @param criteria WeblogEntrySearchCriteria object listing desired search parameters
 * @return List of WeblogEntry objects in order specified by search criteria
 *//*from www. j a  v  a 2 s .  c om*/
public List<WeblogEntry> getWeblogEntries(WeblogEntrySearchCriteria criteria) {
    QueryData qd = createEntryQueryString(criteria);

    TypedQuery<WeblogEntry> query = entityManager.createQuery(qd.queryString, WeblogEntry.class);
    for (int i = 0; i < qd.params.size(); i++) {
        query.setParameter(i + 1, qd.params.get(i));
    }

    if (criteria.getOffset() != 0) {
        query.setFirstResult(criteria.getOffset());
    }
    if (criteria.getMaxResults() != -1) {
        query.setMaxResults(criteria.getMaxResults());
    }

    List<WeblogEntry> results = query.getResultList();

    if (criteria.isCalculatePermalinks()) {
        results = results.stream().peek(we -> we.setPermalink(urlService.getWeblogEntryURL(we)))
                .collect(Collectors.toList());
    }

    return results;
}

From source file:org.tightblog.service.WeblogEntryManager.java

/**
 * Generic comments query method./*from  w  w  w . jav a  2 s. c o m*/
 *
 * @param csc CommentSearchCriteria object with fields indicating search criteria
 * @return list of comments fitting search criteria
 */
public List<WeblogEntryComment> getComments(CommentSearchCriteria csc) {
    QueryData cqd = createCommentQueryString(csc);

    TypedQuery<WeblogEntryComment> query = entityManager.createQuery(cqd.queryString, WeblogEntryComment.class);
    if (csc.getOffset() != 0) {
        query.setFirstResult(csc.getOffset());
    }
    if (csc.getMaxResults() != -1) {
        query.setMaxResults(csc.getMaxResults());
    }
    for (int i = 0; i < cqd.params.size(); i++) {
        query.setParameter(i + 1, cqd.params.get(i));
    }
    return query.getResultList();
}

From source file:org.tightblog.service.WeblogManager.java

/**
 * Get list of WeblogEntryTagAggregate objects for the tags comprising a weblog.
 *
 * @param weblog    Weblog or null to get for all weblogs.
 * @param sortBy     Sort by either 'name' or 'count' (null for name)
 * @param startsWith Prefix for tags to be returned (null or a string of length > 0)
 * @param offset     0-based index into returns
 * @param limit      Max objects to return (or -1 for no limit)
 * @return List of tags matching the criteria.
 *///  w w  w.  j  av a2s  .com
public List<WeblogEntryTagAggregate> getTags(Weblog weblog, String sortBy, String startsWith, int offset,
        int limit) {
    boolean sortByName = !"count".equals(sortBy);

    List<Object> params = new ArrayList<>();
    int size = 0;

    StringBuilder queryString = new StringBuilder();
    queryString.append("SELECT wtag.name, COUNT(wtag), MIN(we.pubTime), MAX(we.pubTime) "
            + "FROM WeblogEntryTag wtag, WeblogEntry we WHERE wtag.weblogEntry.id = we.id");

    if (weblog != null) {
        params.add(size++, weblog.getId());
        queryString.append(" AND wtag.weblog.id = ?").append(size);
    }

    if (startsWith != null && startsWith.length() > 0) {
        params.add(size++, startsWith + '%');
        queryString.append(" AND wtag.name LIKE ?").append(size);
    }

    if (sortByName) {
        sortBy = "wtag.name";
    } else {
        sortBy = "COUNT(wtag) DESC";
    }

    queryString.append(" GROUP BY wtag.name ORDER BY ").append(sortBy);

    TypedQuery<WeblogEntryTagAggregate> query = entityManager.createQuery(queryString.toString(),
            WeblogEntryTagAggregate.class);

    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (limit != -1) {
        query.setMaxResults(limit);
    }
    List queryResults = query.getResultList();

    List<WeblogEntryTagAggregate> results = new ArrayList<>();
    if (queryResults != null) {
        for (Object obj : queryResults) {
            Object[] row = (Object[]) obj;
            WeblogEntryTagAggregate ce = new WeblogEntryTagAggregate();
            ce.setName((String) row[0]);
            // The JPA query retrieves SUM(w.total) always as long
            ce.setTotal(((Long) row[1]).intValue());
            if (weblog != null) {
                ce.setFirstEntry(((Instant) row[2]).atZone(weblog.getZoneId()).toLocalDate());
                ce.setLastEntry(((Instant) row[3]).atZone(weblog.getZoneId()).toLocalDate());
            }
            results.add(ce);
        }
    }

    if (sortByName) {
        results.sort(WeblogEntryTagAggregate.NAME_COMPARATOR);
    } else {
        results.sort(WeblogEntryTagAggregate.COUNT_COMPARATOR);
    }

    return results;
}

From source file:otn.mobile.bl.TrackServicesHandler.java

public OtnServiceGetTracksResponse getTracks(OtnServiceGetTracksRequest request) {

    //*********************** Variables ***************************
    OtnServiceGetTracksResponse response = new OtnServiceGetTracksResponse();

    User users;//  w w w. jav a  2 s .c  om

    Apps app;

    TypedQuery query;

    List<Track> tracksparamsList;

    ArrayList<OtnServicesMyTracksListResponse> myTracksList = new ArrayList<OtnServicesMyTracksListResponse>();

    ArrayList<OtnServiceGetTracksListResponse> trackList = null;

    int maxResults = 100;

    //************************* Action ****************************
    System.out.println("------------Start---------------");

    //        if (em.getTransaction().isActive()) {
    //            System.out.println("****************is active**************");
    //            em.getTransaction().rollback();
    //        }
    try {
        //**********************find user*****************************

        users = em.find(User.class, request.getUserId());

        if (users == null) {
            response.setMessage("user does not exist");
            response.setResponseCode(1);
            return response;
        }

        app = em.find(Apps.class, request.getAppId());

        if (app == null) {

            response.setMessage("application does not exist");
            response.setResponseCode(1);
            return response;
        }

        if ((request.getFromLat() != 0 && request.getFromLon() != 0)
                || (request.getToLat() != 0 && request.getToLon() != 0)) {
            List<OtnServiceGeometryPoints> startPointsList = new ArrayList<OtnServiceGeometryPoints>();
            OtnServiceGeometryPoints startPoints = new OtnServiceGeometryPoints();
            startPoints.setLatitude(request.getFromLat());
            startPoints.setLongitude(request.getFromLon());
            startPointsList.add(startPoints);

            List<OtnServiceGeometryPoints> toPointsList = new ArrayList<OtnServiceGeometryPoints>();
            OtnServiceGeometryPoints toPoints = new OtnServiceGeometryPoints();
            toPoints.setLatitude(request.getToLat());
            toPoints.setLongitude(request.getToLon());
            toPointsList.add(toPoints);

            double radius;
            if (request.getRadius() == 0) {

                radius = 500;

            } else {
                radius = request.getRadius();
            }

            trackList = getSpatialResults(startPointsList, toPointsList, radius, request, app, users);

            response.setTrackList(trackList);

        } /* isPublic=null, isMine=null - just public tracks (without my tracks)*/ else if (request
                .isIsPublic() == null && request.isIsMine() == null) {

            //***************find public tracks****************************
            System.out.println("find public tracks");
            query = (TypedQuery) em.createQuery(
                    "SELECT t FROM Track t WHERE t.isPublic = true and t.appId = :appId order by t.creationDate desc ");
            query.setParameter("appId", app);
            query.setMaxResults(maxResults); //limit results
            //we use list to avoid "not found" exception
            tracksparamsList = query.getResultList();

            //if we found no results, no public tracks available
            //so return error message
            if (tracksparamsList.isEmpty()) {
                response.setMessage("no public tracks for this app");
                response.setResponseCode(1);
                return response;

            } else {
                response.setMessage("succsfull loading");
                response.setResponseCode(0);
                trackList = new ArrayList<OtnServiceGetTracksListResponse>();
                for (Track track : tracksparamsList) {

                    String geomPoints = getGeometryPoints(track.getTrackId());

                    if (geomPoints == null) {
                        geomPoints = "";
                    }

                    trackList.add(new OtnServiceGetTracksListResponse(track.getName(), track.getTrackId(),
                            track.getUserId().getUserId(), track.getDescription(), track.getPicture(),
                            track.getDistance(), track.getDuration(), track.getSpeed(), track.getElevation(),
                            track.getTransportTypeId().getName(), track.getStartAddress(),
                            track.getEndAddress(), track.getIsPublic(), geomPoints));

                }
                response.setTrackList(trackList);

            }
        } /* isPublic!=null and isPublic=true, isMine=null - just public tracks (without my tracks)*/ else if (!(request
                .isIsPublic() == null) && request.isIsPublic() && request.isIsMine() == null) {

            //***************find public tracks****************************
            System.out.println("find public tracks");
            query = (TypedQuery) em.createQuery(
                    "SELECT t FROM Track t WHERE t.isPublic = true and t.appId = :appId order by t.creationDate desc");
            query.setParameter("appId", app);
            //we use list to avoid "not found" exception
            tracksparamsList = query.getResultList();
            query.setMaxResults(maxResults); //limit results

            //if we found no results, no public tracks available
            //so return error message
            if (tracksparamsList.isEmpty()) {
                response.setMessage("no public tracks for this app");
                response.setResponseCode(1);
                return response;

            } else {
                response.setMessage("succsfull loading");
                response.setResponseCode(0);
                trackList = new ArrayList<OtnServiceGetTracksListResponse>();
                for (Track track : tracksparamsList) {

                    String geomPoints = getGeometryPoints(track.getTrackId());

                    if (geomPoints == null) {
                        geomPoints = "";
                    }

                    trackList.add(new OtnServiceGetTracksListResponse(track.getName(), track.getTrackId(),
                            track.getUserId().getUserId(), track.getDescription(), track.getPicture(),
                            track.getDistance(), track.getDuration(), track.getSpeed(), track.getElevation(),
                            track.getTransportTypeId().getName(), track.getStartAddress(),
                            track.getEndAddress(), track.getIsPublic(), geomPoints));

                }
                response.setTrackList(trackList);

            }
        } /* just isMine=true - all my tracks (public & private) */ else if (request.isIsPublic() == null
                && !(request.isIsMine() == null) && request.isIsMine()) {

            //***************find user's tracks****************************
            System.out.println("find user's tracks");
            query = (TypedQuery) em.createQuery(
                    "SELECT t FROM Track t WHERE t.userId = :userId and t.appId = :appId order by t.creationDate desc");

            query.setParameter("userId", users);
            query.setParameter("appId", app);

            //we use list to avoid "not found" exception
            tracksparamsList = query.getResultList();

            //if we found no results, the users is not registered 
            //so return error message
            if (tracksparamsList.isEmpty()) {
                response.setMessage("no available tracks for this user");
                response.setResponseCode(1);
                return response;

            } else {

                trackList = new ArrayList<OtnServiceGetTracksListResponse>();
                for (Track track : tracksparamsList) {
                    //                    System.out.println("********************");
                    //
                    //                    System.out.println("my track name " + track.getName());
                    //                    System.out.println("my track duration " + track.getDuration());
                    //                    System.out.println("my track description " + track.getDescription());

                    String geomPoints = getGeometryPoints(track.getTrackId());

                    if (geomPoints == null) {
                        geomPoints = "";
                    }
                    //***********************add everything in subTrackList to consume JSON******************************
                    trackList.add(new OtnServiceGetTracksListResponse(track.getName(), track.getTrackId(),
                            track.getUserId().getUserId(), track.getDescription(), track.getPicture(),
                            track.getDistance(), track.getDuration(), track.getSpeed(), track.getElevation(),
                            track.getTransportTypeId().getName(), track.getStartAddress(),
                            track.getEndAddress(), track.getIsPublic(), geomPoints));
                }

                response.setTrackList(trackList);
            }
        } //end if isMine
        /* isPublic=true, isMine=false - just public tracks (without my tracks)*/ else if (request.isIsPublic()
                && !request.isIsMine()) {

            //***************find public tracks****************************
            System.out.println("find public tracks");
            query = (TypedQuery) em.createQuery(
                    "SELECT t FROM Track t WHERE t.isPublic = true and t.userId <> :userId and t.appId = :appId order by t.creationDate desc");
            query.setParameter("appId", app);
            query.setParameter("userId", users);
            query.setMaxResults(maxResults); //limit results
            //we use list to avoid "not found" exception
            tracksparamsList = query.getResultList();

            //if we found no results, no public tracks available
            //so return error message
            if (tracksparamsList.isEmpty()) {
                response.setMessage("no public tracks for this app");
                response.setResponseCode(1);
                return response;

            } else {
                response.setMessage("succsfull loading");
                response.setResponseCode(0);
                trackList = new ArrayList<OtnServiceGetTracksListResponse>();
                for (Track track : tracksparamsList) {

                    String geomPoints = getGeometryPoints(track.getTrackId());

                    if (geomPoints == null) {
                        geomPoints = "";
                    }

                    trackList.add(new OtnServiceGetTracksListResponse(track.getName(), track.getTrackId(),
                            track.getUserId().getUserId(), track.getDescription(), track.getPicture(),
                            track.getDistance(), track.getDuration(), track.getSpeed(), track.getElevation(),
                            track.getTransportTypeId().getName(), track.getStartAddress(),
                            track.getEndAddress(), track.getIsPublic(), geomPoints));

                }
                response.setTrackList(trackList);

            }
        } //end if isPublic and not mine
        /* isPublic=true, isMine=true - all public tracks*/ else if ((request.isIsPublic()
                && request.isIsMine()) || request.isIsPublic()) {

            //***************find public tracks****************************
            System.out.println("find public tracks");
            query = (TypedQuery) em.createQuery(
                    "SELECT t FROM Track t WHERE t.isPublic = true and t.appId = :appId order by t.creationDate desc");
            query.setParameter("appId", app);
            query.setMaxResults(maxResults); //limit results
            //we use list to avoid "not found" exception
            tracksparamsList = query.getResultList();

            //if we found no results, no public tracks available
            //so return error message
            if (tracksparamsList.isEmpty()) {
                response.setMessage("no public tracks for this app");
                response.setResponseCode(1);
                return response;

            } else {
                response.setMessage("succsfull loading");
                response.setResponseCode(0);
                trackList = new ArrayList<OtnServiceGetTracksListResponse>();
                for (Track track : tracksparamsList) {

                    String geomPoints = getGeometryPoints(track.getTrackId());

                    if (geomPoints == null) {
                        geomPoints = "";
                    }

                    trackList.add(new OtnServiceGetTracksListResponse(track.getName(), track.getTrackId(),
                            track.getUserId().getUserId(), track.getDescription(), track.getPicture(),
                            track.getDistance(), track.getDuration(), track.getSpeed(), track.getElevation(),
                            track.getTransportTypeId().getName(), track.getStartAddress(),
                            track.getEndAddress(), track.getIsPublic(), geomPoints));

                }
                response.setTrackList(trackList);

            }
        } //end if isPublic
        /* isPublic=false and isMine=true - all my tracks (only private) */ else if (request.isIsMine()
                && !request.isIsPublic()) {
            //***************find user's tracks****************************
            System.out.println("find user's tracks");
            query = (TypedQuery) em.createQuery(
                    "SELECT t FROM Track t WHERE t.userId = :userId  and t.isPublic = false and t.appId = :appId order by t.creationDate desc");

            query.setParameter("userId", users);
            query.setParameter("appId", app);

            //we use list to avoid "not found" exception
            tracksparamsList = query.getResultList();

            //if we found no results, the users is not registered 
            //so return error message
            if (tracksparamsList.isEmpty()) {
                response.setMessage("no available tracks for this user");
                response.setResponseCode(1);
                return response;

            } else {

                trackList = new ArrayList<OtnServiceGetTracksListResponse>();
                for (Track track : tracksparamsList) {
                    //                    System.out.println("********************");
                    //
                    //                    System.out.println("my track name " + track.getName());
                    //                    System.out.println("my track duration " + track.getDuration());
                    //                    System.out.println("my track description " + track.getDescription());

                    String geomPoints = getGeometryPoints(track.getTrackId());

                    if (geomPoints == null) {
                        geomPoints = "";
                    }
                    //***********************add everything in subTrackList to consume JSON******************************
                    trackList.add(new OtnServiceGetTracksListResponse(track.getName(), track.getTrackId(),
                            track.getUserId().getUserId(), track.getDescription(), track.getPicture(),
                            track.getDistance(), track.getDuration(), track.getSpeed(), track.getElevation(),
                            track.getTransportTypeId().getName(), track.getStartAddress(),
                            track.getEndAddress(), track.getIsPublic(), geomPoints));
                }

                response.setTrackList(trackList);
            }
        } //end if isMine

        response.setMessage("success");
        response.setResponseCode(0);

    } catch (Exception e) {
        e.printStackTrace();

        response.setMessage("failure");
        response.setResponseCode(2);
    } finally {

        return response;
    }

}

From source file:otn.mobile.bl.TrackServicesHandler.java

private ArrayList<OtnServiceGetTracksListResponse> getSpatialResults(List<OtnServiceGeometryPoints> fromPoints,
        List<OtnServiceGeometryPoints> toPoints, double radius, OtnServiceGetTracksRequest request, Apps appId,
        User userId) throws ClassNotFoundException {

    java.sql.Connection conpg = null;
    PreparedStatement stmt = null;

    //        Track track;
    ArrayList<OtnServiceGetTracksListResponse> trackList;
    TypedQuery query;
    List<Track> tracksparamsList;
    StringBuilder sb;//from  ww w . j  a v  a  2 s.c om
    int maxResults = 100;
    try {
        /*
         * Load the JDBC driver and establish a connection.
         */
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://localhost:5432/otn_web_app";
        conpg = DriverManager.getConnection(url, username, password);
        //            conpg = DriverManager.getConnection(url, "postgres", "admin");
        //            conpg = DriverManager.getConnection(url, "mobile_service", "otn_ck@n");

        //*********************Read data*****************************
        //            Point fromPoint = new Point(fromPoints.get(0).getLongitude(), fromPoints.get(0).getLatitude());
        //
        //            Point toPoint = new Point(toPoints.get(0).getLongitude(), toPoints.get(0).getLatitude());
        //            PreparedStatement stmt = conpg.prepareStatement("SELECT id,geom, start_point, end_point,track_id FROM otn_web_app.track_spatial WHERE ST_Distance_Sphere(start_point,ST_GeomFromText(?)) < ?  AND ST_Distance_Sphere(end_point, ST_GeomFromText(?)) < ?");
        //              PreparedStatement stmt = conpg.prepareStatement("SELECT id, end_point,ST_DistanceSphere(end_point, ?) FROM otn_web_app.track_spatial WHERE id > 20  ");
        //            stmt.setObject(1, new org.postgis.PGgeometry(fromPoint));
        //            stmt.setDouble(2, radius);
        //            stmt.setObject(3, new org.postgis.PGgeometry(toPoint));
        //            stmt.setDouble(4, radius);
        if (fromPoints.get(0).getLatitude() != 0 && toPoints.get(0).getLatitude() != 0) {

            stmt = conpg.prepareStatement(
                    "SELECT id,geom, start_point, end_point,track_id FROM otn_web_app.track_spatial WHERE ST_Distance_Sphere(start_point,ST_GeomFromText('POINT("
                            + fromPoints.get(0).getLongitude() + " " + fromPoints.get(0).getLatitude()
                            + ")',4326)) < " + radius
                            + " AND ST_Distance_Sphere(end_point, ST_GeomFromText('POINT("
                            + toPoints.get(0).getLongitude() + " " + toPoints.get(0).getLatitude()
                            + ")',4326)) <" + radius + " ");

        } else if (fromPoints.get(0).getLatitude() != 0 && toPoints.get(0).getLatitude() == 0) {

            stmt = conpg.prepareStatement(
                    "SELECT id,geom, start_point, end_point,track_id FROM otn_web_app.track_spatial WHERE ST_Distance_Sphere(start_point,ST_GeomFromText('POINT("
                            + fromPoints.get(0).getLongitude() + " " + fromPoints.get(0).getLatitude()
                            + ")',4326)) < " + radius + " ");

        }
        if (fromPoints.get(0).getLatitude() == 0 && toPoints.get(0).getLatitude() != 0) {

            stmt = conpg.prepareStatement(
                    "SELECT id,geom, start_point, end_point,track_id FROM otn_web_app.track_spatial WHERE ST_Distance_Sphere(end_point, ST_GeomFromText('POINT("
                            + toPoints.get(0).getLongitude() + " " + toPoints.get(0).getLatitude()
                            + ")',4326)) <" + radius + " ");

        }

        System.out.println(stmt.toString());

        String geomPoints;
        ResultSet r = stmt.executeQuery();
        //            Statement stmt = conpg.createStatement();
        //            ResultSet r = stmt.executeQuery("SELECT id, geom FROM otn_web_app.track_spatial ");
        trackList = new ArrayList<OtnServiceGetTracksListResponse>();
        while (r.next()) {
            sb = new StringBuilder();
            /*
             * Retrieve the geometry as an object then cast it to the geometry type.
             * Print things out.
             */
            int id = r.getInt(1);
            int track_id = r.getInt(5);
            PGgeometry geom = (PGgeometry) r.getObject(2);
            PGgeometry start_point = (PGgeometry) r.getObject(3);
            PGgeometry end_point = (PGgeometry) r.getObject(4);

            System.out.println("Row " + id + ":");
            System.out.println(geom.toString());
            System.out.println(start_point);
            System.out.println(end_point);

            geomPoints = geom.toString();
            //                track = em.find(Track.class, track_id);
            String queryString = "SELECT t FROM Track t WHERE t.trackId = :trackId and t.appId = :appId";

            sb.append(queryString);

            if (request.isIsPublic() == null && request.isIsMine() == null) {
                sb.append(" and t.isPublic = true");

            } else if (!(request.isIsPublic() == null) && request.isIsPublic() && request.isIsMine() == null) {
                sb.append(" and t.isPublic = true");

            } else if (request.isIsPublic() == null && !(request.isIsMine() == null) && request.isIsMine()) {
                System.out.println("is mine");
                sb.append(" and t.userId = :userId");

            } else if (request.isIsPublic() && !request.isIsMine()) {
                sb.append(" and t.isPublic = true and  t.userId <> :userId");
            } else if (request.isIsPublic() && request.isIsMine()) {
                sb.append(" and t.isPublic = true");
            } else if (request.isIsMine() && !request.isIsPublic()) {

                sb.append(" and t.userId = :userId  and t.isPublic = false");

            }

            sb.append(" order by t.creationDate desc ");

            query = em.createQuery(sb.toString(), Track.class);

            query.setParameter("trackId", track_id);
            query.setParameter("appId", appId);

            if (request.isIsMine() != null) {
                if (!(!(request.isIsPublic() == null) && request.isIsPublic() && request.isIsMine())) {
                    query.setParameter("userId", userId);
                }
            }

            if (request.isIsPublic() == null && request.isIsMine() == null) {
                query.setMaxResults(maxResults);

            } else if (!(request.isIsPublic() == null) && request.isIsPublic() && request.isIsMine() == null) {
                query.setMaxResults(maxResults);
            } else if (request.isIsPublic() && !request.isIsMine()) {
                query.setMaxResults(maxResults);
            } else if (request.isIsPublic() && request.isIsMine()) {
                query.setMaxResults(maxResults);
            }

            //                query = (TypedQuery) em.createQuery("SELECT t FROM Track t WHERE t.trackId = :trackId and t.userId <> :userId and t.appId = :appId order by t.creationDate desc");
            //                query.setParameter("trackId", track_id);
            //we use list to avoid "not found" exception
            tracksparamsList = query.getResultList();

            //if we found no results, no public tracks available
            //so return error message
            if (!tracksparamsList.isEmpty()) {

                for (Track track : tracksparamsList) {

                    trackList.add(new OtnServiceGetTracksListResponse(track.getName(), track.getTrackId(),
                            track.getUserId().getUserId(), track.getDescription(), track.getPicture(),
                            track.getDistance(), track.getDuration(), track.getSpeed(), track.getElevation(),
                            track.getTransportTypeId().getName(), track.getStartAddress(),
                            track.getEndAddress(), track.getIsPublic(), geomPoints));

                }
            }

        }
        r.close();
        //            conpg.commit();
        //            conpg.close();
        stmt.close();
        return trackList;
    } catch (SQLException ex) {
        //Logger.getLogger(InsertPointPostGis.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                conpg.close();
            }
        } catch (SQLException se) {
        } // do nothing
        try {
            if (conpg != null) {
                conpg.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } //end finally try
    }

}

From source file:pl.datamatica.traccar.api.providers.UserProvider.java

private String generateToken(String colName) {
    TypedQuery<Long> tq = em.createQuery("select x.id from User x " + "where x." + colName + " = :token",
            Long.class);
    tq.setMaxResults(1);
    while (true) {
        UUID token = UUID.randomUUID();
        tq.setParameter("token", token.toString());
        if (tq.getResultList().isEmpty())
            return token.toString();
    }/*from w w  w. j a v  a  2s. c o m*/
}