List of usage examples for javax.persistence Query setFirstResult
Query setFirstResult(int startPosition);
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}/*from ww w .ja va 2s.c o m*/ */ @SuppressWarnings("unchecked") @Override public <T extends VolumeExplorer> Image findImage(T explorer) throws PersistenceException { // If total is null we need to obtain total and partial total by type (rubricario and folio)... if (explorer.getTotal() == null) { this.updateExplorerTotals(explorer); } Image image = explorer.getImage(); StringBuilder stringBuilder = new StringBuilder(" FROM Image WHERE"); stringBuilder.append(" volNum = :volNum"); if (explorer.getVolLetExt() == null || !StringUtils.isEmpty(explorer.getVolLetExt().trim())) { stringBuilder.append(" AND volLetExt") .append(explorer.getVolLetExt() == null ? " IS NULL" : " = :volLetExt"); } if (image.getImageProgTypeNum() != null) { // folio number is provided --> the query search by this criterium if (image.getInsertNum() == null || !StringUtils.isEmpty(image.getInsertNum().trim())) { stringBuilder.append(" AND insertNum") .append(image.getInsertNum() == null ? " IS NULL" : " = :insertNum"); } if (image.getInsertLet() == null || !StringUtils.isEmpty(image.getInsertLet().trim())) { stringBuilder.append(" AND insertLet") .append(image.getInsertLet() == null ? " IS NULL" : " = :insertLet"); } if (image.getImageType() != null) { stringBuilder.append(" AND imageType = :imageType"); } stringBuilder.append(" AND imageProgTypeNum = :imageProgTypeNum"); if (image.getMissedNumbering() == null || !StringUtils.isEmpty(image.getMissedNumbering().trim())) { stringBuilder.append(" AND missedNumbering") .append(image.getMissedNumbering() == null ? " IS NULL" : " = :missedNumbering"); } if (image.getImageRectoVerso() != null) { // imageRectoVerso cannot be null in tblImages stringBuilder.append(" AND imageRectoVerso = :imageRectoVerso"); } } else if (image.getImageOrder() != null) { // folio numnber is not provided --> we first consider image order search filter stringBuilder.append(" AND imageOrder = :imageOrder"); } else if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getImageName())) { // imageOrder is not provided --> we consider imageName search filter stringBuilder.append(" AND imageName LIKE '%").append(image.getImageName().trim()).append("%'"); } else { // no search filter is provided --> we set 1 for imageOrder stringBuilder.append(" AND imageOrder = 1"); } logger.debug("FindImages from documentExplorer query: " + stringBuilder.toString()); Query query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", explorer.getVolNum()); if (!org.medici.bia.common.util.StringUtils.isNullableString(explorer.getVolLetExt())) { query.setParameter("volLetExt", explorer.getVolLetExt()); } if (image.getImageProgTypeNum() != null) { if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getInsertNum())) { query.setParameter("insertNum", image.getInsertNum().trim()); } if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getInsertLet())) { query.setParameter("insertLet", image.getInsertLet().trim()); } if (image.getImageType() != null) { query.setParameter("imageType", image.getImageType()); } query.setParameter("imageProgTypeNum", image.getImageProgTypeNum()); if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getMissedNumbering())) { query.setParameter("missedNumbering", image.getMissedNumbering()); } if (image .getImageRectoVerso() != null/* && !Image.ImageRectoVerso.N.equals(image.getImageRectoVerso())*/) { query.setParameter("imageRectoVerso", image.getImageRectoVerso()); } List<Image> result = (List<Image>) query.getResultList(); if (result.size() > 0) { return result.get(0); } return null; } if (image.getImageOrder() != null) { // imageOrder is provided query.setParameter("imageOrder", image.getImageOrder()); } // imageOrder provided or image name provided or no searching criteria is provided query.setFirstResult(0); query.setMaxResults(1); try { return (Image) query.getSingleResult(); } catch (NoResultException noResultExcepion) { } return null; }
From source file:it.drwolf.ridire.session.JobManager.java
@SuppressWarnings("unchecked") @Factory("jobCrawledResources") public List<CrawledResource> getJobCrawledResources() { String queryString = "select cr from CrawledResource cr left join cr.semanticMetadatum left join cr.functionalMetadatum where cr.job=:job"; String queryCountString = "select count(*) from CrawledResource cr where cr.job=:job"; if (this.getFilterURLValue() != null && this.getFilterURLValue().length() > 0) { queryString += " and cr.url like :url"; queryCountString += " and cr.url like :url"; }//from ww w . j a v a 2s .co m if (this.getFilterMimeTypeValue() != null && this.getFilterMimeTypeValue().length() > 0) { queryString += " and cr.contentType like :mimeType"; queryCountString += " and cr.contentType like :mimeType"; } if (this.getSemanticMetadatumValue() != null && this.getSemanticMetadatumValue() != -1) { queryString += " and cr.semanticMetadatum.id=:semanticMetadatumId"; queryCountString += " and cr.semanticMetadatum.id=:semanticMetadatumId"; } if (this.getFunctionalMetadatumValue() != null && this.getFunctionalMetadatumValue() != -1) { queryString += " and cr.functionalMetadatum.id=:functionalMetadatumId"; queryCountString += " and cr.functionalMetadatum.id=:functionalMetadatumId"; } if (this.isFilterAnalyzed()) { if (this.isSemanticCrawlerUser(this.job.getCrawlerUser())) { queryString += " and (cr.semanticMetadatum is null and cr.deleted=false) "; queryCountString += " and (cr.semanticMetadatum is null and cr.deleted=false) "; } else { queryString += " and (cr.functionalMetadatum is null and cr.deleted=false) "; queryCountString += " and (cr.functionalMetadatum is null and cr.deleted=false) "; } } if (this.sortField != null && this.sortField.length() > 0) { queryString += " order by cr." + this.sortField; if (this.sortOrder != null) { if (this.sortOrder.equals("down")) { queryString += " desc "; } } } Query query = this.entityManager.createQuery(queryString).setParameter("job", this.job); Query queryCount = this.entityManager.createQuery(queryCountString).setParameter("job", this.job); if (this.getFilterURLValue() != null && this.getFilterURLValue().length() > 0) { query.setParameter("url", "%" + this.getFilterURLValue() + "%"); queryCount.setParameter("url", "%" + this.getFilterURLValue() + "%"); } if (this.getFilterMimeTypeValue() != null && this.getFilterMimeTypeValue().length() > 0) { query.setParameter("mimeType", "%" + this.getFilterMimeTypeValue() + "%"); queryCount.setParameter("mimeType", "%" + this.getFilterMimeTypeValue() + "%"); } if (this.getSemanticMetadatumValue() != null && this.getSemanticMetadatumValue() != -1) { query.setParameter("semanticMetadatumId", this.semanticMetadatumValue); queryCount.setParameter("semanticMetadatumId", this.semanticMetadatumValue); } if (this.getFunctionalMetadatumValue() != null && this.getFunctionalMetadatumValue() != -1) { query.setParameter("functionalMetadatumId", this.functionalMetadatumValue); queryCount.setParameter("functionalMetadatumId", this.functionalMetadatumValue); } if (this.firstResult == null) { this.firstResult = 0; } // System.out.println("*****" + this.pageSize); this.results = query.setFirstResult(this.firstResult).setMaxResults(this.pageSize).getResultList(); if (this.results != null) { this.setTotalResults((Long) queryCount.getSingleResult()); if (this.getFirstResult() > this.getTotalResults()) { this.setFirstResult(0); } } return this.results; }
From source file:org.votingsystem.web.accesscontrol.ejb.RepresentativeBean.java
public synchronized RepresentativesAccreditations getAccreditationsBackupForEvent(EventVSElection eventVS) throws ExceptionVS, IOException { /*if(event.isActive(Calendar.getInstance().getTime())) { return new ResponseVS(statusCode:ResponseVS.SC_ERROR, message:messageSource.getMessage('eventActiveErrorMsg', [event.id].toArray(), locale)) }*/// ww w. j ava 2s . co m BakupFiles bakupFiles = new BakupFiles(eventVS, TypeVS.REPRESENTATIVE_DATA, config.getServerDir().getAbsolutePath()); File zipResult = bakupFiles.getZipResult(); File filesDir = bakupFiles.getFilesDir(); File metaInfFile = bakupFiles.getMetaInfFile(); log.info("event: " + eventVS.getId() + " - dir: " + filesDir.getAbsolutePath()); String backupFileName = format("{0}_EventVS_{1}.zip", TypeVS.REPRESENTATIVE_DATA, eventVS.getId()); if (zipResult.exists()) { log.info("existing backup file:" + backupFileName); RepresentativesAccreditations repAccreditations = new ObjectMapper().readValue(metaInfFile, new TypeReference<RepresentativesAccreditations>() { }); return repAccreditations; } Map<Long, ElectionOptionDto> optionsMap = new HashMap<>(); Query query = null; for (FieldEventVS option : eventVS.getFieldsEventVS()) { query = dao.getEM() .createQuery("select count(v) from VoteVS v where v.optionSelected =:option " + "and v.state =:state") .setParameter("option", option).setParameter("state", VoteVS.State.OK); Long numVoteRequests = (long) query.getSingleResult(); query = dao.getEM() .createQuery("select count(v) from VoteVS v where v.optionSelected =:option " + "and v.state =:state and v.certificateVS.userVS is null") .setParameter("option", option).setParameter("state", VoteVS.State.OK); Long numUsersWithVote = (long) query.getSingleResult(); Long numRepresentativesWithVote = numVoteRequests - numUsersWithVote; ElectionOptionDto electionOptionDto = new ElectionOptionDto(option.getContent(), numVoteRequests, numUsersWithVote, numRepresentativesWithVote, null); optionsMap.put(option.getId(), electionOptionDto); } log.info("this is for TEST - CHANGE dateCreated to dateBegin !!!"); query = dao.getEM() .createQuery("select count(r) from RepresentativeDocument r where r.dateCreated <:dateBegin " + "and r.state in :states and (r.dateCanceled is null or r.dateCanceled >:dateFinish)") .setParameter("dateBegin", eventVS.getDateBegin()) .setParameter("dateFinish", eventVS.getDateFinish()).setParameter("states", Arrays.asList(RepresentativeDocument.State.OK, RepresentativeDocument.State.RENEWED)); Long numRepresentatives = (long) query.getSingleResult(); Long numRepresentativesWithAccessRequest = 0L; Long numRepresentativesWithVote = 0L; Long numTotalRepresented = 0L; Long numTotalRepresentedWithAccessRequest = 0L; Long numVotesRepresentedByRepresentatives = 0L; long beginCalc = System.currentTimeMillis(); int offset = 0; int pageSize = 100; query = dao.getEM() .createQuery("select r from RepresentativeDocument r where r.dateCreated <:dateBegin " + "and r.state in :states and (r.dateCanceled is null or r.dateCanceled >:dateFinish)") .setParameter("dateBegin", eventVS.getDateBegin()) .setParameter("dateFinish", eventVS.getDateFinish()) .setParameter("states", Arrays.asList(RepresentativeDocument.State.OK, RepresentativeDocument.State.RENEWED)) .setMaxResults(pageSize); List<RepresentativeDocument> representativeDocList = null; Map<String, RepresentativeVoteDto> representativesMap = new HashMap<>(); DecimalFormat batchFormat = new DecimalFormat("00000000"); int batch = 0; while ((representativeDocList = query.setFirstResult(offset).getResultList()).size() > 0) { for (RepresentativeDocument representativeDoc : representativeDocList) { UserVS representative = representativeDoc.getUserVS(); String representativeBaseDir = format("{0}/representative_{1}/batch_{2}", filesDir.getAbsolutePath(), representative.getNif(), batchFormat.format(++batch)); new File(representativeBaseDir).mkdirs(); Long numRepresented = 1L; //The representative itself Long numRepresentedWithAccessRequest = 0L; Query representationQuery = dao.getEM().createQuery("select r from RepresentationDocument r where " + "r.representative =:representative and r.dateCreated <:dateBegin and r.state =:state and " + "(r.dateCanceled is null or r.dateCanceled >:dateFinish)") .setParameter("representative", representative) .setParameter("dateBegin", eventVS.getDateBegin()) .setParameter("dateFinish", eventVS.getDateFinish()) .setParameter("state", RepresentationDocument.State.OK).setMaxResults(pageSize); int representationOffset = 0; List<RepresentationDocument> representationList = null; while ((representationList = representationQuery.setFirstResult(representationOffset) .getResultList()).size() > 0) { for (RepresentationDocument representationDoc : representationList) { UserVS represented = representationDoc.getUserVS(); ++numRepresented; Query representationDocQuery = dao.getEM() .createQuery("select a from AccessRequestVS a where " + "a.state =:state and a.userVS =:userVS and a.eventVS =:eventVS") .setParameter("state", AccessRequestVS.State.OK).setParameter("userVS", represented) .setParameter("eventVS", eventVS); AccessRequestVS representedAccessRequest = dao.getSingleResult(AccessRequestVS.class, query); String repDocFileName = null; if (representedAccessRequest != null) { numRepresentedWithAccessRequest++; repDocFileName = format("{0}/{1}_delegation_with_vote.p7m", representativeBaseDir, represented.getNif()); } else repDocFileName = format("{0}/{1}_delegation.p7m", representativeBaseDir, represented.getNif()); File representationDocFile = new File(repDocFileName); IOUtils.write(representationDoc.getActivationSMIME().getContent(), new FileOutputStream(representationDocFile)); if ((numRepresented % 100) == 0) { dao.getEM().flush(); dao.getEM().clear(); log.info(format("Representative {0} - processed {1} representations", representative.getNif(), numRepresented)); } if (numRepresented % 2000 == 0) { representativeBaseDir = format("{0}/representative_{1}/batch_{2}", filesDir.getAbsolutePath(), representative.getNif(), batchFormat.format(++batch)); new File(representativeBaseDir).mkdirs(); } } representationOffset += pageSize; representationQuery.setFirstResult(representationOffset); String elapsedTime = DateUtils .getElapsedTimeHoursMinutesMillis(System.currentTimeMillis() - beginCalc); log.info( "processed " + representationOffset + " representatives - elapsedTime: " + elapsedTime); } numTotalRepresented += numRepresented; numTotalRepresentedWithAccessRequest += numRepresentedWithAccessRequest; State state = State.WITHOUT_ACCESS_REQUEST; Query representativeQuery = dao.getEM() .createQuery("select a from AccessRequestVS a where " + "a.eventVS =:eventVS and a.userVS =:userVS and a.state =:state") .setParameter("eventVS", eventVS).setParameter("userVS", representative) .setParameter("state", AccessRequestVS.State.OK); AccessRequestVS accessRequestVS = dao.getSingleResult(AccessRequestVS.class, representativeQuery); VoteVS representativeVote = null; if (accessRequestVS != null) {//Representative has access request numRepresentativesWithAccessRequest++; state = State.WITH_ACCESS_REQUEST; representativeQuery = dao.getEM() .createQuery("select v from VoteVS v where v.certificateVS.userVS =:userVS and " + "v.eventVS =:eventVS and v.state =:state") .setParameter("userVS", representative).setParameter("eventVS", eventVS) .setParameter("state", VoteVS.State.OK); representativeVote = dao.getSingleResult(VoteVS.class, representativeQuery); } Long numVotesRepresentedByRepresentative = 0L; if (representativeVote != null) { state = State.WITH_VOTE; ++numRepresentativesWithVote; numVotesRepresentedByRepresentative = numRepresented - numRepresentedWithAccessRequest; numVotesRepresentedByRepresentatives += numVotesRepresentedByRepresentative; optionsMap.get(representativeVote.getOptionSelected().getId()) .addNumVotesResult(numVotesRepresentedByRepresentative - 1); } RepresentativeVoteDto representativeVoteDto = new RepresentativeVoteDto(representative.getId(), representativeVote.getOptionSelected().getId(), numRepresented, numRepresentedWithAccessRequest, numVotesRepresentedByRepresentative); representativesMap.put(representative.getNif(), representativeVoteDto); String elapsedTimeStr = DateUtils .getElapsedTimeHoursMinutesMillis(System.currentTimeMillis() - beginCalc); /*String csvLine = "${representative.nif}, numRepresented:${formatted.format(numRepresented)}, " + "numRepresentedWithAccessRequest:${formatted.format(numRepresentedWithAccessRequest)}, ${state.toString()}\n" reportFile.append(csvLine)*/ } dao.getEM().flush(); dao.getEM().clear(); offset += pageSize; query.setFirstResult(offset); String elapsedTime = DateUtils.getElapsedTimeHoursMinutesMillis(System.currentTimeMillis() - beginCalc); log.info("processed " + offset + " of " + numRepresentatives + " representatives - elapsedTime: " + elapsedTime); } RepresentativesAccreditations representativesAccreditations = new RepresentativesAccreditations( numRepresentatives, numRepresentativesWithAccessRequest, numRepresentativesWithVote, numTotalRepresentedWithAccessRequest, numTotalRepresented, numVotesRepresentedByRepresentatives, optionsMap, representativesMap); new ObjectMapper().writeValue(metaInfFile, representativesAccreditations); return representativesAccreditations; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
public Query getSelectQuery(int rowsPerPage, String orderBy, EntityManager em, String jpql, List<Date> dtParams, int lastTotal, List<String> idFieldNames) { if (orderBy != null && orderBy.length() > 0) { int join = orderBy.indexOf("@"); if (join > 0) { int k = jpql.indexOf("where"); if (k > 0) { jpql = jpql.substring(0, k) + orderBy.substring(0, join) + jpql.substring(k) + orderBy.substring(join + 1); } else { jpql = jpql + " " + orderBy.substring(0, join) + orderBy.substring(join + 1); }/*from ww w . j a v a 2s .c o m*/ } else jpql = jpql + " " + orderBy; jpql = jpql + ", " + toString(idFieldNames); } Query q = em.createQuery(jpql); if (!dtParams.isEmpty()) { for (int i = 0; i < dtParams.size(); i++) { q.setParameter("dt" + i, dtParams.get(i)); } } setQueryTimeout(q); if (lastTotal >= 0 && rowsPerPage > 0) { q.setFirstResult(lastTotal); q.setMaxResults(rowsPerPage); } return q; }
From source file:org.nuxeo.ecm.rating.LikesCountActivityStreamFilter.java
@Override public ActivitiesList query(ActivityStreamService activityStreamService, Map<String, Serializable> parameters, long offset, long limit) { QueryType queryType = (QueryType) parameters.get(QUERY_TYPE_PARAMETER); if (queryType == null) { return new ActivitiesListImpl(); }/*from w w w . ja v a 2 s .com*/ Query query = null; String queryStr = ""; String innerStr = ""; EntityManager em = ((ActivityStreamServiceImpl) activityStreamService).getEntityManager(); Serializable actor = parameters.get(ACTOR_PARAMETER); switch (queryType) { case GET_DOCUMENTS_COUNT: // InnerQuery indicates if the actor has alredy liked or not innerStr = "SELECT COUNT(activity2) FROM Activity activity2 WHERE activity2.verb = :verb"; innerStr += " AND activity2.context = :context AND activity2.object = :object"; innerStr += " AND activity2.actor = :actor AND activity2.target = activity.target"; if (parameters.containsKey(FROMDT_PARAMETER)) { innerStr += " AND activity2.publishedDate BETWEEN :fromDt AND :toDt"; } queryStr = "SELECT activity.target, count(activity), (" + innerStr + ") FROM Activity activity"; queryStr += " WHERE activity.verb = :verb and activity.context = :context"; queryStr += " AND activity.object = :object"; if (parameters.containsKey(FROMDT_PARAMETER)) { queryStr += " AND activity.publishedDate BETWEEN :fromDt AND :toDt"; } queryStr += " GROUP BY activity.target ORDER BY COUNT(activity) DESC"; Serializable object = String.valueOf(parameters.get(OBJECT_PARAMETER)); query = em.createQuery(queryStr); query.setParameter(OBJECT_PARAMETER, object); break; case GET_MINI_MESSAGE_COUNT: // InnerQuery indicates if the actor has alredy liked or not innerStr = "Select count(likes2) from Activity as likes2 "; innerStr += " where likes.target = likes2.target and likes2.actor = :actor"; if (parameters.containsKey(FROMDT_PARAMETER)) { innerStr += " AND likes2.publishedDate BETWEEN :fromDt AND :toDt"; } queryStr = "Select likes.target, count(likes), (" + innerStr + ") from Activity as likes, Activity as minimessage"; queryStr += " where concat('activity:', cast(minimessage.id as string)) = likes.target"; queryStr += " and minimessage.verb = :verbMiniMessage and minimessage.context = :context"; queryStr += " and likes.verb = :verb"; if (parameters.containsKey(FROMDT_PARAMETER)) { queryStr += " AND likes.publishedDate BETWEEN :fromDt AND :toDt"; } queryStr += " group by likes.target order by count(likes) desc"; query = em.createQuery(queryStr); query.setParameter(VERB_MINIMESSAGE_PARAMETER, "minimessage"); break; default: log.info("Unknown query type: " + queryType); return new ActivitiesListImpl(); } // Default parameters query.setParameter(CONTEXT_PARAMETER, parameters.get(CONTEXT_PARAMETER)); query.setParameter(VERB_PARAMETER, RATING_VERB_PREFIX + LIKE_ASPECT); query.setParameter(ACTOR_PARAMETER, actor); if (parameters.containsKey(FROMDT_PARAMETER)) { query.setParameter(FROMDT_PARAMETER, parameters.get(FROMDT_PARAMETER)); query.setParameter(TODT_PARAMETER, parameters.get(TODT_PARAMETER)); } if (limit > 0) { query.setMaxResults((int) limit); } if (offset > 0) { query.setFirstResult((int) offset); } ActivitiesList likesCount = new ActivitiesListImpl(); for (Object result : query.getResultList()) { Object[] objects = (Object[]) result; ActivityBuilder ab = new ActivityBuilder().verb(RATING_VERB_PREFIX + LIKE_ASPECT).actor((String) actor) .object(String.valueOf(objects[1])).target((String) objects[0]) .context(String.valueOf(objects[2])); likesCount.add(ab.build()); } return likesCount; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public NakedObjectsList getSortedCollection(String nakedObjectName, com.hiperf.common.ui.shared.util.Id id, String attributeName, String sortAttribute, Boolean asc, int page, int rowsPerPage, ObjectsToPersist toPersist) throws PersistenceException { EntityManager em = null;//from ww w .j a v a2 s . co m TransactionContext tc = null; Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>(); try { Map<Object, IdHolder> newIdByOldId = new HashMap<Object, IdHolder>(); tc = createTransactionalContext(); em = tc.getEm(); ITransaction tx = tc.getTx(); tx.begin(); doPersist(toPersist, null, res, newIdByOldId, em, true, null); String jpql = "select count(*) from " + nakedObjectName + " o"; String currentFilter = getIdClause(id, attributeName); jpql += " where " + currentFilter; Query q = em.createQuery(jpql); Long count = getCount(id, newIdByOldId, q); int lastTotal = rowsPerPage * (page - 1); if (count > 0 && count > lastTotal) { jpql = "select o from " + nakedObjectName + " o "; jpql += "where " + currentFilter; if (asc != null) { if (asc) { jpql += " order by o." + sortAttribute + " asc"; } else { jpql += " order by o." + sortAttribute + " desc"; } } q = em.createQuery(jpql); int i = 0; for (Object idObj : id.getFieldValues()) { if (id.isLocal() && newIdByOldId.containsKey(idObj)) q.setParameter("id" + i, newIdByOldId.get(idObj).getId()); else q.setParameter("id" + i, idObj); } q.setFirstResult(lastTotal); q.setMaxResults(rowsPerPage); List<INakedObject> list = q.getResultList(); if (list != null && !list.isEmpty()) { String name = list.get(0).getClass().getName(); Map<String, Map<Object, Object>> oldIdByNewIdMap = buildInverseIdMap(newIdByOldId); list = deproxyEntities(name, list, true, oldIdByNewIdMap); } NakedObjectsList l = new NakedObjectsList(list, count.intValue(), rowsPerPage, currentFilter); l.setConstantFilterFields(new String[] { attributeName }); return l; } else return null; } catch (Exception e) { logger.log(Level.SEVERE, "Exception in getCollection " + e.getMessage(), e); throw new PersistenceException("Exception in getCollection " + e.getMessage(), e); } finally { finalizeTx(tc); } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public NakedObjectsList getCollectionInverse(String wrappedClassName, String attribute, com.hiperf.common.ui.shared.util.Id id, int page, int nbRows, ObjectsToPersist toPersist, String sortAttribute, Boolean asc) throws PersistenceException { INakedObject o = null;//from w ww .j a v a2s.c om EntityManager em = null; TransactionContext tc = null; Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>(); try { Map<Object, IdHolder> newIdByOldId = new HashMap<Object, IdHolder>(); tc = createTransactionalContext(); em = tc.getEm(); ITransaction tx = tc.getTx(); tx.begin(); doPersist(toPersist, null, res, newIdByOldId, em, true, null); String jpql = "select size(o." + attribute + ") from " + wrappedClassName + " o"; String currentFilter = getIdClause(id); jpql += " where " + currentFilter; Query q = em.createQuery(jpql); Integer count = getSize(id, newIdByOldId, q); int lastTotal = nbRows * (page - 1); if (count > 0 && count > lastTotal) { jpql = "select j from " + wrappedClassName + " o inner join o." + attribute + " j "; jpql += "where " + currentFilter; if (asc != null && sortAttribute != null) { if (asc) { jpql += " order by j." + sortAttribute + " asc"; } else { jpql += " order by j." + sortAttribute + " desc"; } } q = em.createQuery(jpql); int i = 0; for (Object idObj : id.getFieldValues()) { if (id.isLocal() && newIdByOldId.containsKey(idObj)) q.setParameter("id" + i, newIdByOldId.get(idObj).getId()); else q.setParameter("id" + i, idObj); } q.setFirstResult(lastTotal); q.setMaxResults(nbRows); List<INakedObject> list = q.getResultList(); if (list != null && !list.isEmpty()) { String name = list.get(0).getClass().getName(); Map<String, Map<Object, Object>> oldIdByNewMap = buildInverseIdMap(newIdByOldId); list = deproxyEntities(name, list, true, oldIdByNewMap); } return new NakedObjectsList(list, count.intValue(), nbRows, currentFilter); } else return null; } catch (Exception e) { logger.log(Level.SEVERE, "Exception in getCollection " + e.getMessage(), e); throw new PersistenceException("Exception in getCollection " + e.getMessage(), e); } finally { finalizeTx(tc); } }
From source file:org.sofun.core.team.TeamServiceImpl.java
@SuppressWarnings("unchecked") @Override//from w w w . ja v a2s .c o m public Set<Team> searchTeams(Map<String, String> params) throws CoreException { log.debug("searchTeams()"); Set<Team> teams = new HashSet<Team>(); List<TeamImpl> results = null; // Batching information int offset = 0; final String offsetStr = params.get("offset"); if (offsetStr != null) { log.debug("searchTeams() - user param offset => " + offsetStr); offset = Integer.valueOf(offsetStr); } int batchSize = 10; // default batch size final String batchSizeStr = params.get("batchSize"); if (batchSizeStr != null) { log.debug("searchTeams() - user param batchSize => " + batchSizeStr); batchSize = Integer.valueOf(batchSizeStr); } String queryStr = ""; Query query = null; final String email = params.get("email"); if (email != null) { Member member = members.getMember(email); if (member != null) { log.debug("searchTeams() - user param email => " + email); // We assume an administrator is always a member of the team queryStr = "SELECT t FROM " + TeamImpl.class.getSimpleName() + " t JOIN t.members m WHERE m.id=:member_id AND t.name NOT IN (:name)"; query = em.createQuery(queryStr, TeamImpl.class); query.setParameter("member_id", member.getId()); // Exclude community teams. query.setParameter("name", communities.getCommunityNames()); } } else { boolean sflag = false; queryStr = "SELECT DISTINCT * FROM teams WHERE "; // Keywords final String lkeywords = params.get("keywords"); if (lkeywords != null && !lkeywords.isEmpty()) { final List<String> keywords = Arrays.asList(lkeywords.split(" ")); int i = 0; for (String keyword : keywords) { if (i == 0) { queryStr += " ( "; } else if (i > 0) { queryStr += " OR "; } queryStr += " to_tsvector('french', name || ' ' || description) @@ to_tsquery('french', '" + keyword + "') "; i++; } if (keywords.size() > 0) { sflag = true; queryStr += " ) "; } } final String name = params.get("name"); if (name != null && !name.isEmpty()) { if (sflag) { queryStr += " AND "; } final List<String> names = Arrays.asList(name.split(",")); // Remove all community names to avoid default community teams // to show up in search results. for (String cname : communities.getCommunityNames()) { if (names.contains(cname)) { names.remove(cname); } } if (names.size() > 0) { queryStr += " ( "; int i = 0; for (String kname : names) { if (i > 0) { queryStr += " OR "; } queryStr += " name like '" + kname + "'"; i++; } queryStr += " ) "; sflag = true; } } else { if (sflag) { queryStr += " AND "; } final List<String> names = communities.getCommunityNames(); if (names.size() > 0) { queryStr += " ( "; int i = 0; for (String kname : names) { if (i > 0) { queryStr += " AND "; } queryStr += " name not like '" + kname + "'"; i++; } sflag = true; queryStr += " ) "; } } // Privacy final String privacy = params.get("privacy"); List<String> privacyParam = new ArrayList<String>(); if (privacy != null && !privacy.isEmpty()) { if (TeamPrivacy.PUBLIC.equals(privacy)) { privacyParam.add(TeamPrivacy.PUBLIC); privacyParam.add(TeamPrivacy.PUBLIC_GAMBLING_FR); } else if (TeamPrivacy.PRIVATE.equals(privacy)) { privacyParam.add(TeamPrivacy.PRIVATE); privacyParam.add(TeamPrivacy.PRIVATE_GAMBLING_FR); } else { privacyParam.add(privacy); } } else { privacyParam.add(TeamPrivacy.PRIVATE); privacyParam.add(TeamPrivacy.PRIVATE_GAMBLING_FR); privacyParam.add(TeamPrivacy.PUBLIC); privacyParam.add(TeamPrivacy.PUBLIC_GAMBLING_FR); } if (privacyParam.size() > 0) { if (sflag) { queryStr += " AND "; } queryStr += " ( "; int i = 0; for (String kprivacy : privacyParam) { if (i > 0) { queryStr += " OR "; } queryStr += " privacy like '" + kprivacy + "'"; i++; } queryStr += " ) "; } // SORTING queryStr += " ORDER BY nb_members DESC,created DESC"; query = em.createNativeQuery(queryStr, TeamImpl.class); } if (query != null) { // Batching information query.setFirstResult(offset); query.setMaxResults(batchSize); results = query.getResultList(); if (results != null) { log.debug("searchTeams() - results.size() => " + results.size()); teams = new HashSet<Team>(results); } } return teams; }