Search in sources :

Example 6 with QueryParam

use of javax.ws.rs.QueryParam in project jersey by jersey.

the class InjectLinkFieldDescriptor method extractQueryParams.

private static CharSequence extractQueryParams(AnnotatedMethod method) throws SecurityException {
    // append query parameters
    StringBuilder querySubString = new StringBuilder();
    int parameterIndex = 0;
    for (Annotation[] paramAnns : method.getParameterAnnotations()) {
        for (Annotation ann : paramAnns) {
            if (ann.annotationType() == QueryParam.class) {
                querySubString.append(((QueryParam) ann).value());
                querySubString.append(',');
            }
            if (ann.annotationType() == BeanParam.class) {
                Class<?> beanParamType = method.getParameterTypes()[parameterIndex];
                Field[] fields = beanParamType.getFields();
                for (Field field : fields) {
                    QueryParam queryParam = field.getAnnotation(QueryParam.class);
                    if (queryParam != null) {
                        querySubString.append(queryParam.value());
                        querySubString.append(',');
                    }
                }
                Method[] beanMethods = beanParamType.getMethods();
                for (Method beanMethod : beanMethods) {
                    QueryParam queryParam = beanMethod.getAnnotation(QueryParam.class);
                    if (queryParam != null) {
                        querySubString.append(queryParam.value());
                        querySubString.append(',');
                    }
                }
            }
        }
        parameterIndex++;
    }
    CharSequence result = "";
    if (querySubString.length() > 0) {
        result = querySubString.subSequence(0, querySubString.length() - 1);
    }
    return result;
}
Also used : Field(java.lang.reflect.Field) QueryParam(javax.ws.rs.QueryParam) AnnotatedMethod(org.glassfish.jersey.server.model.AnnotatedMethod) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation)

Example 7 with QueryParam

use of javax.ws.rs.QueryParam in project helios by spotify.

the class HostsResource method list.

/**
   * Returns the list of hostnames of known hosts/agents.
   * @return The list of hostnames.
   */
@GET
@Produces(APPLICATION_JSON)
@Timed
@ExceptionMetered
public List<String> list(@QueryParam("namePattern") final String namePattern, @QueryParam("selector") final List<String> hostSelectors) {
    List<String> hosts = model.listHosts();
    if (namePattern != null) {
        final Predicate<String> matchesPattern = Pattern.compile(namePattern).asPredicate();
        hosts = hosts.stream().filter(matchesPattern).collect(Collectors.toList());
    }
    if (!hostSelectors.isEmpty()) {
        // check that all supplied selectors are parseable/valid
        final List<HostSelector> selectors = hostSelectors.stream().map(selectorStr -> {
            final HostSelector parsed = HostSelector.parse(selectorStr);
            if (parsed == null) {
                throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid host selector: " + selectorStr).build());
            }
            return parsed;
        }).collect(Collectors.toList());
        final Map<String, Map<String, String>> hostsAndLabels = getLabels(hosts);
        final HostMatcher matcher = new HostMatcher(hostsAndLabels);
        hosts = matcher.getMatchingHosts(selectors);
    }
    return hosts;
}
Also used : Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) SetGoalResponse(com.spotify.helios.common.protocol.SetGoalResponse) HostRegisterResponse(com.spotify.helios.common.protocol.HostRegisterResponse) Valid(javax.validation.Valid) QueryParam(javax.ws.rs.QueryParam) Optional(com.google.common.base.Optional) JobUndeployResponse(com.spotify.helios.common.protocol.JobUndeployResponse) Map(java.util.Map) INVALID_ID(com.spotify.helios.common.protocol.JobUndeployResponse.Status.INVALID_ID) Deployment(com.spotify.helios.common.descriptors.Deployment) DefaultValue(javax.ws.rs.DefaultValue) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) HostStillInUseException(com.spotify.helios.master.HostStillInUseException) JobDeployResponse(com.spotify.helios.common.protocol.JobDeployResponse) DELETE(javax.ws.rs.DELETE) HostMatcher(com.spotify.helios.master.HostMatcher) Responses.notFound(com.spotify.helios.master.http.Responses.notFound) JobDoesNotExistException(com.spotify.helios.master.JobDoesNotExistException) FORBIDDEN(com.spotify.helios.common.protocol.JobUndeployResponse.Status.FORBIDDEN) Predicate(java.util.function.Predicate) JOB_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.JOB_NOT_FOUND) Collectors(java.util.stream.Collectors) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) JobPortAllocationConflictException(com.spotify.helios.master.JobPortAllocationConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) Responses.badRequest(com.spotify.helios.master.http.Responses.badRequest) Pattern(java.util.regex.Pattern) JobId(com.spotify.helios.common.descriptors.JobId) PathParam(javax.ws.rs.PathParam) HOST_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.HOST_NOT_FOUND) GET(javax.ws.rs.GET) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) OK(com.spotify.helios.common.protocol.JobUndeployResponse.Status.OK) PATCH(com.spotify.helios.master.http.PATCH) Function(java.util.function.Function) Responses.forbidden(com.spotify.helios.master.http.Responses.forbidden) HostSelector(com.spotify.helios.common.descriptors.HostSelector) EMPTY_TOKEN(com.spotify.helios.common.descriptors.Job.EMPTY_TOKEN) HostStatus(com.spotify.helios.common.descriptors.HostStatus) HostNotFoundException(com.spotify.helios.master.HostNotFoundException) JobAlreadyDeployedException(com.spotify.helios.master.JobAlreadyDeployedException) MasterModel(com.spotify.helios.master.MasterModel) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) HostDeregisterResponse(com.spotify.helios.common.protocol.HostDeregisterResponse) Maps(com.google.common.collect.Maps) TokenVerificationException(com.spotify.helios.master.TokenVerificationException) PUT(javax.ws.rs.PUT) JobNotDeployedException(com.spotify.helios.master.JobNotDeployedException) WebApplicationException(javax.ws.rs.WebApplicationException) HostSelector(com.spotify.helios.common.descriptors.HostSelector) Map(java.util.Map) HostMatcher(com.spotify.helios.master.HostMatcher) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 8 with QueryParam

use of javax.ws.rs.QueryParam in project keywhiz by square.

the class AutomationGroupResource method getGroupByName.

/**
   * Retrieve Group by a specified name, or all Groups if no name given
   *
   * @param name the name of the Group to retrieve, if provided
   * @excludeParams automationClient
   * @optionalParams name
   * @description Returns a single Group or a set of all Groups
   * @responseMessage 200 Found and retrieved Group(s)
   * @responseMessage 404 Group with given name not found (if name provided)
   */
@Timed
@ExceptionMetered
@GET
public Response getGroupByName(@Auth AutomationClient automationClient, @QueryParam("name") Optional<String> name) {
    if (name.isPresent()) {
        Group group = groupDAO.getGroup(name.get()).orElseThrow(NotFoundException::new);
        ImmutableList<Client> clients = ImmutableList.copyOf(aclDAO.getClientsFor(group));
        ImmutableList<SanitizedSecret> sanitizedSecrets = ImmutableList.copyOf(aclDAO.getSanitizedSecretsFor(group));
        return Response.ok().entity(GroupDetailResponse.fromGroup(group, sanitizedSecrets, clients)).build();
    }
    ImmutableList<SanitizedSecret> emptySecrets = ImmutableList.of();
    ImmutableList<Client> emptyClients = ImmutableList.of();
    List<GroupDetailResponse> groups = groupDAO.getGroups().stream().map((g) -> GroupDetailResponse.fromGroup(g, emptySecrets, emptyClients)).collect(toList());
    return Response.ok().entity(groups).build();
}
Also used : PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Event(keywhiz.log.Event) Strings.nullToEmpty(com.google.common.base.Strings.nullToEmpty) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) GroupResource(keywhiz.service.resources.automation.v2.GroupResource) QueryParam(javax.ws.rs.QueryParam) ImmutableList(com.google.common.collect.ImmutableList) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) DELETE(javax.ws.rs.DELETE) AuditLog(keywhiz.log.AuditLog) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) LongParam(io.dropwizard.jersey.params.LongParam) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) NotFoundException(javax.ws.rs.NotFoundException) Timed(com.codahale.metrics.annotation.Timed) CreateGroupRequest(keywhiz.api.CreateGroupRequest) EventTag(keywhiz.log.EventTag) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) VisibleForTesting(com.google.common.annotations.VisibleForTesting) GroupDetailResponse(keywhiz.api.GroupDetailResponse) Group(keywhiz.api.model.Group) SanitizedSecret(keywhiz.api.model.SanitizedSecret) GroupDetailResponse(keywhiz.api.GroupDetailResponse) NotFoundException(javax.ws.rs.NotFoundException) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 9 with QueryParam

use of javax.ws.rs.QueryParam in project keywhiz by square.

the class AutomationClientResource method findClient.

/**
   * Retrieve Client by a specified name, or all Clients if no name given
   *
   * @param name the name of the Client to retrieve, if provided
   * @excludeParams automationClient
   * @optionalParams name
   * @description Returns a single Client or a set of all Clients
   * @responseMessage 200 Found and retrieved Client(s)
   * @responseMessage 404 Client with given name not found (if name provided)
   */
@Timed
@ExceptionMetered
@GET
public Response findClient(@Auth AutomationClient automationClient, @QueryParam("name") Optional<String> name) {
    logger.info("Automation ({}) - Looking up a name {}", automationClient.getName(), name);
    if (name.isPresent()) {
        Client client = clientDAO.getClient(name.get()).orElseThrow(NotFoundException::new);
        ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(client));
        return Response.ok().entity(ClientDetailResponse.fromClient(client, groups, ImmutableList.of())).build();
    }
    List<ClientDetailResponse> clients = clientDAO.getClients().stream().map(c -> ClientDetailResponse.fromClient(c, ImmutableList.copyOf(aclDAO.getGroupsFor(c)), ImmutableList.of())).collect(toList());
    return Response.ok().entity(clients).build();
}
Also used : PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) ClientDAO(keywhiz.service.daos.ClientDAO) GET(javax.ws.rs.GET) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) ClientsResource(keywhiz.service.resources.admin.ClientsResource) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) ClientDAOFactory(keywhiz.service.daos.ClientDAO.ClientDAOFactory) QueryParam(javax.ws.rs.QueryParam) ImmutableList(com.google.common.collect.ImmutableList) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) DELETE(javax.ws.rs.DELETE) ClientResource(keywhiz.service.resources.automation.v2.ClientResource) AuditLog(keywhiz.log.AuditLog) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) LongParam(io.dropwizard.jersey.params.LongParam) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) NotFoundException(javax.ws.rs.NotFoundException) Timed(com.codahale.metrics.annotation.Timed) EventTag(keywhiz.log.EventTag) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ClientDetailResponse(keywhiz.api.ClientDetailResponse) CreateClientRequest(keywhiz.api.CreateClientRequest) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Group(keywhiz.api.model.Group) NotFoundException(javax.ws.rs.NotFoundException) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) ClientDetailResponse(keywhiz.api.ClientDetailResponse) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 10 with QueryParam

use of javax.ws.rs.QueryParam in project japid42 by branaway.

the class RouterMethod method extractArguments.

public Object[] extractArguments(play.mvc.Http.RequestHeader r) {
    String path = r.path();
    if (path.endsWith(withExtension))
        path = path.substring(0, path.lastIndexOf(withExtension));
    List<RegMatch> rootParamValueMatches = RegMatch.findAllMatchesIn(valueExtractionPattern, path);
    List<String> rootParamValues = new ArrayList<String>();
    for (RegMatch rm : rootParamValueMatches) {
        rootParamValues.addAll(rm.subgroups);
    }
    if (rootParamValues.size() != paramSpecList.size()) {
        throw new RuntimeException("param spec number does not match that from URI capturing. Spec contains: " + paramSpecList.size() + " while the URI contains: " + rootParamValues.size() + ". The route entry is: " + this.toString());
    }
    Map<String, Object> args = new java.util.HashMap<String, Object>();
    int c = 0;
    for (ParamSpec paramSpec : paramSpecList) {
        String name = paramSpec.name;
        String value = rootParamValues.get(c++);
        if (!paramSpec.formatPattern.matcher(value).matches()) {
            throw new IllegalArgumentException("format mismatch for : (" + name + ")" + value + ". The route entry is: " + this.toString());
        }
        Class<?> type = paramSpec.type;
        Object val = convertArgType(c, name, value, type);
        args.put(name, val);
    }
    //
    Object[] argValues = new Object[0];
    List<Object> argVals = new ArrayList<Object>();
    Annotation[][] annos = meth.getParameterAnnotations();
    c = 0;
    int pos = 0;
    for (Annotation[] ans : annos) {
        PathParam pathParam = null;
        QueryParam queryParam = null;
        for (Annotation an : ans) {
            if (an instanceof PathParam)
                pathParam = (PathParam) an;
            else if (an instanceof QueryParam)
                queryParam = (QueryParam) an;
        }
        if (pathParam != null) {
            Object v = args.get(pathParam.value());
            if (v != null)
                argVals.add(v);
            else
                throw new IllegalArgumentException("can not find annotation value for argument " + pathParam.value() + "in " + meth.getDeclaringClass() + "#" + meth);
        } else if (queryParam != null) {
            String name = queryParam.value();
            // XXX should this
            String queryString = r.getQueryString(name);
            // be of
            // String[]?
            argVals.add(convertArgType(c, name, queryString, meth.getParameterTypes()[c]));
        } else if (autoRouting) {
            Object v = args.get("_" + pos++);
            if (v != null)
                argVals.add(v);
            else
                throw new IllegalArgumentException("can not find value for param No. " + c + " in " + meth.getDeclaringClass() + "#" + meth);
        } else
            throw new IllegalArgumentException("can not find how to map the value for an argument for method:" + meth.getDeclaringClass() + "#" + meth + ". The parameter position is(0-based): " + c);
        c++;
    }
    argValues = argVals.toArray(argValues);
    return argValues;
}
Also used : ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) QueryParam(javax.ws.rs.QueryParam) PathParam(javax.ws.rs.PathParam)

Aggregations

QueryParam (javax.ws.rs.QueryParam)19 PathParam (javax.ws.rs.PathParam)15 Path (javax.ws.rs.Path)12 GET (javax.ws.rs.GET)11 Produces (javax.ws.rs.Produces)11 Response (javax.ws.rs.core.Response)9 Logger (org.slf4j.Logger)9 LoggerFactory (org.slf4j.LoggerFactory)9 ApiParam (io.swagger.annotations.ApiParam)8 Annotation (java.lang.annotation.Annotation)8 POST (javax.ws.rs.POST)8 ApiOperation (io.swagger.annotations.ApiOperation)7 ApiResponse (io.swagger.annotations.ApiResponse)7 ApiResponses (io.swagger.annotations.ApiResponses)7 List (java.util.List)7 Inject (javax.inject.Inject)7 Consumes (javax.ws.rs.Consumes)7 DefaultValue (javax.ws.rs.DefaultValue)7 ArrayList (java.util.ArrayList)6 DELETE (javax.ws.rs.DELETE)6