use of org.candlepin.dto.rules.v1.PoolDTO in project candlepin by candlepin.
the class OwnerResource method populateEntity.
/**
* Populates an entity that is to be created with data from the provided DTO.
*
* @param entity
* The entity instance to populate
*
* @param dto
* The DTO containing the data with which to populate the entity
*
* @throws IllegalArgumentException
* if either entity or dto are null
*/
@SuppressWarnings("checkstyle:methodlength")
protected void populateEntity(Pool entity, PoolDTO dto) {
if (entity == null) {
throw new IllegalArgumentException("entity is null");
}
if (dto == null) {
throw new IllegalArgumentException("dto is null");
}
if (dto.getId() != null) {
entity.setId(dto.getId());
}
if (dto.getStartDate() != null) {
entity.setStartDate(dto.getStartDate());
}
if (dto.getEndDate() != null) {
entity.setEndDate(dto.getEndDate());
}
if (dto.getQuantity() != null) {
entity.setQuantity(dto.getQuantity());
}
if (dto.getAttributes() != null) {
if (dto.getAttributes().isEmpty()) {
entity.setAttributes(Collections.emptyMap());
} else {
entity.setAttributes(dto.getAttributes());
}
}
if (dto.getProvidedProducts() != null) {
if (dto.getProvidedProducts().isEmpty()) {
entity.setProvidedProducts(Collections.emptySet());
} else {
Set<Product> products = new HashSet<>();
for (PoolDTO.ProvidedProductDTO providedProductDTO : dto.getProvidedProducts()) {
if (providedProductDTO != null) {
Product newProd = findProduct(entity.getOwner(), providedProductDTO.getProductId());
products.add(newProd);
}
}
entity.setProvidedProducts(products);
}
}
if (dto.getDerivedProvidedProducts() != null) {
if (dto.getDerivedProvidedProducts().isEmpty()) {
entity.setDerivedProvidedProducts(Collections.emptySet());
} else {
Set<Product> derivedProducts = new HashSet<>();
for (PoolDTO.ProvidedProductDTO derivedProvidedProductDTO : dto.getDerivedProvidedProducts()) {
if (derivedProvidedProductDTO != null) {
Product newDerivedProd = findProduct(entity.getOwner(), derivedProvidedProductDTO.getProductId());
derivedProducts.add(newDerivedProd);
}
}
entity.setDerivedProvidedProducts(derivedProducts);
}
}
if (dto.getBranding() != null) {
if (dto.getBranding().isEmpty()) {
entity.setBranding(Collections.emptySet());
} else {
Set<Branding> branding = new HashSet<>();
for (BrandingDTO brandingDTO : dto.getBranding()) {
if (brandingDTO != null) {
branding.add(new Branding(brandingDTO.getProductId(), brandingDTO.getType(), brandingDTO.getName()));
}
}
entity.setBranding(branding);
}
}
}
use of org.candlepin.dto.rules.v1.PoolDTO 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.dto.rules.v1.PoolDTO in project candlepin by candlepin.
the class QuantityRules method getSuggestedQuantities.
/**
* Calculates the suggested quantities for many pools in one call. This allows for
* performant list pools queries with large numbers of pools and a large amount of
* entitlements to serialize.
*
* Map returned will map each pool ID to the suggested quantities for it. Every pool
* provided should have it's ID present in the result.
*
* @param pools
* @param c
* @param date
* @return suggested quantities for all pools requested
*/
@SuppressWarnings("checkstyle:indentation")
public Map<String, SuggestedQuantity> getSuggestedQuantities(List<Pool> pools, Consumer c, Date date) {
JsonJsContext args = new JsonJsContext(mapper);
Stream<PoolDTO> poolStream = pools == null ? Stream.empty() : pools.stream().map(this.translator.getStreamMapper(Pool.class, PoolDTO.class));
Stream<EntitlementDTO> entStream = c.getEntitlements() == null ? Stream.empty() : c.getEntitlements().stream().filter(ent -> ent.isValidOnDate(date)).map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class));
args.put("pools", poolStream.collect(Collectors.toSet()));
args.put("consumer", this.translator.translate(c, ConsumerDTO.class));
args.put("validEntitlements", entStream.collect(Collectors.toSet()));
args.put("log", log, false);
args.put("guestIds", c.getGuestIds());
String json = jsRules.runJsFunction(String.class, "get_suggested_quantities", args);
Map<String, SuggestedQuantity> resultMap;
TypeReference<Map<String, SuggestedQuantity>> typeref = new TypeReference<Map<String, SuggestedQuantity>>() {
};
try {
resultMap = mapper.toObject(json, typeref);
} catch (Exception e) {
throw new RuleExecutionException(e);
}
return resultMap;
}
use of org.candlepin.dto.rules.v1.PoolDTO in project candlepin by candlepin.
the class EntitlementRules method filterPools.
@Override
@SuppressWarnings("checkstyle:indentation")
public List<Pool> filterPools(Consumer consumer, List<Pool> pools, boolean showAll) {
JsonJsContext args = new JsonJsContext(objectMapper);
Map<String, ValidationResult> resultMap = new HashMap<>();
ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
if (!ctype.isType(ConsumerTypeEnum.SHARE)) {
Stream<PoolDTO> poolStream = pools == null ? Stream.empty() : pools.stream().map(this.translator.getStreamMapper(Pool.class, PoolDTO.class));
Stream<EntitlementDTO> entStream = consumer.getEntitlements() == null ? Stream.empty() : consumer.getEntitlements().stream().map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class));
args.put("consumer", this.translator.translate(consumer, ConsumerDTO.class));
args.put("hostConsumer", this.translator.translate(getHost(consumer, pools), ConsumerDTO.class));
args.put("consumerEntitlements", entStream.collect(Collectors.toSet()));
args.put("standalone", config.getBoolean(ConfigProperties.STANDALONE));
args.put("pools", poolStream.collect(Collectors.toSet()));
args.put("caller", CallerType.LIST_POOLS.getLabel());
args.put("log", log, false);
String json = jsRules.runJsFunction(String.class, "validate_pools_list", args);
TypeReference<Map<String, ValidationResult>> typeref = new TypeReference<Map<String, ValidationResult>>() {
};
try {
resultMap = objectMapper.toObject(json, typeref);
} catch (Exception e) {
throw new RuleExecutionException(e);
}
}
List<Pool> filteredPools = new LinkedList<>();
for (Pool pool : pools) {
ValidationResult result;
if (ctype.isType(ConsumerTypeEnum.SHARE)) {
result = new ValidationResult();
resultMap.put(pool.getId(), result);
validatePoolSharingEligibility(result, pool);
} else {
result = resultMap.get(pool.getId());
}
finishValidation(result, pool, 1);
if (result.isSuccessful() && (!result.hasWarnings() || showAll)) {
filteredPools.add(pool);
} else if (log.isDebugEnabled()) {
log.debug("Omitting pool due to failed rules: " + pool.getId());
if (result.hasErrors()) {
log.debug("\tErrors: " + result.getErrors());
}
if (result.hasWarnings()) {
log.debug("\tWarnings: " + result.getWarnings());
}
}
}
return filteredPools;
}
use of org.candlepin.dto.rules.v1.PoolDTO 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