Java Code Examples for javax.persistence.TypedQuery

The following examples show how to use javax.persistence.TypedQuery. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: zstack   Source File: SecurityGroupManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional
private List<SecurityGroupFailureHostVO> takeFailureHosts() {
    String sql = "select sgf from SecurityGroupFailureHostVO sgf, HostVO host where host.uuid = sgf.hostUuid and host.status = :hostConnectionState and sgf.managementNodeId is NULL group by sgf.hostUuid order by sgf.lastOpDate ASC";
    TypedQuery<SecurityGroupFailureHostVO> q = dbf.getEntityManager().createQuery(sql, SecurityGroupFailureHostVO.class);
    q.setLockMode(LockModeType.PESSIMISTIC_READ);
    q.setParameter("hostConnectionState", HostStatus.Connected);
    q.setMaxResults(failureHostEachTimeTake);
    List<SecurityGroupFailureHostVO> lst = q.getResultList();
    if (lst.isEmpty()) {
        return lst;
    }

    List<Long> ids = CollectionUtils.transformToList(lst, new Function<Long, SecurityGroupFailureHostVO>() {
        @Override
        public Long call(SecurityGroupFailureHostVO arg) {
            return arg.getId();
        }
    });

    sql = "update SecurityGroupFailureHostVO f set f.managementNodeId = :mgmtId where f.id in (:ids)";
    Query uq = dbf.getEntityManager().createQuery(sql);
    uq.setParameter("mgmtId", Platform.getManagementServerId());
    uq.setParameter("ids", ids);
    uq.executeUpdate();
    return lst;
}
 
Example 2
Source Project: monolith   Source File: TicketPriceEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<TicketPriceDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<TicketPrice> findAllQuery = em.createQuery("SELECT DISTINCT t FROM TicketPrice t LEFT JOIN FETCH t.show LEFT JOIN FETCH t.section LEFT JOIN FETCH t.ticketCategory ORDER BY t.id", TicketPrice.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<TicketPrice> searchResults = findAllQuery.getResultList();
   final List<TicketPriceDTO> results = new ArrayList<TicketPriceDTO>();
   for (TicketPrice searchResult : searchResults)
   {
      TicketPriceDTO dto = new TicketPriceDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 3
Source Project: TeaStore   Source File: OrderItemRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets all order items for the given productId.
 * @param productId The id of the product ordered.
 * @param start The index of the first orderItem to return. Negative value to start at the beginning.
 * @param limit The maximum number of orderItem to return. Negative value to return all.
 * @return List of order items with the specified product.
 */
public List<PersistenceOrderItem> getAllEntitiesWithProduct(long productId, int start, int limit) {
	List<PersistenceOrderItem> entities = null;
	EntityManager em = getEM();
    try {
        em.getTransaction().begin();
        PersistenceProduct prod = em.find(PersistenceProduct.class, productId);
        if (prod != null) {
        	TypedQuery<PersistenceOrderItem> allMatchesQuery =
        			em.createQuery("SELECT u FROM " + getEntityClass().getName()
        					+ " u WHERE u.product = :prod", getEntityClass());
        	allMatchesQuery.setParameter("prod", prod);
    		entities = resultsWithStartAndLimit(em, allMatchesQuery, start, limit);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
	if (entities == null) {
		return new ArrayList<PersistenceOrderItem>();
	}
	return entities;
}
 
Example 4
Source Project: monolith   Source File: ShowEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<ShowDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<Show> findAllQuery = em.createQuery("SELECT DISTINCT s FROM Show s LEFT JOIN FETCH s.event LEFT JOIN FETCH s.venue LEFT JOIN FETCH s.performances LEFT JOIN FETCH s.ticketPrices ORDER BY s.id", Show.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<Show> searchResults = findAllQuery.getResultList();
   final List<ShowDTO> results = new ArrayList<ShowDTO>();
   for (Show searchResult : searchResults)
   {
      ShowDTO dto = new ShowDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 5
Source Project: cloud-espm-v2   Source File: DataLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to the parse the contents of the
 * "com/sap/espm/model/data/Products.xml" file and populate a list of
 * {@link Product} that will eventually be persisted in the Data Source.
 * 
 * @param suppliers
 *            - The List of {@link Supplier}.
 * @return - The list of {@link Product} that will be persisted in the
 *         Database.
 */
public List<Product> loadProducts(List<Supplier> suppliers) {
	EntityManager em = emf.createEntityManager();
	TypedQuery<Product> queryProd;
	List<Product> resProd = null;
	try {
		em.getTransaction().begin();
		queryProd = em.createNamedQuery("Product.getAllProducts", Product.class);
		resProd = queryProd.getResultList();
		if (resProd.size() > 5) {
			logger.info(resProd.size() + " Products already available in the db");
		} else {
			new XMLParser().readProduct(em, "com/sap/espm/model/data/Products.xml", suppliers);
			em.getTransaction().commit();
			queryProd = em.createNamedQuery("Product.getAllProducts", Product.class);
			resProd = queryProd.getResultList();
			logger.info(resProd.size() + " Products loaded into the db");
		}
	} catch (Exception e) {
		logger.error("Exception occured", e);
	} finally {
		em.close();
	}
	return resProd;
}
 
Example 6
Source Project: monolith   Source File: EventEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<EventDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<Event> findAllQuery = em.createQuery("SELECT DISTINCT e FROM Event e LEFT JOIN FETCH e.mediaItem LEFT JOIN FETCH e.category ORDER BY e.id", Event.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<Event> searchResults = findAllQuery.getResultList();
   final List<EventDTO> results = new ArrayList<EventDTO>();
   for (Event searchResult : searchResults)
   {
      EventDTO dto = new EventDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 7
Source Project: zstack   Source File: VirtualRouterPortForwardingBackend.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
private VirtualRouterVmInventory findRunningVirtualRouterForRule(String ruleUuid) {
    List<String> vrUuids = proxy.getVrUuidsByNetworkService(PortForwardingRuleVO.class.getSimpleName(), ruleUuid);
    if (vrUuids == null || vrUuids.isEmpty()) {
        return null;
    }

    String sql = "select vr from VirtualRouterVmVO vr where vr.uuid in (:vrUuids) and vr.state = :vrState";
    TypedQuery<VirtualRouterVmVO> q = dbf.getEntityManager().createQuery(sql, VirtualRouterVmVO.class);
    q.setParameter("vrUuids", vrUuids);
    q.setParameter("vrState", VmInstanceState.Running);
    q.setMaxResults(1);
    List<VirtualRouterVmVO> vrs = q.getResultList();
    if (vrs.isEmpty()) {
        return null;
    } else {
        return VirtualRouterVmInventory.valueOf(vrs.get(0));
    }
}
 
Example 8
Source Project: zstack   Source File: ImageCascadeExtension.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
private List<ImageDeletionStruct> getImageOnBackupStorage(List<String> bsUuids) {
    String sql = "select ref.backupStorageUuid, img from ImageVO img, ImageBackupStorageRefVO ref where img.uuid = ref.imageUuid and ref.backupStorageUuid in (:bsUuids) group by img.uuid";
    TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
    q.setParameter("bsUuids", bsUuids);
    List<Tuple> ts = q.getResultList();

    Map<String, ImageDeletionStruct> tmp = new HashMap<String, ImageDeletionStruct>();
    for (Tuple t : ts) {
        String bsUuid = t.get(0, String.class);
        ImageVO img = t.get(1, ImageVO.class);
        ImageDeletionStruct struct = tmp.get(img.getUuid());
        if (struct == null) {
            struct = new ImageDeletionStruct();
            struct.setImage(ImageInventory.valueOf(img));
            struct.setBackupStorageUuids(new ArrayList<String>());
            tmp.put(img.getUuid(), struct);
        }
        struct.getBackupStorageUuids().add(bsUuid);
    }

    List<ImageDeletionStruct> structs = new ArrayList<ImageDeletionStruct>();
    structs.addAll(tmp.values());
    return structs;
}
 
Example 9
Source Project: monolith   Source File: SectionAllocationEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/json")
public Response findById(@PathParam("id") Long id)
{
   TypedQuery<SectionAllocation> findByIdQuery = em.createQuery("SELECT DISTINCT s FROM SectionAllocation s LEFT JOIN FETCH s.performance LEFT JOIN FETCH s.section WHERE s.id = :entityId ORDER BY s.id", SectionAllocation.class);
   findByIdQuery.setParameter("entityId", id);
   SectionAllocation entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   SectionAllocationDTO dto = new SectionAllocationDTO(entity);
   return Response.ok(dto).build();
}
 
Example 10
Source Project: SeaCloudsPlatform   Source File: EnforcementJobDAOJpa.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public EnforcementJob getByAgreementId(String agreementId) {

    TypedQuery<EnforcementJob> query = entityManager.createNamedQuery(EnforcementJob.QUERY_FIND_BY_AGREEMENT_ID,EnforcementJob.class);
    query.setParameter("agreementId", agreementId);

    EnforcementJob result;
    try {
        result = query.getSingleResult();

    } catch (NoResultException e) {
        logger.debug("Null will returned due to no Result found: " + e);
        return null;
    }

    return result;
}
 
Example 11
Source Project: container   Source File: CoreEndpointServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public WSDLEndpoint getWSDLEndpointForIa(final CsarId csarId, final QName nodeTypeImpl, final String iaName) {
    WSDLEndpoint endpoint = null;
    final TypedQuery<WSDLEndpoint> queryWSDLEndpoint = em.createQuery(
        "SELECT e FROM WSDLEndpoint e where e.csarId= :csarId and e.IaName = :IaName and e.TypeImplementation = :nodeTypeImpl", WSDLEndpoint.class);
    queryWSDLEndpoint.setParameter("csarId", csarId);
    queryWSDLEndpoint.setParameter("IaName", iaName);
    queryWSDLEndpoint.setParameter("nodeTypeImpl", nodeTypeImpl);

    try {
        endpoint = (WSDLEndpoint) queryWSDLEndpoint.getSingleResult();
    } catch (final NoResultException e) {
        LOG.info("No endpoint stored for requested IA.");
    }
    return endpoint;
}
 
Example 12
Source Project: keycloak   Source File: JpaRealmProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<GroupModel> searchForGroupByName(RealmModel realm, String search, Integer first, Integer max) {
    TypedQuery<String> query = em.createNamedQuery("getGroupIdsByNameContaining", String.class)
            .setParameter("realm", realm.getId())
            .setParameter("search", search);
    if(Objects.nonNull(first) && Objects.nonNull(max)) {
        query= query.setFirstResult(first).setMaxResults(max);
    }
    List<String> groups =  query.getResultList();
    if (Objects.isNull(groups)) return Collections.EMPTY_LIST;
    List<GroupModel> list = new ArrayList<>();
    for (String id : groups) {
        GroupModel groupById = session.realms().getGroupById(id, realm);
        while(Objects.nonNull(groupById.getParentId())) {
            groupById = session.realms().getGroupById(groupById.getParentId(), realm);
        }
        if(!list.contains(groupById)) {
            list.add(groupById);
        }
    }
    list.sort(Comparator.comparing(GroupModel::getName));

    return Collections.unmodifiableList(list);
}
 
Example 13
Source Project: container   Source File: PlanInstanceRepository.java    License: Apache License 2.0 6 votes vote down vote up
public PlanInstance findByCorrelationId(final String correlationId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();
        // Parameters
        final ParameterExpression<String> correlationIdParameter = cb.parameter(String.class);
        // Build the Criteria Query
        final CriteriaQuery<PlanInstance> cq = cb.createQuery(PlanInstance.class);
        final Root<PlanInstance> sti = cq.from(PlanInstance.class);
        cq.select(sti).where(cb.equal(sti.get("correlationId"), correlationIdParameter));
        // Create a TypedQuery
        final TypedQuery<PlanInstance> q = em.createQuery(cq);
        q.setParameter(correlationIdParameter, correlationId);
        // Execute
        PlanInstance result = q.getSingleResult();
        initializeInstance(result);
        return result;
    }
}
 
Example 14
Source Project: zstack   Source File: PortForwardingApiInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
private void checkIfAnotherVip(String vipUuid, String vmNicUuid) {
    String sql = "select nic.uuid from VmNicVO nic where nic.vmInstanceUuid = (select n.vmInstanceUuid from VmNicVO n where" +
            " n.uuid = :nicUuid)";
    TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
    q.setParameter("nicUuid", vmNicUuid);
    List<String> nicUuids = q.getResultList();

    sql = "select count(*) from VmNicVO nic, PortForwardingRuleVO pf where nic.uuid = pf.vmNicUuid and pf.vipUuid != :vipUuid and nic.uuid in (:nicUuids)";
    TypedQuery<Long> lq = dbf.getEntityManager().createQuery(sql, Long.class);
    lq.setParameter("vipUuid", vipUuid);
    lq.setParameter("nicUuids", nicUuids);
    long count = lq.getSingleResult();

    if (count > 0) {
        sql = "select vm from VmInstanceVO vm, VmNicVO nic where vm.uuid = nic.vmInstanceUuid and nic.uuid = :nicUuid";
        TypedQuery<VmInstanceVO> vq = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class);
        vq.setParameter("nicUuid", vmNicUuid);
        VmInstanceVO vm = vq.getSingleResult();

        throw new ApiMessageInterceptionException(operr("the VM[name:%s uuid:%s] already has port forwarding rules that have different VIPs than the one[uuid:%s]",
                        vm.getName(), vm.getUuid(), vipUuid));
    }
}
 
Example 15
Source Project: quarkus   Source File: JPAFunctionalityTestEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
private static void verifyJPANamedQuery(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    TypedQuery<Person> typedQuery = em.createNamedQuery(
            "get_person_by_name", Person.class);
    typedQuery.setParameter("name", "Quarkus");
    final Person singleResult = typedQuery.getSingleResult();

    if (!singleResult.getName().equals("Quarkus")) {
        throw new RuntimeException("Wrong result from named JPA query");
    }

    transaction.commit();
    em.close();
}
 
Example 16
Source Project: keycloak   Source File: JPAPermissionTicketStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<PermissionTicket> findByScope(String scopeId, String resourceServerId) {
    if (scopeId==null) {
        return Collections.emptyList();
    }

    // Use separate subquery to handle DB2 and MSSSQL
    TypedQuery<String> query = entityManager.createNamedQuery("findPermissionIdByScope", String.class);

    query.setFlushMode(FlushModeType.COMMIT);
    query.setParameter("scopeId", scopeId);
    query.setParameter("serverId", resourceServerId);

    List<String> result = query.getResultList();
    List<PermissionTicket> list = new LinkedList<>();
    PermissionTicketStore ticketStore = provider.getStoreFactory().getPermissionTicketStore();

    for (String id : result) {
        PermissionTicket ticket = ticketStore.findById(id, resourceServerId);
        if (Objects.nonNull(ticket)) {
            list.add(ticket);
        }
    }

    return list;
}
 
Example 17
Source Project: zstack   Source File: SecurityGroupManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
private List<HostRuleTO> calculateByHost() {
    String sql = "select nic.uuid from VmNicVO nic, VmInstanceVO vm, VmNicSecurityGroupRefVO ref, SecurityGroupVO sg" +
            " where nic.uuid = ref.vmNicUuid and nic.vmInstanceUuid = vm.uuid"+
            " and ref.securityGroupUuid = sg.uuid and sg.state in (:sgState)" +
            " and vm.hostUuid in (:hostUuids) and vm.state in (:vmStates)";
    TypedQuery<String> insgQuery = dbf.getEntityManager().createQuery(sql, String.class);
    insgQuery.setParameter("hostUuids", hostUuids);
    insgQuery.setParameter("vmStates", vmStates);
    insgQuery.setParameter("sgState", sgStates);
    List<String> nicsInSg = insgQuery.getResultList();

    sql = "select nic.uuid from VmNicVO nic, VmInstanceVO vm where nic.vmInstanceUuid = vm.uuid" +
            " and vm.hostUuid in (:hostUuids) and vm.state in (:vmStates)";
    TypedQuery<String> allq = dbf.getEntityManager().createQuery(sql, String.class);
    allq.setParameter("hostUuids", hostUuids);
    allq.setParameter("vmStates", vmStates);
    List<String> allNics = allq.getResultList();
    allNics.removeAll(nicsInSg);
    List<String> nicsOutSg = allNics;

    List<HostRuleTO> ret = new ArrayList<HostRuleTO>();
    if (!nicsInSg.isEmpty()) {
        vmNicUuids = nicsInSg.stream().distinct().collect(Collectors.toList());
        ret.addAll(calculateByVmNic());
    }
    if (!nicsOutSg.isEmpty()) {
        Collection<HostRuleTO> toRemove = createRulePlaceHolder(nicsOutSg, null);
        for (HostRuleTO hto : toRemove) {
            hto.setActionCodeForAllSecurityGroupRuleTOs(SecurityGroupRuleTO.ACTION_CODE_DELETE_CHAIN);
        }
        //ret.addAll(toRemove);
        ret = mergeMultiHostRuleTO(ret, toRemove);
    }

    return ret;
}
 
Example 18
Source Project: syncope   Source File: JPAReportDAO.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
@Override
public List<Report> findByTemplate(final ReportTemplate template) {
    TypedQuery<Report> query = entityManager().createQuery(
            "SELECT e FROM " + JPAReport.class.getSimpleName() + " e "
            + "WHERE e.template=:template", Report.class);
    query.setParameter("template", template);
    return query.getResultList();
}
 
Example 19
Source Project: monolith   Source File: EventEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, EventDTO dto)
{
   TypedQuery<Event> findByIdQuery = em.createQuery("SELECT DISTINCT e FROM Event e LEFT JOIN FETCH e.mediaItem LEFT JOIN FETCH e.category WHERE e.id = :entityId ORDER BY e.id", Event.class);
   findByIdQuery.setParameter("entityId", id);
   Event entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   entity = dto.fromDTO(entity, em);
   try
   {
      entity = em.merge(entity);
   }
   catch (OptimisticLockException e)
   {
      return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
   }
   return Response.noContent().build();
}
 
Example 20
Source Project: monolith   Source File: NestedMediaItemDTO.java    License: Apache License 2.0 5 votes vote down vote up
public MediaItem fromDTO(MediaItem entity, EntityManager em)
{
   if (entity == null)
   {
      entity = new MediaItem();
   }
   if (this.id != null)
   {
      TypedQuery<MediaItem> findByIdQuery = em
            .createQuery(
                  "SELECT DISTINCT m FROM MediaItem m WHERE m.id = :entityId",
                  MediaItem.class);
      findByIdQuery.setParameter("entityId", this.id);
      try
      {
         entity = findByIdQuery.getSingleResult();
      }
      catch (javax.persistence.NoResultException nre)
      {
         entity = null;
      }
      return entity;
   }
   entity.setMediaType(this.mediaType);
   entity.setUrl(this.url);
   entity = em.merge(entity);
   return entity;
}
 
Example 21
public List<Quiz> getRandomQuizzes(int n, long categoryId){

        TypedQuery<Long> sizeQuery= em.createQuery(
                "select count(q) from Quiz q where q.subCategory.parent.id=?1", Long.class);
        sizeQuery.setParameter(1, categoryId);
        long size = sizeQuery.getSingleResult();

        if(n > size){
            throw new IllegalArgumentException("Cannot choose " + n + " unique quizzes out of the " + size + " existing");
        }

        Random random = new Random();

        List<Quiz> quizzes = new ArrayList<>();
        Set<Integer> chosen = new HashSet<>();

        while(chosen.size() < n) {

            int k = random.nextInt((int)size);
            if(chosen.contains(k)){
                continue;
            }
            chosen.add(k);

            TypedQuery<Quiz> query = em.createQuery(
                    "select q from Quiz q where q.subCategory.parent.id=?1", Quiz.class);
            query.setParameter(1, categoryId);
            query.setMaxResults(1);
            query.setFirstResult(k);

            quizzes.add(query.getSingleResult());
        }


        return  quizzes;
    }
 
Example 22
Source Project: keycloak   Source File: JPAPolicyStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
    TypedQuery<PolicyEntity> query = entityManager.createNamedQuery("findPolicyIdByResource", PolicyEntity.class);

    query.setFlushMode(FlushModeType.COMMIT);
    query.setParameter("resourceId", resourceId);
    query.setParameter("serverId", resourceServerId);

    StoreFactory storeFactory = provider.getStoreFactory();

    query.getResultList().stream()
            .map(entity -> new PolicyAdapter(entity, entityManager, storeFactory))
            .forEach(consumer::accept);
}
 
Example 23
Source Project: syncope   Source File: JPAPlainSchemaDAO.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T extends PlainAttr<?>> List<T> findAttrs(final PlainSchema schema, final Class<T> reference) {
    TypedQuery<T> query = entityManager().createQuery(
            "SELECT e FROM " + JPAPlainAttrDAO.getEntityReference(reference).getSimpleName()
            + " e WHERE e.schema=:schema", reference);
    query.setParameter("schema", schema);

    return query.getResultList();
}
 
Example 24
Source Project: syncope   Source File: JPAPolicyDAO.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<AccountPolicy> findByResource(final ExternalResource resource) {
    TypedQuery<AccountPolicy> query = entityManager().createQuery(
            "SELECT e FROM " + JPAAccountPolicy.class.getSimpleName() + " e "
            + "WHERE :resource MEMBER OF e.resources", AccountPolicy.class);
    query.setParameter("resource", resource);

    return query.getResultList();
}
 
Example 25
Source Project: keycloak   Source File: JpaUserFederatedStorageProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Set<GroupModel> getGroups(RealmModel realm, String userId) {
    Set<GroupModel> set = new HashSet<>();
    TypedQuery<FederatedUserGroupMembershipEntity> query = em.createNamedQuery("feduserGroupMembership", FederatedUserGroupMembershipEntity.class);
    query.setParameter("userId", userId);
    List<FederatedUserGroupMembershipEntity> results = query.getResultList();
    if (results.size() == 0) return set;
    for (FederatedUserGroupMembershipEntity entity : results) {
        GroupModel group = realm.getGroupById(entity.getGroupId());
        set.add(group);
    }
    return set;
}
 
Example 26
Source Project: zstack   Source File: EipApiInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
private void checkIfVmAlreadyHasVipNetwork(String vmUuid, VipVO vip) {
    String sql = "select count(*) from VmNicVO nic, VmInstanceVO vm where nic.vmInstanceUuid = vm.uuid" +
            " and vm.uuid = :vmUuid and nic.l3NetworkUuid = :vipL3Uuid";
    TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class);
    q.setParameter("vmUuid", vmUuid);
    q.setParameter("vipL3Uuid", vip.getL3NetworkUuid());
    Long c = q.getSingleResult();
    if (c > 0) {
        throw new ApiMessageInterceptionException(argerr("the vm[uuid:%s] that the EIP is about to attach is already on the public network[uuid:%s] from which" +
                        " the vip[uuid:%s, name:%s, ip:%s] comes", vmUuid, vip.getL3NetworkUuid(), vip.getUuid(), vip.getName(), vip.getIp()));
    }
}
 
Example 27
Source Project: container   Source File: CoreEndpointServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
/**
 * {@Inheritdoc}
 */
public List<RESTEndpoint> getRestEndpoints(final URI anyURI, String triggeringContainer, final CsarId csarId) {
    final ArrayList<RESTEndpoint> results = new ArrayList<>();

    /**
     * Create Query to retrieve RESTEndpoints identified by a URI and thorID
     *
     * @see RESTEndpoint#getEndpointForPath
     **/
    final TypedQuery<RESTEndpoint> getRestEndpointsQuery = this.em.createNamedQuery(RESTEndpoint.getEndpointForPath, RESTEndpoint.class);

    // Set Parameters
    getRestEndpointsQuery.setParameter("path", anyURI.getPath());
    getRestEndpointsQuery.setParameter("triggeringContainer", triggeringContainer);
    getRestEndpointsQuery.setParameter("csarId", csarId);

    // Get Query-Results and add them to the result list
    final
    // Result can only be a RESTEndpoint
        List<RESTEndpoint> queryResults = getRestEndpointsQuery.getResultList();
    for (final RESTEndpoint endpoint : queryResults) {
        results.add(endpoint);
    }
    return results;
}
 
Example 28
Source Project: joynr   Source File: GlobalCapabilitiesDirectoryEjb.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void touch(String clusterControllerId) {
    logger.debug("Touch called. Updating discovery entries from cluster controller with id {}",
                 clusterControllerId);
    String queryString = "FROM GlobalDiscoveryEntryPersisted gdep WHERE gdep.clusterControllerId = :clusterControllerId";
    long now = System.currentTimeMillis();
    TypedQuery<GlobalDiscoveryEntryPersisted> query = entityManager.createQuery(queryString,
                                                                                GlobalDiscoveryEntryPersisted.class);
    query.setParameter("clusterControllerId", clusterControllerId);
    for (GlobalDiscoveryEntryPersisted globalDiscoveryEntryPersisted : query.getResultList()) {
        globalDiscoveryEntryPersisted.setLastSeenDateMs(now);
        globalDiscoveryEntryPersisted.setExpiryDateMs(now + defaultExpiryTimeMs);
    }
}
 
Example 29
Source Project: SeaCloudsPlatform   Source File: EnforcementJobDAOJpa.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<IEnforcementJob> getAll() {
    TypedQuery<IEnforcementJob> query = entityManager.createNamedQuery(    "EnforcementJob.findAll", IEnforcementJob.class);

    List<IEnforcementJob> enforcementJob = new ArrayList<IEnforcementJob>();
    enforcementJob = query.getResultList();

    if (enforcementJob != null) {
        logger.debug("Number of enforcementJob:" + enforcementJob.size());
    } else {
        logger.debug("No Result found.");
    }

    return enforcementJob;
}
 
Example 30
Source Project: sample.daytrader7   Source File: TradeSLSBBean.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) {
    if (!TradeConfig.getUpdateQuotePrices()) {
        return new QuoteDataBean();
    }

    if (Log.doTrace()) {
        Log.trace("TradeSLSBBean:updateQuote", symbol, changeFactor);
    }

    TypedQuery<QuoteDataBean> q = entityManager.createNamedQuery("quoteejb.quoteForUpdate",QuoteDataBean.class);
    q.setParameter(1, symbol);
    QuoteDataBean quote = q.getSingleResult();

    BigDecimal oldPrice = quote.getPrice();
    BigDecimal openPrice = quote.getOpen();

    if (oldPrice.equals(TradeConfig.PENNY_STOCK_PRICE)) {
        changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER;
    } else if (oldPrice.compareTo(TradeConfig.MAXIMUM_STOCK_PRICE) > 0) {
        changeFactor = TradeConfig.MAXIMUM_STOCK_SPLIT_MULTIPLIER;
    }

    BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP);

    quote.setPrice(newPrice);
    quote.setChange(newPrice.subtract(openPrice).doubleValue());
    quote.setVolume(quote.getVolume() + sharesTraded);
    entityManager.merge(quote);

    context.getBusinessObject(TradeSLSBLocal.class).publishQuotePriceChange(quote, oldPrice, changeFactor, sharesTraded);
   
    return quote;
}