use of org.candlepin.resteasy.parameter.KeyValueParameter in project candlepin by candlepin.
the class ConsumerCurator method searchOwnerConsumers.
@SuppressWarnings("checkstyle:indentation")
public CandlepinQuery<Consumer> searchOwnerConsumers(Owner owner, String userName, Collection<ConsumerType> types, List<String> uuids, List<String> hypervisorIds, List<KeyValueParameter> factFilters, List<String> skus, List<String> subscriptionIds, List<String> contracts) {
DetachedCriteria crit = super.createSecureDetachedCriteria();
if (owner != null) {
crit.add(Restrictions.eq("ownerId", owner.getId()));
}
if (userName != null && !userName.isEmpty()) {
crit.add(Restrictions.eq("username", userName));
}
if (types != null && !types.isEmpty()) {
Collection<String> typeIds = types.stream().filter(t -> t.getId() != null).map(t -> t.getId()).collect(Collectors.toList());
crit.add(CPRestrictions.in("typeId", typeIds));
}
if (uuids != null && !uuids.isEmpty()) {
crit.add(CPRestrictions.in("uuid", uuids));
}
if (hypervisorIds != null && !hypervisorIds.isEmpty()) {
// Cannot use Restrictions.in here because hypervisorId is case insensitive
Set<Criterion> ors = new HashSet<>();
for (String hypervisorId : hypervisorIds) {
ors.add(Restrictions.eq("hvsr.hypervisorId", hypervisorId.toLowerCase()));
}
crit.createAlias("hypervisorId", "hvsr");
crit.add(Restrictions.or(ors.toArray(new Criterion[ors.size()])));
}
if (factFilters != null && !factFilters.isEmpty()) {
// Process the filters passed for the attributes
FilterBuilder factFilter = new FactFilterBuilder();
for (KeyValueParameter filterParam : factFilters) {
factFilter.addAttributeFilter(filterParam.key(), filterParam.value());
}
factFilter.applyTo(crit);
}
boolean hasSkus = (skus != null && !skus.isEmpty());
boolean hasSubscriptionIds = (subscriptionIds != null && !subscriptionIds.isEmpty());
boolean hasContractNumbers = (contracts != null && !contracts.isEmpty());
if (hasSkus || hasSubscriptionIds || hasContractNumbers) {
if (hasSkus) {
for (String sku : skus) {
DetachedCriteria subCrit = DetachedCriteria.forClass(Consumer.class, "subquery_consumer");
if (owner != null) {
subCrit.add(Restrictions.eq("ownerId", owner.getId()));
}
subCrit.createCriteria("entitlements").createCriteria("pool").createCriteria("product").createAlias("attributes", "attrib").add(Restrictions.eq("id", sku)).add(Restrictions.eq("attrib.indices", "type")).add(Restrictions.eq("attrib.elements", "MKT"));
subCrit.add(Restrictions.eqProperty("this.id", "subquery_consumer.id"));
crit.add(Subqueries.exists(subCrit.setProjection(Projections.property("subquery_consumer.name"))));
}
}
if (hasSubscriptionIds) {
for (String subId : subscriptionIds) {
DetachedCriteria subCrit = DetachedCriteria.forClass(Consumer.class, "subquery_consumer");
if (owner != null) {
subCrit.add(Restrictions.eq("ownerId", owner.getId()));
}
subCrit.createCriteria("entitlements").createCriteria("pool").createCriteria("sourceSubscription").add(Restrictions.eq("subscriptionId", subId));
subCrit.add(Restrictions.eqProperty("this.id", "subquery_consumer.id"));
crit.add(Subqueries.exists(subCrit.setProjection(Projections.property("subquery_consumer.name"))));
}
}
if (hasContractNumbers) {
for (String contract : contracts) {
DetachedCriteria subCrit = DetachedCriteria.forClass(Consumer.class, "subquery_consumer");
if (owner != null) {
subCrit.add(Restrictions.eq("ownerId", owner.getId()));
}
subCrit.createCriteria("entitlements").createCriteria("pool").add(Restrictions.eq("contractNumber", contract));
subCrit.add(Restrictions.eqProperty("this.id", "subquery_consumer.id"));
crit.add(Subqueries.exists(subCrit.setProjection(Projections.property("subquery_consumer.name"))));
}
}
}
return this.cpQueryFactory.<Consumer>buildQuery(this.currentSession(), crit);
}
use of org.candlepin.resteasy.parameter.KeyValueParameter in project candlepin by candlepin.
the class OwnerResource method listPools.
/**
* Retrieves a list of Pools for an Owner
*
* @param ownerKey id of the owner whose entitlement pools are sought.
* @param matches Find pools matching the given pattern in a variety of fields.
* * and ? wildcards are supported.
* @return a list of Pool objects
* @httpcode 400
* @httpcode 404
* @httpcode 200
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{owner_key}/pools")
@SuppressWarnings("checkstyle:indentation")
@ApiOperation(notes = "Retrieves a list of Pools for an Owner", value = "List Pools")
@ApiResponses({ @ApiResponse(code = 404, message = "Owner not found"), @ApiResponse(code = 400, message = "Invalid request") })
public List<PoolDTO> listPools(@PathParam("owner_key") @Verify(value = Owner.class, subResource = SubResource.POOLS) String ownerKey, @QueryParam("consumer") String consumerUuid, @QueryParam("activation_key") String activationKeyName, @QueryParam("product") String productId, @QueryParam("subscription") String subscriptionId, @ApiParam("Include pools that are not suited to the unit's facts.") @QueryParam("listall") @DefaultValue("false") boolean listAll, @ApiParam("Date to use as current time for lookup criteria. Defaults" + " to current date if not specified.") @QueryParam("activeon") @DefaultValue(DateFormat.NOW) @DateFormat Date activeOn, @ApiParam("Find pools matching the given pattern in a variety of fields;" + " * and ? wildcards are supported; may be specified multiple times") @QueryParam("matches") List<String> matches, @ApiParam("The attributes to return based on the specified types.") @QueryParam("attribute") @CandlepinParam(type = KeyValueParameter.class) List<KeyValueParameter> attrFilters, @ApiParam("When set to true, it will add future dated pools to the result, " + "based on the activeon date.") @QueryParam("add_future") @DefaultValue("false") boolean addFuture, @ApiParam("When set to true, it will return only future dated pools to the result, " + "based on the activeon date.") @QueryParam("only_future") @DefaultValue("false") boolean onlyFuture, @ApiParam("Will only return pools with a start date after the supplied date. " + "Overrides the activeOn date.") @QueryParam("after") @DateFormat Date after, @ApiParam("One or more pool IDs to use to filter the output; only pools with IDs matching " + "those provided will be returned; may be specified multiple times") @QueryParam("poolid") List<String> poolIds, @Context Principal principal, @Context PageRequest pageRequest) {
Owner owner = findOwnerByKey(ownerKey);
Consumer c = null;
if (consumerUuid != null) {
c = consumerCurator.findByUuid(consumerUuid);
if (c == null) {
throw new NotFoundException(i18n.tr("Unit: {0} not found", consumerUuid));
}
if (!c.getOwnerId().equals(owner.getId())) {
throw new BadRequestException("Consumer specified does not belong to owner on path");
}
if (!principal.canAccess(c, SubResource.NONE, Access.READ_ONLY)) {
throw new ForbiddenException(i18n.tr("User {0} cannot access consumer {1}", principal.getPrincipalName(), c.getUuid()));
}
}
ActivationKey key = null;
if (activationKeyName != null) {
key = activationKeyCurator.lookupForOwner(activationKeyName, owner);
if (key == null) {
throw new BadRequestException(i18n.tr("ActivationKey with id {0} could not be found.", activationKeyName));
}
}
if (addFuture && onlyFuture) {
throw new BadRequestException(i18n.tr("The flags add_future and only_future cannot be used at the same time."));
}
if (after != null && (addFuture || onlyFuture)) {
throw new BadRequestException(i18n.tr("The flags add_future and only_future cannot be used with the parameter after."));
}
if (after != null) {
activeOn = null;
}
// Process the filters passed for the attributes
PoolFilterBuilder poolFilters = new PoolFilterBuilder();
for (KeyValueParameter filterParam : attrFilters) {
poolFilters.addAttributeFilter(filterParam.key(), filterParam.value());
}
if (matches != null) {
matches.stream().filter(elem -> elem != null && !elem.isEmpty()).forEach(elem -> poolFilters.addMatchesFilter(elem));
}
if (poolIds != null && !poolIds.isEmpty()) {
poolFilters.addIdFilters(poolIds);
}
Page<List<Pool>> page = poolManager.listAvailableEntitlementPools(c, key, owner.getId(), productId, subscriptionId, activeOn, listAll, poolFilters, pageRequest, addFuture, onlyFuture, after);
List<Pool> poolList = page.getPageData();
calculatedAttributesUtil.setCalculatedAttributes(poolList, activeOn);
calculatedAttributesUtil.setQuantityAttributes(poolList, c, activeOn);
// Store the page for the LinkHeaderResponseFilter
ResteasyProviderFactory.pushContext(Page.class, page);
List<PoolDTO> poolDTOs = new ArrayList<>();
for (Pool pool : poolList) {
poolDTOs.add(translator.translate(pool, PoolDTO.class));
}
return poolDTOs;
}
use of org.candlepin.resteasy.parameter.KeyValueParameter in project candlepin by candlepin.
the class ConsumerResourceTest method testAsyncExport.
@Test
public void testAsyncExport() {
CdnCurator mockCdnCurator = mock(CdnCurator.class);
ManifestManager manifestManager = mock(ManifestManager.class);
ConsumerResource cr = new ConsumerResource(mockConsumerCurator, mockConsumerTypeCurator, null, null, null, null, null, null, i18n, null, null, null, null, null, null, null, mockOwnerCurator, null, null, null, null, null, null, this.config, null, mockCdnCurator, null, null, manifestManager, null, this.factValidator, null, consumerEnricher, migrationProvider, translator);
List<KeyValueParameter> extParams = new ArrayList<>();
Owner owner = this.createOwner();
owner.setId(TestUtil.randomString());
when(mockOwnerCurator.findOwnerById(eq(owner.getId()))).thenReturn(owner);
ConsumerType ctype = this.mockConsumerType(new ConsumerType(ConsumerType.ConsumerTypeEnum.CANDLEPIN));
Consumer consumer = this.createConsumer(owner, ctype);
Cdn cdn = new Cdn("cdn-label", "test", "url");
when(mockCdnCurator.lookupByLabel(eq(cdn.getLabel()))).thenReturn(cdn);
cr.exportDataAsync(null, consumer.getUuid(), cdn.getLabel(), "prefix", cdn.getUrl(), extParams);
verify(manifestManager).generateManifestAsync(eq(consumer.getUuid()), eq(owner.getKey()), eq(cdn.getLabel()), eq("prefix"), eq(cdn.getUrl()), any(Map.class));
}
use of org.candlepin.resteasy.parameter.KeyValueParameter in project candlepin by candlepin.
the class OwnerResourceTest method createKeyValueParam.
@QueryParam("test-attr")
@CandlepinParam(type = KeyValueParameter.class)
private KeyValueParameter createKeyValueParam(String key, String val) throws Exception {
// Can't create the KeyValueParam directly as the parse method
// is package protected -- create one via the unmarshaller so we don't have to
// change the visibility of the parse method.
Annotation[] annotations = this.getClass().getDeclaredMethod("createKeyValueParam", String.class, String.class).getAnnotations();
CandlepinParameterUnmarshaller unmarshaller = new CandlepinParameterUnmarshaller();
unmarshaller.setAnnotations(annotations);
return (KeyValueParameter) unmarshaller.fromString(key + ":" + val);
}
use of org.candlepin.resteasy.parameter.KeyValueParameter in project candlepin by candlepin.
the class OwnerResourceTest method testCanFilterOutDevPoolsByAttribute.
@Test
public void testCanFilterOutDevPoolsByAttribute() throws Exception {
Principal principal = setupPrincipal(owner, Access.ALL);
Product p = this.createProduct(owner);
Pool pool1 = TestUtil.createPool(owner, p);
pool1.setAttribute(Pool.Attributes.DEVELOPMENT_POOL, "true");
poolCurator.create(pool1);
Product p2 = this.createProduct(owner);
Pool pool2 = TestUtil.createPool(owner, p2);
poolCurator.create(pool2);
List<KeyValueParameter> params = new ArrayList<>();
List<PoolDTO> pools = ownerResource.listPools(owner.getKey(), null, null, null, null, true, null, null, params, false, false, null, null, principal, null);
assertEquals(2, pools.size());
params = new ArrayList<>();
params.add(createKeyValueParam(Pool.Attributes.DEVELOPMENT_POOL, "!true"));
pools = ownerResource.listPools(owner.getKey(), null, null, null, null, true, null, null, params, false, false, null, null, principal, null);
assertEquals(1, pools.size());
assertModelEqualsDTO(pool2, pools.get(0));
}
Aggregations