use of javax.ws.rs.HttpMethod in project che by eclipse.
the class Service method generateLinkForMethod.
private Link generateLinkForMethod(UriInfo uriInfo, String linkRel, Method method, Object... pathParameters) {
String httpMethod = null;
final HttpMethod httpMethodAnnotation = getMetaAnnotation(method, HttpMethod.class);
if (httpMethodAnnotation != null) {
httpMethod = httpMethodAnnotation.value();
}
if (httpMethod == null) {
throw new IllegalArgumentException(format("Method '%s' has not any HTTP method annotation and may not be used to produce link.", method.getName()));
}
final Consumes consumes = getAnnotation(method, Consumes.class);
final Produces produces = getAnnotation(method, Produces.class);
final UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
final LinkedList<String> matchedURIs = new LinkedList<>(uriInfo.getMatchedURIs());
// Get path to the root resource.
if (uriInfo.getMatchedResources().size() < matchedURIs.size()) {
matchedURIs.remove();
}
while (!matchedURIs.isEmpty()) {
baseUriBuilder.path(matchedURIs.pollLast());
}
final Path path = method.getAnnotation(Path.class);
if (path != null) {
baseUriBuilder.path(path.value());
}
final Link link = DtoFactory.getInstance().createDto(Link.class).withRel(linkRel).withHref(baseUriBuilder.build(pathParameters).toString()).withMethod(httpMethod);
if (consumes != null) {
link.setConsumes(consumes.value()[0]);
}
if (produces != null) {
link.setProduces(produces.value()[0]);
}
Class<?>[] parameterClasses = method.getParameterTypes();
if (parameterClasses.length > 0) {
Annotation[][] annotations = method.getParameterAnnotations();
for (int i = 0; i < parameterClasses.length; i++) {
if (annotations[i].length > 0) {
boolean isBodyParameter = false;
QueryParam queryParam = null;
Description description = null;
Required required = null;
Valid valid = null;
DefaultValue defaultValue = null;
for (int j = 0; j < annotations[i].length; j++) {
Annotation annotation = annotations[i][j];
isBodyParameter |= !JAX_RS_ANNOTATIONS.contains(annotation.annotationType().getName());
Class<?> annotationType = annotation.annotationType();
if (annotationType == QueryParam.class) {
queryParam = (QueryParam) annotation;
} else if (annotationType == Description.class) {
description = (Description) annotation;
} else if (annotationType == Required.class) {
required = (Required) annotation;
} else if (annotationType == Valid.class) {
valid = (Valid) annotation;
} else if (annotationType == DefaultValue.class) {
defaultValue = (DefaultValue) annotation;
}
}
if (queryParam != null) {
LinkParameter parameter = DtoFactory.getInstance().createDto(LinkParameter.class).withName(queryParam.value()).withRequired(required != null).withType(getParameterType(parameterClasses[i]));
if (defaultValue != null) {
parameter.setDefaultValue(defaultValue.value());
}
if (description != null) {
parameter.setDescription(description.value());
}
if (valid != null) {
parameter.setValid(Arrays.asList(valid.value()));
}
link.getParameters().add(parameter);
} else if (isBodyParameter) {
if (description != null) {
link.setRequestBody(DtoFactory.getInstance().createDto(RequestBodyDescriptor.class).withDescription(description.value()));
}
}
}
}
}
return link;
}
use of javax.ws.rs.HttpMethod 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);
}
}
}
use of javax.ws.rs.HttpMethod in project opencast by opencast.
the class RestDocsAnnotationTest method testRestQueryDocs2.
/**
* This tests the functionality of @RestQuery, @RestParameter, @RestResponse, @Path, @Produces, @Consumes annotation
* type using a different technique.
*/
@Test
public void testRestQueryDocs2() {
Method testMethod;
try {
testMethod = TestServletSample.class.getMethod("methodA");
if (testMethod != null) {
RestDocData restDocData = new RestDocData("NAME", "TITLE", "URL", null, new TestServletSample(), new HashMap<String, String>());
RestQuery restQueryAnnotation = (RestQuery) testMethod.getAnnotation(RestQuery.class);
Path pathAnnotation = (Path) testMethod.getAnnotation(Path.class);
Produces producesAnnotation = (Produces) testMethod.getAnnotation(Produces.class);
String httpMethodString = null;
// we cannot hard code the GET.class or POST.class because we don't know which one is used.
for (Annotation a : testMethod.getAnnotations()) {
HttpMethod method = (HttpMethod) a.annotationType().getAnnotation(HttpMethod.class);
if (method != null) {
httpMethodString = method.value();
}
}
RestEndpointData endpoint = new RestEndpointData(testMethod.getReturnType(), restDocData.processMacro(restQueryAnnotation.name()), httpMethodString, "/" + pathAnnotation.value(), restDocData.processMacro(restQueryAnnotation.description()));
if (!restQueryAnnotation.returnDescription().isEmpty()) {
endpoint.addNote("Return value description: " + restDocData.processMacro(restQueryAnnotation.returnDescription()));
}
// name, description and return description
assertEquals("addTrackInputStream", endpoint.getName());
assertEquals("Add a media track to a given media package using an input stream", endpoint.getDescription());
assertEquals(1, endpoint.getNotes().size());
assertEquals("Return value description: augmented media package", endpoint.getNotes().get(0));
// HTTP method
assertEquals("POST", endpoint.getMethod());
assertEquals("/addTrack", endpoint.getPath());
// @Produces
if (producesAnnotation != null) {
for (String format : producesAnnotation.value()) {
endpoint.addFormat(new RestFormatData(format));
}
}
assertEquals(1, endpoint.getFormats().size());
assertEquals(MediaType.TEXT_XML, endpoint.getFormats().get(0).getName());
// responses
for (RestResponse restResp : restQueryAnnotation.reponses()) {
endpoint.addStatus(restResp, restDocData);
}
assertEquals(3, endpoint.getStatuses().size());
assertEquals(HttpServletResponse.SC_OK, endpoint.getStatuses().get(0).getCode());
assertEquals("Returns augmented media package", endpoint.getStatuses().get(0).getDescription());
assertEquals(HttpServletResponse.SC_BAD_REQUEST, endpoint.getStatuses().get(1).getCode());
assertEquals(null, endpoint.getStatuses().get(1).getDescription());
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, endpoint.getStatuses().get(2).getCode());
assertEquals(null, endpoint.getStatuses().get(2).getDescription());
// body parameter
if (restQueryAnnotation.bodyParameter().type() != RestParameter.Type.NO_PARAMETER) {
endpoint.addBodyParam(restQueryAnnotation.bodyParameter(), restDocData);
}
assertEquals("BODY", endpoint.getBodyParam().getName());
assertEquals("The media track file", endpoint.getBodyParam().getDescription());
assertTrue(endpoint.getBodyParam().isRequired());
assertEquals(null, endpoint.getBodyParam().getDefaultValue());
assertTrue("FILE".equalsIgnoreCase(endpoint.getBodyParam().getType()));
// path parameter
for (RestParameter restParam : restQueryAnnotation.pathParameters()) {
endpoint.addPathParam(new RestParamData(restParam, restDocData));
}
assertEquals(1, endpoint.getPathParams().size());
assertEquals("wdID", endpoint.getPathParams().get(0).getName());
assertEquals("Workflow definition id", endpoint.getPathParams().get(0).getDescription());
assertTrue(endpoint.getPathParams().get(0).isRequired());
assertTrue(endpoint.getPathParams().get(0).isPath());
assertEquals(null, endpoint.getPathParams().get(0).getDefaultValue());
assertTrue("STRING".equalsIgnoreCase(endpoint.getPathParams().get(0).getType()));
// query parameters
for (RestParameter restParam : restQueryAnnotation.restParameters()) {
if (restParam.isRequired()) {
endpoint.addRequiredParam(new RestParamData(restParam, restDocData));
} else {
endpoint.addOptionalParam(new RestParamData(restParam, restDocData));
}
}
// #1
assertEquals(1, endpoint.getRequiredParams().size());
assertEquals("flavor", endpoint.getRequiredParams().get(0).getName());
assertEquals("The kind of media track", endpoint.getRequiredParams().get(0).getDescription());
assertTrue(endpoint.getRequiredParams().get(0).isRequired());
assertEquals("Default", endpoint.getRequiredParams().get(0).getDefaultValue());
assertTrue("STRING".equalsIgnoreCase(endpoint.getRequiredParams().get(0).getType()));
// #2
assertEquals(1, endpoint.getOptionalParams().size());
assertEquals("mediaPackage", endpoint.getOptionalParams().get(0).getName());
assertEquals("The media package as XML", endpoint.getOptionalParams().get(0).getDescription());
assertFalse(endpoint.getOptionalParams().get(0).isRequired());
assertEquals(null, endpoint.getOptionalParams().get(0).getDefaultValue());
assertTrue("TEXT".equalsIgnoreCase(endpoint.getOptionalParams().get(0).getType()));
}
} catch (SecurityException e) {
fail();
} catch (NoSuchMethodException e) {
fail();
}
}
use of javax.ws.rs.HttpMethod in project cxf by apache.
the class CrossOriginResourceSharingFilter method filter.
@Override
public void filter(ContainerRequestContext context) {
Message m = JAXRSUtils.getCurrentMessage();
String httpMethod = (String) m.get(Message.HTTP_REQUEST_METHOD);
if (HttpMethod.OPTIONS.equals(httpMethod)) {
Response r = preflightRequest(m);
if (r != null) {
context.abortWith(r);
}
} else if (findResourceMethod) {
Method method = getResourceMethod(m, httpMethod);
simpleRequest(m, method);
} else {
m.getInterceptorChain().add(new CorsInInterceptor());
}
}
use of javax.ws.rs.HttpMethod in project swagger-core by swagger-api.
the class Reader method read.
private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
Map<String, Tag> tags = new LinkedHashMap<String, Tag>();
List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
String[] consumes = new String[0];
String[] produces = new String[0];
final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class);
Api api = ReflectionUtils.getAnnotation(cls, Api.class);
boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null);
boolean hasApiAnnotation = (api != null);
boolean isApiHidden = hasApiAnnotation && api.hidden();
// class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden
boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden;
// with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource
boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource);
// readable if classReadable or scanAll
boolean readable = classReadable || scanAll;
if (!readable) {
return swagger;
}
// api readable only if @Api present; cannot be hidden because checked in classReadable.
boolean apiReadable = hasApiAnnotation;
if (apiReadable) {
// the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
Set<String> tagStrings = extractTags(api);
for (String tagString : tagStrings) {
Tag tag = new Tag().name(tagString);
tags.put(tagString, tag);
}
for (String tagName : tags.keySet()) {
swagger.tag(tags.get(tagName));
}
if (!api.produces().isEmpty()) {
produces = ReaderUtils.splitContentValues(new String[] { api.produces() });
}
if (!api.consumes().isEmpty()) {
consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() });
}
globalSchemes.addAll(parseSchemes(api.protocols()));
for (Authorization auth : api.authorizations()) {
if (auth.value() != null && !auth.value().isEmpty()) {
SecurityRequirement security = new SecurityRequirement();
security.setName(auth.value());
for (AuthorizationScope scope : auth.scopes()) {
if (scope.scope() != null && !scope.scope().isEmpty()) {
security.addScope(scope.scope());
}
}
securities.add(security);
}
}
}
if (readable) {
if (isSubresource) {
if (parentTags != null) {
tags.putAll(parentTags);
}
}
// merge consumes, produces
if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) {
consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
}
if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) {
produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
}
// look for method-level annotated properties
// handle sub-resources by looking at return type
final List<Parameter> globalParameters = new ArrayList<Parameter>();
// look for constructor-level annotated properties
globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger));
// look for field-level annotated properties
globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger));
// build class/interface level @ApiResponse list
ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class);
List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>();
if (classResponseAnnotation != null) {
classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value()));
}
// parse the method
final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class);
JavaType classType = TypeFactory.defaultInstance().constructType(cls);
BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType);
Method[] methods = cls.getMethods();
for (Method method : methods) {
AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes());
if (ReflectionUtils.isOverriddenMethod(method, cls)) {
continue;
}
javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class);
String operationPath = getPath(apiPath, methodPath, parentPath);
Map<String, String> regexMap = new LinkedHashMap<String, String>();
operationPath = PathUtils.parsePath(operationPath, regexMap);
if (operationPath != null) {
if (isIgnored(operationPath)) {
continue;
}
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain());
Operation operation = null;
if (apiOperation != null || config.isScanAllResources() || httpMethod != null || methodPath != null) {
operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses);
}
if (operation == null) {
continue;
}
if (parentParameters != null) {
for (Parameter param : parentParameters) {
operation.parameter(param);
}
}
for (Parameter param : operation.getParameters()) {
if (regexMap.get(param.getName()) != null) {
String pattern = regexMap.get(param.getName());
param.setPattern(pattern);
}
}
if (apiOperation != null) {
for (Scheme scheme : parseSchemes(apiOperation.protocols())) {
operation.scheme(scheme);
}
}
if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) {
for (Scheme scheme : globalSchemes) {
operation.scheme(scheme);
}
}
String[] apiConsumes = consumes;
if (parentConsumes != null) {
Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiConsumes));
both.addAll(new LinkedHashSet<String>(Arrays.asList(parentConsumes)));
if (operation.getConsumes() != null) {
both.addAll(new LinkedHashSet<String>(operation.getConsumes()));
}
apiConsumes = both.toArray(new String[both.size()]);
}
String[] apiProduces = produces;
if (parentProduces != null) {
Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiProduces));
both.addAll(new LinkedHashSet<String>(Arrays.asList(parentProduces)));
if (operation.getProduces() != null) {
both.addAll(new LinkedHashSet<String>(operation.getProduces()));
}
apiProduces = both.toArray(new String[both.size()]);
}
final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method);
if (subResource != null && !scannedResources.contains(subResource)) {
scannedResources.add(subResource);
read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources);
// remove the sub resource so that it can visit it later in another path
// but we have a room for optimization in the future to reuse the scanned result
// by caching the scanned resources in the reader instance to avoid actual scanning
// the the resources again
scannedResources.remove(subResource);
}
// can't continue without a valid http method
httpMethod = (httpMethod == null) ? parentMethod : httpMethod;
if (httpMethod != null) {
if (apiOperation != null) {
for (String tag : apiOperation.tags()) {
if (!"".equals(tag)) {
operation.tag(tag);
swagger.tag(new Tag().name(tag));
}
}
operation.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions()));
}
if (operation.getConsumes() == null) {
for (String mediaType : apiConsumes) {
operation.consumes(mediaType);
}
}
if (operation.getProduces() == null) {
for (String mediaType : apiProduces) {
operation.produces(mediaType);
}
}
if (operation.getTags() == null) {
for (String tagString : tags.keySet()) {
operation.tag(tagString);
}
}
// Only add global @Api securities if operation doesn't already have more specific securities
if (operation.getSecurity() == null) {
for (SecurityRequirement security : securities) {
operation.security(security);
}
}
Path path = swagger.getPath(operationPath);
if (path == null) {
path = new Path();
swagger.path(operationPath, path);
}
path.set(httpMethod, operation);
readImplicitParameters(method, operation);
readExternalDocs(method, operation);
}
}
}
}
return swagger;
}
Aggregations