List of usage examples for javax.persistence TypedQuery getSingleResult
X getSingleResult();
From source file:org.openmeetings.app.data.user.Usermanagement.java
public Long getUserLevelByIdAndOrg(Long user_id, Long organisation_id) { try {/* w ww . java2 s .co m*/ if (user_id == null) return new Long(0); // For direct access of linked users if (user_id == -1) { return new Long(1); } TypedQuery<Users> query = em.createQuery( "select c from Users as c where c.user_id = :user_id AND c.deleted <> 'true'", Users.class); query.setParameter("user_id", user_id); Users us = null; try { us = query.getSingleResult(); } catch (NoResultException e) { // u=null} } if (us != null) { if (us.getLevel_id() > 2) { return us.getLevel_id(); } else { log.debug("user_id, organisation_id" + user_id + ", " + organisation_id); Organisation_Users ou = organisationmanagement .getOrganisation_UserByUserAndOrganisation(user_id, organisation_id); log.debug("ou: " + ou); if (ou != null) { if (ou.getIsModerator() != null && ou.getIsModerator()) { return 2L; } else { return us.getLevel_id(); } } else { return us.getLevel_id(); } } } else { return -1L; } } catch (Exception ex2) { log.error("[getUserLevelByID]", ex2); } return null; }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
@Override public BaseHasResource readEntity(IdDt theId, boolean theCheckForForcedId) { validateResourceTypeAndThrowIllegalArgumentException(theId); Long pid = translateForcedIdToPid(theId); BaseHasResource entity = myEntityManager.find(ResourceTable.class, pid); if (theId.hasVersionIdPart()) { if (entity.getVersion() != theId.getVersionIdPartAsLong()) { entity = null;/* ww w . j a va 2 s . c o m*/ } } if (entity == null) { if (theId.hasVersionIdPart()) { TypedQuery<ResourceHistoryTable> q = myEntityManager.createQuery( "SELECT t from ResourceHistoryTable t WHERE t.myResourceId = :RID AND t.myResourceType = :RTYP AND t.myResourceVersion = :RVER", ResourceHistoryTable.class); q.setParameter("RID", pid); q.setParameter("RTYP", myResourceName); q.setParameter("RVER", theId.getVersionIdPartAsLong()); entity = q.getSingleResult(); } if (entity == null) { throw new ResourceNotFoundException(theId); } } validateResourceType(entity); if (theCheckForForcedId) { validateGivenIdIsAppropriateToRetrieveResource(theId, entity); } return entity; }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
@Override public IBundleProvider history(final IdDt theId, final Date theSince) { final InstantDt end = createHistoryToTimestamp(); final String resourceType = getContext().getResourceDefinition(myResourceType).getName(); T currentTmp;/*from w ww. j av a 2s . com*/ try { BaseHasResource entity = readEntity(theId.toVersionless(), false); validateResourceType(entity); currentTmp = toResource(myResourceType, entity); if (ResourceMetadataKeyEnum.UPDATED.get(currentTmp).after(end.getValue())) { currentTmp = null; } } catch (ResourceNotFoundException e) { currentTmp = null; } final T current = currentTmp; String querySring = "SELECT count(h) FROM ResourceHistoryTable h " + "WHERE h.myResourceId = :PID AND h.myResourceType = :RESTYPE" + " AND h.myUpdated < :END" + (theSince != null ? " AND h.myUpdated >= :SINCE" : ""); TypedQuery<Long> countQuery = myEntityManager.createQuery(querySring, Long.class); countQuery.setParameter("PID", translateForcedIdToPid(theId)); countQuery.setParameter("RESTYPE", resourceType); countQuery.setParameter("END", end.getValue(), TemporalType.TIMESTAMP); if (theSince != null) { countQuery.setParameter("SINCE", theSince, TemporalType.TIMESTAMP); } int historyCount = countQuery.getSingleResult().intValue(); final int offset; final int count; if (current != null) { count = historyCount + 1; offset = 1; } else { offset = 0; count = historyCount; } if (count == 0) { throw new ResourceNotFoundException(theId); } return new IBundleProvider() { @Override public InstantDt getPublished() { return end; } @Override public List<IResource> getResources(int theFromIndex, int theToIndex) { ArrayList<IResource> retVal = new ArrayList<IResource>(); if (theFromIndex == 0 && current != null) { retVal.add(current); } TypedQuery<ResourceHistoryTable> q = myEntityManager.createQuery( "SELECT h FROM ResourceHistoryTable h WHERE h.myResourceId = :PID AND h.myResourceType = :RESTYPE AND h.myUpdated < :END " + (theSince != null ? " AND h.myUpdated >= :SINCE" : "") + " ORDER BY h.myUpdated ASC", ResourceHistoryTable.class); q.setParameter("PID", translateForcedIdToPid(theId)); q.setParameter("RESTYPE", resourceType); q.setParameter("END", end.getValue(), TemporalType.TIMESTAMP); if (theSince != null) { q.setParameter("SINCE", theSince, TemporalType.TIMESTAMP); } int firstResult = Math.max(0, theFromIndex - offset); q.setFirstResult(firstResult); int maxResults = (theToIndex - theFromIndex) + 1; q.setMaxResults(maxResults); List<ResourceHistoryTable> results = q.getResultList(); for (ResourceHistoryTable next : results) { if (retVal.size() == maxResults) { break; } retVal.add(toResource(myResourceType, next)); } return retVal; } @Override public Integer preferredPageSize() { return null; } @Override public int size() { return count; } }; }
From source file:gov.osti.services.Metadata.java
/** * Acquire a List of records in pending ("Submitted") state, to be approved * for indexing and searching.//from w ww . j a va 2s . com * * 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(); } }
From source file:com.clustercontrol.jobmanagement.factory.SelectJob.java
/** * ???????<BR>/*from w ww. ja v a2 s . c om*/ * ????????? * <p> * <ol> * <li>???????</li> * <li>?????????</li> * <ol> * <li>?????</li> * <li>?????</li> * <li>1??{@link com.clustercontrol.jobmanagement.bean.HistoryTableDefine}??{@link ArrayList}????</li> * <dl> * <dt>Object?2?</dt> * <dd>{ 1 {1?, 2?, }, 2{1?, 2?, }, }</dd> * </dl> * </ol> * <li>?{@link com.clustercontrol.jobmanagement.bean.JobHistoryList}?????</li> * </ol> * * @param userId ?ID * @param property ? * @param histories * @return * @throws JobInfoNotFound * * @see com.clustercontrol.bean.JobConstant */ public JobHistoryList getHistoryList(String userId, JobHistoryFilter property, int histories) throws JobInfoNotFound { m_log.debug("getHistoryList() start : userId = " + userId + ", histories = " + histories); Long startFromDate = null; Long startToDate = null; Long endFromDate = null; Long endToDate = null; String jobId = null; Integer status = null; Integer endStatus = null; Integer triggerType = null; String triggerInfo = null; String ownerRoleId = null; if (property != null) { if (property.getStartFromDate() != null) { startFromDate = property.getStartFromDate(); } if (property.getStartToDate() != null) { startToDate = property.getStartToDate(); } if (property.getEndFromDate() != null) { endFromDate = property.getEndFromDate(); } if (property.getEndToDate() != null) { endToDate = property.getEndToDate(); } jobId = property.getJobId(); status = property.getStatus(); endStatus = property.getEndStatus(); triggerType = property.getTriggerType(); triggerInfo = property.getTriggerInfo(); ownerRoleId = property.getOwnerRoleId(); m_log.debug("getHistoryList() property" + " startFromDate = " + startFromDate + ", startToDate = " + startToDate + ", endFromDate = " + endFromDate + ", endToDate = " + endToDate + ", jobId = " + jobId + ", status = " + status + ", endStatus = " + endStatus + ", triggerType = " + triggerType + ", triggerInfo = " + triggerInfo + ", ownerRoleId = " + ownerRoleId); } else { m_log.debug("getHistoryList() property is null"); } JobHistoryList list = new JobHistoryList(); ArrayList<JobHistory> historyList = new ArrayList<JobHistory>(); int total = 0; if (histories <= 0) { histories = MAX_DISPLAY_NUMBER; } Integer limit = histories + 1; //???? TypedQuery<?> typedQuery = getHistoryFilterQuery(startFromDate, startToDate, endFromDate, endToDate, jobId, status, endStatus, triggerType, triggerInfo, ownerRoleId, false); if (limit != null) { typedQuery = typedQuery.setMaxResults(limit); } @SuppressWarnings("unchecked") List<JobSessionJobEntity> sessionJobList = (List<JobSessionJobEntity>) typedQuery.getResultList(); if (sessionJobList == null) { JobInfoNotFound je = new JobInfoNotFound(); je.setJobId(jobId); m_log.info("getHistoryList() : " + je.getClass().getSimpleName() + ", " + je.getMessage()); } m_log.debug("getHistoryList() target sessionList exist"); if (sessionJobList != null) { // if (sessionJobList.size() > histories) { //???? TypedQuery<?> countTypedQuery = getHistoryFilterQuery(startFromDate, startToDate, endFromDate, endToDate, jobId, status, endStatus, triggerType, triggerInfo, ownerRoleId, true); total = (int) ((Long) countTypedQuery.getSingleResult()).longValue(); } else { total = sessionJobList.size(); } m_log.debug("getHistoryList() total = " + total); for (JobSessionJobEntity sessionJob : sessionJobList) { // JobSession? JobSessionEntity session = sessionJob.getJobSessionEntity(); // JobInfoEntity? JobInfoEntity jobInfo = sessionJob.getJobInfoEntity(); //?? JobHistory info = new JobHistory(); info.setStatus(sessionJob.getStatus()); info.setEndStatus(sessionJob.getEndStatus()); info.setEndValue(sessionJob.getEndValue()); info.setSessionId(sessionJob.getId().getSessionId()); info.setJobId(sessionJob.getId().getJobId()); info.setJobunitId(sessionJob.getId().getJobunitId()); info.setJobName(jobInfo.getJobName()); info.setJobType(jobInfo.getJobType()); if (jobInfo.getJobType() == JobConstant.TYPE_JOB || jobInfo.getJobType() == JobConstant.TYPE_APPROVALJOB || jobInfo.getJobType() == JobConstant.TYPE_MONITORJOB) { info.setFacilityId(jobInfo.getFacilityId()); info.setScope(sessionJob.getScopeText()); } info.setOwnerRoleId(sessionJob.getOwnerRoleId()); if (session.getScheduleDate() != null) { info.setScheduleDate(session.getScheduleDate()); } if (sessionJob.getStartDate() != null) { info.setStartDate(sessionJob.getStartDate()); } if (sessionJob.getEndDate() != null) { info.setEndDate(sessionJob.getEndDate()); } if (session.getTriggerInfo() != null && !session.getTriggerInfo().equals("")) { info.setJobTriggerType(session.getTriggerType()); info.setTriggerInfo(session.getTriggerInfo()); } historyList.add(info); //???????? if (historyList.size() >= histories) break; } } list.setTotal(total); list.setList(historyList); return list; }
From source file:com.tasktop.c2c.server.tasks.tests.service.TaskServiceTest.java
License:asdf
protected void assertUserExistsWithCurrentValues(TaskUserProfile user1) { TypedQuery<Profile> query = entityManager .createQuery("select u from " + Profile.class.getSimpleName() + " u where u.loginName = :name", Profile.class) .setParameter("name", user1.getLoginName()); Profile result = query.getSingleResult(); assertEquals(user1.getLoginName(), result.getLoginName()); assertEquals(user1.getRealname(), result.getRealname()); }
From source file:fr.ortolang.diffusion.core.CoreServiceBean.java
@Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public String resolveWorkspaceAlias(String alias) throws CoreServiceException, AliasNotFoundException { LOGGER.log(Level.FINE, "finding workspace for alias: " + alias); try {/*from w ww .j a v a2 s.co m*/ TypedQuery<Workspace> query = em.createNamedQuery("findWorkspaceByAlias", Workspace.class) .setParameter("alias", alias); try { Workspace workspace = query.getSingleResult(); return registry.lookup(workspace.getObjectIdentifier()); } catch (NoResultException e) { throw new AliasNotFoundException(alias); } } catch (RegistryServiceException | IdentifierNotRegisteredException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred during resolving workspace alias: " + alias, e); throw new CoreServiceException("unable to resolve workspace alias: " + alias, e); } }
From source file:fr.ortolang.diffusion.core.CoreServiceBean.java
@Override public List<OrtolangIndexableContent> getIndexableContent(String key) throws KeyNotFoundException, RegistryServiceException, IndexingServiceException, OrtolangException { OrtolangObjectIdentifier identifier = registry.lookup(key); if (!identifier.getService().equals(CoreService.SERVICE_NAME)) { throw new OrtolangException( "object identifier " + identifier + " does not refer to service " + getServiceName()); }/* ww w. j a v a 2s . co m*/ List<OrtolangIndexableContent> indexableContents = new ArrayList<>(); OrtolangObject object = null; switch (identifier.getType()) { case DataObject.OBJECT_TYPE: DataObject dataObject = em.find(DataObject.class, identifier.getId()); object = dataObject; dataObject.setKey(key); // indexableContents.add(new DataObjectIndexableContent(dataObject)); break; case Collection.OBJECT_TYPE: Collection collection = em.find(Collection.class, identifier.getId()); object = collection; collection.setKey(key); // indexableContents.add(new CollectionIndexableContent(collection)); if (collection.isRoot() && Status.PUBLISHED.value().equals(registry.getPublicationStatus(key))) { try { TypedQuery<Workspace> query = em .createNamedQuery("findWorkspaceByRootCollection", Workspace.class) .setParameter("root", "%" + collection.getKey() + "%"); Workspace workspace = query.getSingleResult(); String wskey = registry.lookup(workspace.getObjectIdentifier()); workspace.setKey(wskey); String snapshot = workspace.findSnapshotByKey(collection.getKey()).getName(); TagElement tagElement = workspace.findTagBySnapshot(snapshot); if (tagElement == null) { // Do not index published root collection with no associated tag: replaced by new version (tag moved) break; } String tag = tagElement.getName(); // CollectionContent collectionContent = listCollectionContent(collection.getKey()); // Rating metadata for root collections int rate = 0; MetadataElement ratingMetadata = collection.findMetadataByName(MetadataFormat.RATING); if (ratingMetadata != null) { OrtolangObjectIdentifier ratingMetadataIdentifier = registry .lookup(ratingMetadata.getKey()); MetadataObject ratingMetadataObject = em.find(MetadataObject.class, ratingMetadataIdentifier.getId()); ObjectMapper mapper = new ObjectMapper(); try { Map<String, Object> content = mapper.readValue( binarystore.getFile(ratingMetadataObject.getStream()), new TypeReference<Map<String, Object>>() { }); Object score = content.get("score"); if (score != null && score instanceof Integer) { rate = (Integer) score; } } catch (IOException | BinaryStoreServiceException | DataNotFoundException e) { } } // Index item metadata for root collections MetadataElement itemMetadata = collection.findMetadataByName(MetadataFormat.ITEM); if (itemMetadata != null) { OrtolangObjectIdentifier itemMetadataIdentifier = registry.lookup(itemMetadata.getKey()); MetadataObject metadataObject = em.find(MetadataObject.class, itemMetadataIdentifier.getId()); // Indexes in item-all index : /item-all/{ortolang-type} indexableContents.add(new OrtolangItemIndexableContent(metadataObject, collection, workspace.getAlias(), snapshot, tag, rate, workspace.isArchive(), false)); String latestPublishedSnapshot = findWorkspaceLatestPublishedSnapshot(workspace.getKey()); if (snapshot.equals(latestPublishedSnapshot)) { // Indexes in item index : /item/{ortolang-type} indexableContents.add(new OrtolangItemIndexableContent(metadataObject, collection, workspace.getAlias(), snapshot, tag, rate, workspace.isArchive(), true)); } } // for (CollectionContentEntry entry : collectionContent.getContent()) { // Map<String, Object> params = new HashMap<>(); // params.put("alias", workspace.getAlias()); // params.put("key", workspace.getKey()); // params.put("root", collection.getKey()); // params.put("path", entry.getPath()); // params.put("snapshot", snapshot); // indexableContents.add(new OrtolangObjectScriptedUpdate(CoreService.SERVICE_NAME, entry.getType(), entry.getKey(),"updateRootCollectionChild", params)); // } } catch (IdentifierNotRegisteredException | CoreServiceException | NoResultException e) { throw new OrtolangException(e.getMessage(), e); } } break; case Workspace.OBJECT_TYPE: Workspace workspace = em.find(Workspace.class, identifier.getId()); workspace.setKey(key); // Indexes in core index : /core/workspace return Collections.singletonList(new WorkspaceIndexableContent(workspace)); case MetadataObject.OBJECT_TYPE: MetadataObject metadataObject = em.find(MetadataObject.class, identifier.getId()); MetadataFormat format = em.find(MetadataFormat.class, metadataObject.getFormat()); metadataObject.setKey(key); // Indexes in core index : /core/metadata // indexableContents.add(new MetadataObjectIndexableContent(metadataObject, format)); if (!metadataObject.getName().startsWith("system-") && !metadataObject.getName().startsWith("ortolang-") && Status.PUBLISHED.value().equals(registry.getPublicationStatus(key))) { // Indexes in core index : /metadata/{format} indexableContents.add(new UserMetadataIndexableContent(metadataObject, format)); } } // if (object != null) { // for (MetadataElement metadataElement : ((MetadataSource) object).getMetadatas()) { //// if (metadataElement.getName().startsWith("system-x-")) { // OrtolangObjectIdentifier mdIdentifier = registry.lookup(metadataElement.getKey()); // MetadataObject metadataObject = em.find(MetadataObject.class, mdIdentifier.getId()); // MetadataFormat format = em.find(MetadataFormat.class, metadataObject.getFormat()); // metadataObject.setKey(metadataElement.getKey()); // indexableContents.add(new MetadataObjectIndexableContent(metadataObject, format)); //// } // } // } return indexableContents; }
From source file:org.apache.cxf.jaxrs.ext.search.jpa.AbstractJPATypedQueryVisitor.java
public Long getQueriesCount() { CriteriaQuery<Long> select = (CriteriaQuery<Long>) getCriteriaQuery() .select((Selection<? extends T1>) builder.count(root)); TypedQuery<Long> typedQuery = em.createQuery(select); Long result = typedQuery.getSingleResult(); return result; }
From source file:org.apache.falcon.jdbc.MonitoringJdbcStateStore.java
public PendingInstanceBean getPendingInstance(String feedName, String clusterName, Date nominalTime) { EntityManager entityManager = getEntityManager(); beginTransaction(entityManager);/*from w w w . java2 s .c o m*/ TypedQuery<PendingInstanceBean> q = entityManager .createNamedQuery(PersistenceConstants.GET_PENDING_INSTANCE, PendingInstanceBean.class); q.setParameter("feedName", feedName); q.setParameter("clusterName", clusterName); q.setParameter("nominalTime", nominalTime); try { return q.getSingleResult(); } finally { commitAndCloseTransaction(entityManager); } }