Search in sources :

Example 11 with PathParam

use of javax.ws.rs.PathParam in project keycloak by keycloak.

the class ResourceSetService method getScopes.

@Path("{id}/scopes")
@GET
@NoCache
@Produces("application/json")
public Response getScopes(@PathParam("id") String id) {
    requireView();
    StoreFactory storeFactory = authorization.getStoreFactory();
    Resource model = storeFactory.getResourceStore().findById(id, resourceServer.getId());
    if (model == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    List<ScopeRepresentation> scopes = model.getScopes().stream().map(scope -> {
        ScopeRepresentation representation = new ScopeRepresentation();
        representation.setId(scope.getId());
        representation.setName(scope.getName());
        return representation;
    }).collect(Collectors.toList());
    if (model.getType() != null && !model.getOwner().equals(resourceServer.getId())) {
        ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
        for (Resource typed : resourceStore.findByType(model.getType(), resourceServer.getId())) {
            if (typed.getOwner().equals(resourceServer.getId()) && !typed.getId().equals(model.getId())) {
                scopes.addAll(typed.getScopes().stream().map(model1 -> {
                    ScopeRepresentation scope = new ScopeRepresentation();
                    scope.setId(model1.getId());
                    scope.setName(model1.getName());
                    String iconUri = model1.getIconUri();
                    if (iconUri != null) {
                        scope.setIconUri(iconUri);
                    }
                    return scope;
                }).filter(scopeRepresentation -> !scopes.contains(scopeRepresentation)).collect(Collectors.toList()));
            }
        }
    }
    return Response.ok(scopes).build();
}
Also used : ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) BiFunction(java.util.function.BiFunction) Path(javax.ws.rs.Path) OAuthErrorException(org.keycloak.OAuthErrorException) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ErrorResponseException(org.keycloak.services.ErrorResponseException) ModelToRepresentation.toRepresentation(org.keycloak.models.utils.ModelToRepresentation.toRepresentation) Map(java.util.Map) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) EnumMap(java.util.EnumMap) Collection(java.util.Collection) Set(java.util.Set) PolicyStore(org.keycloak.authorization.store.PolicyStore) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) RepresentationToModel.toModel(org.keycloak.models.utils.RepresentationToModel.toModel) ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) PathParam(javax.ws.rs.PathParam) Scope(org.keycloak.authorization.model.Scope) GET(javax.ws.rs.GET) StoreFactory(org.keycloak.authorization.store.StoreFactory) Constants(org.keycloak.models.Constants) HashMap(java.util.HashMap) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) Status(javax.ws.rs.core.Response.Status) PathMatcher(org.keycloak.common.util.PathMatcher) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) Policy(org.keycloak.authorization.model.Policy) NoCache(org.jboss.resteasy.annotations.cache.NoCache) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) Resource(org.keycloak.authorization.model.Resource) AdminEventBuilder(org.keycloak.services.resources.admin.AdminEventBuilder) Resource(org.keycloak.authorization.model.Resource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ResourceStore(org.keycloak.authorization.store.ResourceStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 12 with PathParam

use of javax.ws.rs.PathParam in project keycloak by keycloak.

the class UserResource method getOfflineSessions.

/**
 * Get offline sessions associated with the user and client
 *
 * @return
 */
@Path("offline-sessions/{clientUuid}")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Stream<UserSessionRepresentation> getOfflineSessions(@PathParam("clientUuid") final String clientUuid) {
    auth.users().requireView(user);
    ClientModel client = realm.getClientById(clientUuid);
    if (client == null) {
        throw new NotFoundException("Client not found");
    }
    return new UserSessionManager(session).findOfflineSessionsStream(realm, user).map(session -> toUserSessionRepresentation(session, clientUuid)).filter(Objects::nonNull);
}
Also used : UserSessionManager(org.keycloak.services.managers.UserSessionManager) EmailTemplateProvider(org.keycloak.email.EmailTemplateProvider) RedirectUtils(org.keycloak.protocol.oidc.utils.RedirectUtils) Produces(javax.ws.rs.Produces) USER_API(org.keycloak.userprofile.UserProfileContext.USER_API) MediaType(javax.ws.rs.core.MediaType) ErrorResponseException(org.keycloak.services.ErrorResponseException) Validation(org.keycloak.services.validation.Validation) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) UserConsentRepresentation(org.keycloak.representations.idm.UserConsentRepresentation) UriBuilder(javax.ws.rs.core.UriBuilder) Time(org.keycloak.common.util.Time) UserCredentialModel(org.keycloak.models.UserCredentialModel) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Set(java.util.Set) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) Stream(java.util.stream.Stream) LoginActionsService(org.keycloak.services.resources.LoginActionsService) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) WebApplicationException(javax.ws.rs.WebApplicationException) GET(javax.ws.rs.GET) Constants(org.keycloak.models.Constants) ArrayList(java.util.ArrayList) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) UserModel(org.keycloak.models.UserModel) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) UserConsentManager(org.keycloak.services.managers.UserConsentManager) ProviderFactory(org.keycloak.provider.ProviderFactory) UserManager(org.keycloak.models.UserManager) Properties(java.util.Properties) CredentialModel(org.keycloak.credential.CredentialModel) ExecuteActionsActionToken(org.keycloak.authentication.actiontoken.execactions.ExecuteActionsActionToken) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) EventType(org.keycloak.events.EventType) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) IMPERSONATOR_USERNAME(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_USERNAME) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ValidationException(org.keycloak.userprofile.ValidationException) ResourceType(org.keycloak.events.admin.ResourceType) Path(javax.ws.rs.Path) GroupRepresentation(org.keycloak.representations.idm.GroupRepresentation) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) QueryParam(javax.ws.rs.QueryParam) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) DefaultValue(javax.ws.rs.DefaultValue) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) BadRequestException(javax.ws.rs.BadRequestException) URI(java.net.URI) AccountFormService(org.keycloak.services.resources.account.AccountFormService) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) IMPERSONATOR_ID(org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_ID) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ForbiddenException(org.keycloak.services.ForbiddenException) ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) UserProfile(org.keycloak.userprofile.UserProfile) PathParam(javax.ws.rs.PathParam) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) Profile(org.keycloak.common.Profile) Logger(org.jboss.logging.Logger) HashMap(java.util.HashMap) ServicesLogger(org.keycloak.services.ServicesLogger) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) MessageFormat(java.text.MessageFormat) HashSet(java.util.HashSet) EventBuilder(org.keycloak.events.EventBuilder) UserConsentModel(org.keycloak.models.UserConsentModel) EmailException(org.keycloak.email.EmailException) GroupModel(org.keycloak.models.GroupModel) LinkedList(java.util.LinkedList) ProfileHelper(org.keycloak.utils.ProfileHelper) Status(javax.ws.rs.core.Response.Status) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) POST(javax.ws.rs.POST) UserLoginFailureModel(org.keycloak.models.UserLoginFailureModel) UserSessionModel(org.keycloak.models.UserSessionModel) TimeUnit(java.util.concurrent.TimeUnit) NoCache(org.jboss.resteasy.annotations.cache.NoCache) UserSessionManager(org.keycloak.services.managers.UserSessionManager) ModelException(org.keycloak.models.ModelException) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ErrorResponse(org.keycloak.services.ErrorResponse) ClientModel(org.keycloak.models.ClientModel) Objects(java.util.Objects) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 13 with PathParam

use of javax.ws.rs.PathParam in project wildfly-swarm by wildfly-swarm.

the class BuilderImpl method verifyInterface.

private <T> void verifyInterface(Class<T> typeDef) {
    Method[] methods = typeDef.getMethods();
    // multiple verbs
    for (Method method : methods) {
        boolean hasHttpMethod = false;
        for (Annotation annotation : method.getAnnotations()) {
            boolean isHttpMethod = (annotation.annotationType().getAnnotation(HttpMethod.class) != null);
            if (!hasHttpMethod && isHttpMethod) {
                hasHttpMethod = true;
            } else if (hasHttpMethod && isHttpMethod) {
                throw new RestClientDefinitionException("Ambiguous @Httpmethod defintion on type " + typeDef);
            }
        }
    }
    // invalid parameter
    Path classPathAnno = typeDef.getAnnotation(Path.class);
    final Set<String> classLevelVariables = new HashSet<>();
    ResteasyUriBuilder classTemplate = null;
    if (classPathAnno != null) {
        classTemplate = (ResteasyUriBuilder) UriBuilder.fromUri(classPathAnno.value());
        classLevelVariables.addAll(classTemplate.getPathParamNamesInDeclarationOrder());
    }
    ResteasyUriBuilder template;
    for (Method method : methods) {
        Path methodPathAnno = method.getAnnotation(Path.class);
        if (methodPathAnno != null) {
            template = classPathAnno == null ? (ResteasyUriBuilder) UriBuilder.fromUri(methodPathAnno.value()) : (ResteasyUriBuilder) UriBuilder.fromUri(classPathAnno.value() + "/" + methodPathAnno.value());
        } else {
            template = classTemplate;
        }
        if (template == null) {
            continue;
        }
        // it's not executed, so this can be anything - but a hostname needs to present
        template.host("localhost");
        Set<String> allVariables = new HashSet<>(template.getPathParamNamesInDeclarationOrder());
        Map<String, Object> paramMap = new HashMap<>();
        for (Parameter p : method.getParameters()) {
            PathParam pathParam = p.getAnnotation(PathParam.class);
            if (pathParam != null) {
                paramMap.put(pathParam.value(), "foobar");
            }
        }
        if (allVariables.size() != paramMap.size()) {
            throw new RestClientDefinitionException("Parameters and variables don't match on " + typeDef + "::" + method.getName());
        }
        try {
            template.resolveTemplates(paramMap, false).build();
        } catch (IllegalArgumentException ex) {
            throw new RestClientDefinitionException("Parameter names don't match variable names on " + typeDef + "::" + method.getName(), ex);
        }
    }
}
Also used : Path(javax.ws.rs.Path) HashMap(java.util.HashMap) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) RestClientDefinitionException(org.eclipse.microprofile.rest.client.RestClientDefinitionException) Annotation(java.lang.annotation.Annotation) ResteasyUriBuilder(org.jboss.resteasy.specimpl.ResteasyUriBuilder) Parameter(java.lang.reflect.Parameter) PathParam(javax.ws.rs.PathParam) HashSet(java.util.HashSet)

Example 14 with PathParam

use of javax.ws.rs.PathParam in project incubator-pulsar by apache.

the class TopicLookup method lookupTopicAsync.

@GET
@Path("{topic-domain}/{property}/{cluster}/{namespace}/{topic}")
@Produces(MediaType.APPLICATION_JSON)
public void lookupTopicAsync(@PathParam("topic-domain") String topicDomain, @PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("topic") @Encoded String encodedTopic, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative, @Suspended AsyncResponse asyncResponse) {
    String topicName = Codec.decode(encodedTopic);
    TopicDomain domain = null;
    try {
        domain = TopicDomain.getEnum(topicDomain);
    } catch (IllegalArgumentException e) {
        log.error("[{}] Invalid topic-domain {}", clientAppId(), topicDomain, e);
        throw new RestException(Status.METHOD_NOT_ALLOWED, "Unsupported topic domain " + topicDomain);
    }
    TopicName topic = TopicName.get(domain.value(), property, cluster, namespace, topicName);
    if (!pulsar().getBrokerService().getLookupRequestSemaphore().tryAcquire()) {
        log.warn("No broker was found available for topic {}", topic);
        asyncResponse.resume(new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
        return;
    }
    try {
        validateClusterOwnership(topic.getCluster());
        checkConnect(topic);
        validateGlobalNamespaceOwnership(topic.getNamespaceObject());
    } catch (WebApplicationException we) {
        // Validation checks failed
        log.error("Validation check failed: {}", we.getMessage());
        completeLookupResponseExceptionally(asyncResponse, we);
        return;
    } catch (Throwable t) {
        // Validation checks failed with unknown error
        log.error("Validation check failed: {}", t.getMessage(), t);
        completeLookupResponseExceptionally(asyncResponse, new RestException(t));
        return;
    }
    CompletableFuture<Optional<LookupResult>> lookupFuture = pulsar().getNamespaceService().getBrokerServiceUrlAsync(topic, authoritative);
    lookupFuture.thenAccept(optionalResult -> {
        if (optionalResult == null || !optionalResult.isPresent()) {
            log.warn("No broker was found available for topic {}", topic);
            completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
            return;
        }
        LookupResult result = optionalResult.get();
        // We have found either a broker that owns the topic, or a broker to which we should redirect the client to
        if (result.isRedirect()) {
            boolean newAuthoritative = this.isLeaderBroker();
            URI redirect;
            try {
                String redirectUrl = isRequestHttps() ? result.getLookupData().getHttpUrlTls() : result.getLookupData().getHttpUrl();
                checkNotNull(redirectUrl, "Redirected cluster's service url is not configured");
                redirect = new URI(String.format("%s%s%s?authoritative=%s", redirectUrl, "/lookup/v2/destination/", topic.getLookupName(), newAuthoritative));
            } catch (URISyntaxException | NullPointerException e) {
                log.error("Error in preparing redirect url for {}: {}", topic, e.getMessage(), e);
                completeLookupResponseExceptionally(asyncResponse, e);
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("Redirect lookup for topic {} to {}", topic, redirect);
            }
            completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.temporaryRedirect(redirect).build()));
        } else {
            // Found broker owning the topic
            if (log.isDebugEnabled()) {
                log.debug("Lookup succeeded for topic {} -- broker: {}", topic, result.getLookupData());
            }
            completeLookupResponseSuccessfully(asyncResponse, result.getLookupData());
        }
    }).exceptionally(exception -> {
        log.warn("Failed to lookup broker for topic {}: {}", topic, exception.getMessage(), exception);
        completeLookupResponseExceptionally(asyncResponse, exception);
        return null;
    });
}
Also used : PathParam(javax.ws.rs.PathParam) Encoded(javax.ws.rs.Encoded) TopicName(org.apache.pulsar.common.naming.TopicName) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) LookupType(org.apache.pulsar.common.api.proto.PulsarApi.CommandLookupTopicResponse.LookupType) CompletableFuture(java.util.concurrent.CompletableFuture) ApiResponses(io.swagger.annotations.ApiResponses) StringUtils(dlshade.org.apache.commons.lang3.StringUtils) ServerError(org.apache.pulsar.common.api.proto.PulsarApi.ServerError) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ByteBuf(io.netty.buffer.ByteBuf) DefaultValue(javax.ws.rs.DefaultValue) RestException(org.apache.pulsar.broker.web.RestException) NoSwaggerDocumentation(org.apache.pulsar.broker.web.NoSwaggerDocumentation) URI(java.net.URI) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) TopicDomain(org.apache.pulsar.common.naming.TopicDomain) Status(javax.ws.rs.core.Response.Status) Logger(org.slf4j.Logger) Commands.newLookupErrorResponse(org.apache.pulsar.common.api.Commands.newLookupErrorResponse) PulsarWebResource(org.apache.pulsar.broker.web.PulsarWebResource) AsyncResponse(javax.ws.rs.container.AsyncResponse) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) LookupData(org.apache.pulsar.common.lookup.data.LookupData) CompletionException(java.util.concurrent.CompletionException) PulsarService(org.apache.pulsar.broker.PulsarService) Suspended(javax.ws.rs.container.Suspended) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) Codec(org.apache.pulsar.common.util.Codec) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) Commands.newLookupResponse(org.apache.pulsar.common.api.Commands.newLookupResponse) TopicDomain(org.apache.pulsar.common.naming.TopicDomain) WebApplicationException(javax.ws.rs.WebApplicationException) Optional(java.util.Optional) RestException(org.apache.pulsar.broker.web.RestException) URI(java.net.URI) TopicName(org.apache.pulsar.common.naming.TopicName) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 15 with PathParam

use of javax.ws.rs.PathParam 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;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) ApiParam(io.swagger.annotations.ApiParam) CalculatedAttributesUtil(org.candlepin.resource.util.CalculatedAttributesUtil) EventSink(org.candlepin.audit.EventSink) MediaType(javax.ws.rs.core.MediaType) ImportRecordCurator(org.candlepin.model.ImportRecordCurator) PageRequest(org.candlepin.common.paging.PageRequest) ImporterException(org.candlepin.sync.ImporterException) ExporterMetadataCurator(org.candlepin.model.ExporterMetadataCurator) ActivationKeyCurator(org.candlepin.model.activationkeys.ActivationKeyCurator) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) DateFormat(org.candlepin.resteasy.DateFormat) HealEntireOrgJob(org.candlepin.pinsetter.tasks.HealEntireOrgJob) EventCurator(org.candlepin.model.EventCurator) Feed(org.jboss.resteasy.plugins.providers.atom.Feed) ActivationKeyDTO(org.candlepin.dto.api.v1.ActivationKeyDTO) SyncDataFormatException(org.candlepin.sync.SyncDataFormatException) ResourceMovedException(org.candlepin.common.exceptions.ResourceMovedException) UeberCertificateCurator(org.candlepin.model.UeberCertificateCurator) Set(java.util.Set) PoolManager(org.candlepin.controller.PoolManager) Access(org.candlepin.auth.Access) IseException(org.candlepin.common.exceptions.IseException) Type(org.candlepin.audit.Event.Type) OwnerServiceAdapter(org.candlepin.service.OwnerServiceAdapter) PoolDTO(org.candlepin.dto.api.v1.PoolDTO) Util(org.candlepin.util.Util) I18n(org.xnap.commons.i18n.I18n) Event(org.candlepin.audit.Event) Subscription(org.candlepin.model.dto.Subscription) GET(javax.ws.rs.GET) RefreshPoolsJob(org.candlepin.pinsetter.tasks.RefreshPoolsJob) KeyValueParameter(org.candlepin.resteasy.parameter.KeyValueParameter) ContentAccessCertServiceAdapter(org.candlepin.service.ContentAccessCertServiceAdapter) EventDTO(org.candlepin.dto.api.v1.EventDTO) ArrayList(java.util.ArrayList) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) Target(org.candlepin.audit.Event.Target) Entitlement(org.candlepin.model.Entitlement) StringTokenizer(java.util.StringTokenizer) Branding(org.candlepin.model.Branding) Api(io.swagger.annotations.Api) UpstreamConsumerDTO(org.candlepin.dto.api.v1.UpstreamConsumerDTO) UeberCertificateGenerator(org.candlepin.model.UeberCertificateGenerator) CandlepinException(org.candlepin.common.exceptions.CandlepinException) OwnerInfo(org.candlepin.model.OwnerInfo) ModelTranslator(org.candlepin.dto.ModelTranslator) ExporterMetadata(org.candlepin.model.ExporterMetadata) ServiceLevelValidator(org.candlepin.util.ServiceLevelValidator) Wrapped(org.jboss.resteasy.annotations.providers.jaxb.Wrapped) IOException(java.io.IOException) CandlepinQuery(org.candlepin.model.CandlepinQuery) File(java.io.File) EntitlementCurator(org.candlepin.model.EntitlementCurator) UndoImportsJob(org.candlepin.pinsetter.tasks.UndoImportsJob) CandlepinParam(org.candlepin.resteasy.parameter.CandlepinParam) ApiResponse(io.swagger.annotations.ApiResponse) ImportRecord(org.candlepin.model.ImportRecord) ActivationKey(org.candlepin.model.activationkeys.ActivationKey) EnvironmentDTO(org.candlepin.dto.api.v1.EnvironmentDTO) Date(java.util.Date) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) MultipartInput(org.jboss.resteasy.plugins.providers.multipart.MultipartInput) EntitlementFinderUtil(org.candlepin.resource.util.EntitlementFinderUtil) EntitlementFilterBuilder(org.candlepin.model.EntitlementFilterBuilder) ConflictOverrides(org.candlepin.sync.ConflictOverrides) ActivationKeyContentOverride(org.candlepin.model.activationkeys.ActivationKeyContentOverride) Transactional(com.google.inject.persist.Transactional) OwnerDTO(org.candlepin.dto.api.v1.OwnerDTO) ConflictException(org.candlepin.common.exceptions.ConflictException) ApiOperation(io.swagger.annotations.ApiOperation) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ConsumerTypeCurator(org.candlepin.model.ConsumerTypeCurator) DefaultValue(javax.ws.rs.DefaultValue) ContentOverrideValidator(org.candlepin.util.ContentOverrideValidator) Product(org.candlepin.model.Product) DELETE(javax.ws.rs.DELETE) NotFoundException(org.candlepin.common.exceptions.NotFoundException) UpstreamConsumer(org.candlepin.model.UpstreamConsumer) Context(javax.ws.rs.core.Context) OwnerManager(org.candlepin.controller.OwnerManager) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) EventAdapter(org.candlepin.audit.EventAdapter) GenericType(org.jboss.resteasy.util.GenericType) Page(org.candlepin.common.paging.Page) OwnerCurator(org.candlepin.model.OwnerCurator) EntitlementDTO(org.candlepin.dto.api.v1.EntitlementDTO) OwnerProductCurator(org.candlepin.model.OwnerProductCurator) ManifestFileServiceException(org.candlepin.sync.file.ManifestFileServiceException) ConsumerCurator(org.candlepin.model.ConsumerCurator) List(java.util.List) PersistenceException(javax.persistence.PersistenceException) ProductCurator(org.candlepin.model.ProductCurator) SourceSubscription(org.candlepin.model.SourceSubscription) PathParam(javax.ws.rs.PathParam) ConsumerDTO(org.candlepin.dto.api.v1.ConsumerDTO) Release(org.candlepin.model.Release) Verify(org.candlepin.auth.Verify) ManifestManager(org.candlepin.controller.ManifestManager) ConsumerType(org.candlepin.model.ConsumerType) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) ApiResponses(io.swagger.annotations.ApiResponses) ConfigProperties(org.candlepin.config.ConfigProperties) Pool(org.candlepin.model.Pool) UeberCertificate(org.candlepin.model.UeberCertificate) HashSet(java.util.HashSet) SubResource(org.candlepin.auth.SubResource) PoolType(org.candlepin.model.Pool.PoolType) Owner(org.candlepin.model.Owner) CollectionUtils(org.apache.commons.collections.CollectionUtils) BadRequestException(org.candlepin.common.exceptions.BadRequestException) BrandingDTO(org.candlepin.dto.api.v1.BrandingDTO) Environment(org.candlepin.model.Environment) Principal(org.candlepin.auth.Principal) LinkedList(java.util.LinkedList) Configuration(org.candlepin.common.config.Configuration) JobDetail(org.quartz.JobDetail) OwnerInfoCurator(org.candlepin.model.OwnerInfoCurator) ResolverUtil(org.candlepin.resource.util.ResolverUtil) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) EnvironmentCurator(org.candlepin.model.EnvironmentCurator) ConsumerTypeValidator(org.candlepin.resource.util.ConsumerTypeValidator) EventFactory(org.candlepin.audit.EventFactory) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ImportJob(org.candlepin.pinsetter.tasks.ImportJob) Level(ch.qos.logback.classic.Level) EntitlementCertificateCurator(org.candlepin.model.EntitlementCertificateCurator) PUT(javax.ws.rs.PUT) Consumer(org.candlepin.model.Consumer) Authorization(io.swagger.annotations.Authorization) Collections(java.util.Collections) ArrayUtils(org.apache.commons.lang.ArrayUtils) Owner(org.candlepin.model.Owner) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) ArrayList(java.util.ArrayList) NotFoundException(org.candlepin.common.exceptions.NotFoundException) PoolDTO(org.candlepin.dto.api.v1.PoolDTO) ActivationKey(org.candlepin.model.activationkeys.ActivationKey) UpstreamConsumer(org.candlepin.model.UpstreamConsumer) Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) KeyValueParameter(org.candlepin.resteasy.parameter.KeyValueParameter) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Pool(org.candlepin.model.Pool) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

PathParam (javax.ws.rs.PathParam)127 Path (javax.ws.rs.Path)105 GET (javax.ws.rs.GET)96 Produces (javax.ws.rs.Produces)96 Response (javax.ws.rs.core.Response)93 QueryParam (javax.ws.rs.QueryParam)82 List (java.util.List)72 MediaType (javax.ws.rs.core.MediaType)72 POST (javax.ws.rs.POST)71 DELETE (javax.ws.rs.DELETE)70 Consumes (javax.ws.rs.Consumes)66 Inject (javax.inject.Inject)62 Api (io.swagger.annotations.Api)60 ApiOperation (io.swagger.annotations.ApiOperation)59 Map (java.util.Map)59 ApiResponse (io.swagger.annotations.ApiResponse)58 ApiResponses (io.swagger.annotations.ApiResponses)57 Collectors (java.util.stream.Collectors)57 Logger (org.slf4j.Logger)52 LoggerFactory (org.slf4j.LoggerFactory)52