void map(@NonNull HttpConfiguration httpConfiguration) throws IOException { org.springframework.core.io.Resource[] resources; try { resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources( applicationProperties.getResourcePath() + "/openapi/**.y*ml"); } catch (FileNotFoundException exp) { LOG.warn("No Open API resources found in path:{}/openapi", applicationProperties.getResourcePath()); return; } for (org.springframework.core.io.Resource resource : resources) { InputStream inputStream = new EnvironmentAwareResource(resource.getInputStream(), environment).getInputStream(); String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); if (!StringUtils.isBlank(result)) { Swagger swagger = openApiParser.parse(result); mapOpenApiDefinition(swagger, httpConfiguration); } } }
@Test public void mapEndpointWithoutBasePath() throws IOException { // Arrange mockDefinition().host(DBEERPEDIA.OPENAPI_HOST).produces(MediaType.TEXT_PLAIN).path("/breweries", new Path().get(new Operation().vendorExtensions( ImmutableMap.of(OpenApiSpecificationExtensions.INFORMATION_PRODUCT, DBEERPEDIA.BREWERIES.stringValue())).response(Status.OK.getStatusCode(), new Response().schema(mock(Property.class))))); when(informationProductResourceProviderMock.get(DBEERPEDIA.BREWERIES)).thenReturn( informationProductMock); // Act requestMapper.map(httpConfigurationMock); // Assert verify(httpConfigurationMock).registerResources(resourceCaptor.capture()); Resource resource = resourceCaptor.getValue(); assertThat(resource.getPath(), equalTo("/" + DBEERPEDIA.OPENAPI_HOST + "/breweries")); }
@Test public void map_BodyParameter() throws IOException { // Arrange Property property = mock(Property.class); List<Parameter> parameters = createBodyParameter("object"); Operation newOp = new Operation(); newOp.setParameters(parameters); newOp.vendorExtensions(ImmutableMap.of(OpenApiSpecificationExtensions.INFORMATION_PRODUCT, DBEERPEDIA.BREWERIES.stringValue())); newOp.response(200, new Response().schema(property)); mockDefinition().host(DBEERPEDIA.OPENAPI_HOST).produces(MediaType.APPLICATION_JSON).path( "/breweries", new Path().get(newOp)); // Act requestMapper.map(httpConfigurationMock); // Assert verify(httpConfigurationMock).registerResources(resourceCaptor.capture()); Resource resource = resourceCaptor.getValue(); assertThat(resource.getPath(), equalTo("/" + DBEERPEDIA.OPENAPI_HOST + "/breweries")); }
@Test public void initialize_RegistersErrorResource_WhenCalled() { // Act errorModule.initialize(httpConfigurationMock); // Assert verify(httpConfigurationMock).registerResources(resourceCaptor.capture()); assertThat(resourceCaptor.getAllValues(), hasSize(1)); Resource resource = resourceCaptor.getValue(); assertThat(resource.getPath(), equalTo("/{domain}/__errors/{statusCode:\\d{3}}")); assertThat(resource.getResourceMethods(), hasSize(1)); ResourceMethod method = resource.getResourceMethods().get(0); assertThat(method.getHttpMethod(), CoreMatchers.equalTo(HttpMethod.GET)); assertThat(method.getProducedTypes(), contains(MediaType.TEXT_PLAIN_TYPE)); Object handler = resource.getHandlerInstances().iterator().next(); assertThat(handler, instanceOf(ServletErrorHandler.class)); }
private void mapRepresentation(Representation representation, HttpConfiguration httpConfiguration) { String basePath = representation.getStage().getFullPath(); representation.getUrlPatterns().forEach(path -> { String absolutePath = basePath.concat(path); Resource.Builder resourceBuilder = Resource.builder().path(absolutePath); resourceBuilder.addMethod(HttpMethod.GET).handledBy( representationRequestHandlerFactory.newRepresentationRequestHandler( representation)).produces( supportedMediaTypesScanner.getMediaTypes( representation.getInformationProduct().getResultType())).nameBindings( ExpandFormatParameter.class); if (!httpConfiguration.resourceAlreadyRegistered(absolutePath)) { httpConfiguration.registerResources(resourceBuilder.build()); LOG.debug("Mapped GET operation for request path {}", absolutePath); } else { LOG.error("Resource <%s> is not registered", absolutePath); } }); }
private void mapRedirection(Redirection redirection, HttpConfiguration httpConfiguration) { String basePath = redirection.getStage().getFullPath(); String urlPattern = redirection.getUrlPattern().replaceAll("^\\^", ""); String absolutePathRegex = String.format("%s{any: %s}", basePath, urlPattern); Resource.Builder resourceBuilder = Resource.builder().path(absolutePathRegex); resourceBuilder.addMethod(HttpMethod.GET).handledBy( new RedirectionRequestHandler(redirection)).nameBindings(ExpandFormatParameter.class); if (!httpConfiguration.resourceAlreadyRegistered(absolutePathRegex)) { httpConfiguration.registerResources(resourceBuilder.build()); LOG.debug("Mapped GET redirection for request path {}", absolutePathRegex); } else { LOG.error("Resource <%s> is not registered", absolutePathRegex); } }
@Test public void loadRepresentations_MapRepresentation_WithValidData() { // Arrange when(supportedMediaTypesScanner.getMediaTypes(any())).thenReturn( new MediaType[] {MediaType.valueOf("text/turtle")}); // Act ldRepresentationRequestMapper.loadRepresentations(httpConfiguration); // Assert Resource resource = (Resource) httpConfiguration.getResources().toArray()[0]; final ResourceMethod method = resource.getResourceMethods().get(0); assertThat(httpConfiguration.getResources(), hasSize(1)); assertThat(resource.getPath(), equalTo("/" + DBEERPEDIA.ORG_HOST + DBEERPEDIA.BASE_PATH.getLabel() + DBEERPEDIA.URL_PATTERN_VALUE)); assertThat(resource.getResourceMethods(), hasSize(1)); assertThat(method.getHttpMethod(), equalTo(HttpMethod.GET)); }
/** * Updates the default {@code @Produces} list of every controller method whose list is empty. * The new list contains a single media type: "text/html". * * @param r resource to process. * @return newly updated resource. */ private static Resource processResource(Resource r) { final boolean isControllerClass = isController(r); Resource.Builder rb = Resource.builder(r); r.getAllMethods().forEach( (ResourceMethod m) -> { if ((isController(m) || isControllerClass) && m.getProducedTypes().isEmpty()) { final ResourceMethod.Builder rmb = rb.updateMethod(m); rmb.produces(MediaType.TEXT_HTML_TYPE); rmb.build(); } } ); r.getChildResources().forEach(cr -> { rb.replaceChildResource(cr, processResource(cr)); }); return rb.build(); }
private void prepareAppEvent(final String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final MockResource mockResource = new MockResource(); final Method handlingMethod = mockResource.getClass().getMethod(resourceMethodName); Method definitionMethod = handlingMethod; final Class<?> interfaceClass = mockResource.getClass().getInterfaces()[0]; if (this.methodDefinedOnInterface(resourceMethodName, interfaceClass.getMethods())) { definitionMethod = interfaceClass.getMethod(resourceMethodName); } final ResourceMethod resourceMethod = builder.addMethod() .handlingMethod(handlingMethod) .handledBy(mockResource, definitionMethod).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(this.appEvent.getResourceModel()).thenReturn(model); when(this.uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
/** * Registers any Guice-bound providers or root resources. */ public static void registerGuiceBound(Injector injector, final JerseyEnvironment environment) { while (injector != null) { for (Key<?> key : injector.getBindings().keySet()) { Type type = key.getTypeLiteral().getType(); if (type instanceof Class) { Class<?> c = (Class) type; if (isProviderClass(c)) { logger.info("Registering {} as a provider class", c.getName()); environment.register(c); } else if (isRootResourceClass(c)) { // Jersey rejects resources that it doesn't think are acceptable // Including abstract classes and interfaces, even if there is a valid Guice binding. if(Resource.isAcceptable(c)) { logger.info("Registering {} as a root resource class", c.getName()); environment.register(c); } else { logger.warn("Class {} was not registered as a resource. Bind a concrete implementation instead.", c.getName()); } } } } injector = injector.getParent(); } }
private void prepareAppEvent(String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final MockResource mockResource = new MockResource(); final Method handlingMethod = mockResource.getClass().getMethod(resourceMethodName); Method definitionMethod = handlingMethod; Class<?> interfaceClass = mockResource.getClass().getInterfaces()[0]; if (methodDefinedOnInterface(resourceMethodName, interfaceClass.getMethods())) { definitionMethod = interfaceClass.getMethod(resourceMethodName); } final ResourceMethod resourceMethod = builder.addMethod() .handlingMethod(handlingMethod) .handledBy(mockResource, definitionMethod).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(appEvent.getResourceModel()).thenReturn(model); when(uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
/** * Registers any Guice-bound providers or root resources. */ public static void registerGuiceBound(Injector injector, final JerseyEnvironment environment) { while (injector != null) { for (Key<?> key : injector.getBindings().keySet()) { Type type = key.getTypeLiteral().getType(); if (type instanceof Class) { Class<?> c = (Class) type; if (isProviderClass(c)) { logger.info("Registering {} as a provider class", c.getName()); environment.register(c); } else if (isRootResourceClass(c)) { // Jersey rejects resources that it doesn't think are acceptable // Including abstract classes and interfaces, even if there is a valid Guice binding. if (Resource.isAcceptable(c)) { logger.info("Registering {} as a root resource class", c.getName()); environment.register(c); } else { logger.warn("Class {} was not registered as a resource. Bind a concrete implementation instead.", c.getName()); } } } } injector = injector.getParent(); } }
private boolean buildSchemaConfig(ResourceConfig config, String schemaName) { Schema schema = rePro.getSchema(schemaName); // get schema -> resources int cnt = 0; for (com.bagri.core.system.Resource res: schema.getResources()) { // for each resource -> get module if (res.isEnabled()) { Module module = rePro.getModule(res.getModule()); try { buildDynamicResources(config, res.getPath(), module); cnt++; } catch (BagriException ex) { logger.error("buildSchemaConfig; error processing module: " + res.getModule(), ex); // skip it.. } } } return cnt > 0; }
private void buildDynamicResources(ResourceConfig config, String basePath, Module module) throws BagriException { Resource.Builder resourceBuilder = Resource.builder(); resourceBuilder.path(basePath); // get functions for module List<Function> functions = xqComp.getRestFunctions(module); // now build Resource dynamically from the function list for (Function function: functions) { buildMethod(resourceBuilder, module, function); SwaggerListener.addFunction(basePath, function); } Resource resource = resourceBuilder.build(); config.registerResources(resource); logger.info("buildDynamicResources; registered resource: {}", resource); }
/** * <p>getRoutes.</p> * * @return a {@link java.util.List} object. */ @GET public List<String> getRoutes() { List<Resource> resourceList = resourceContext.getResourceModel().getResources(); List<String> routeList = Lists.newArrayList(); for (Resource resource : resourceList) { String path = resource.getPath().startsWith("/") ? "" : "/" + resource.getPath(); if (resource.getAllMethods().size() > 0) { routeList.add(path); } routeList.addAll( resource.getChildResources() .stream() .map(res -> path + (res.getPath().startsWith("/") ? "" : "/") + res.getPath()) .collect(Collectors.toList()) ); } return routeList; }
@Test public void testJerseyApplicatio() { ClassPathScanner classPathScanner = new ClassPathScanner("org.camunda"); Class<? extends Application> jaxRsApplicationSubclass = classPathScanner.getJaxRsApplicationSubclass(); Set<Resource> resources = Resources.getAll(jaxRsApplicationSubclass, null); assertNotNull(resources); ArrayList<Resource> sortedResources = new ArrayList<>(resources); Collections.sort(sortedResources, new Comparator<Resource>() { @Override public int compare(Resource o1, Resource o2) { if (o1.getPath() != null && o2.getPath() != null) { int res = String.CASE_INSENSITIVE_ORDER.compare(o1.getPath(), o2.getPath()); return (res != 0) ? res : o1.getPath().compareTo(o2.getPath()); } return 0; } }); for (Resource resource : sortedResources) { printResource(resource); } }
private void prepareAppEvent(String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final MockResource mockResource = new MockResource(); final Method handlingMethod = mockResource.getClass().getMethod(resourceMethodName); Method definitionMethod = handlingMethod; Class<?> interfaceClass = mockResource.getClass().getInterfaces()[0]; if (methodDefinedOnInterface(resourceMethodName, interfaceClass.getMethods())) { definitionMethod = interfaceClass.getMethod(resourceMethodName); } final ResourceMethod resourceMethod = builder.addMethod().handlingMethod(handlingMethod) .handledBy(mockResource, definitionMethod).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(appEvent.getResourceModel()).thenReturn(model); when(uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
/** * Builds new {@link Resource} from passed one with new * {@link org.glassfish.jersey.process.Inflector} implementation * {@link RestInflector} and with all child resources * * @param resource * @return {@link Resource} * @throws IOException */ public static Resource rebuildResource(Resource resource) throws IOException { Resource rebuiltResource; Resource.Builder builder = Resource.builder(resource.getPath()); builder.name(resource.getName()); MetaData metaData = getMetaData(resource); List<ResourceMethod> methods = resource.getAllMethods(); for (ResourceMethod method : methods) { addMethod(builder, method, metaData); } // Registers children resources recursively registerChildren(resource, builder); rebuiltResource = builder.build(); return rebuiltResource; }
/** * Reloads {@link RestConfig} instance with new registered * {@link org.glassfish.jersey.server.model.Resource}s to activate */ public static void reload() { try { RestReloader reloader = RestReloader.get(); RestConfig conf = get(); if (ObjectUtils.notNullAll(conf, reloader)) { if (RestContainer.hasRest()) { RestConfig existingConfig = RestContainer.getRestConfig(); Set<Resource> existingResources = existingConfig.getResources(); RestContainer.removeResources(existingResources); } ClassLoader commonLoader = getCommonLoader(); if (ObjectUtils.notNull(commonLoader)) { conf.setClassLoader(commonLoader); } conf.registerPreResources(); reloader.reload(conf); conf.cache(); } } finally { newConfig = null; } }
/** * Finds if {@link Resource} has handler instances and if they are instance * of {@link RestInflector} and gets appropriate EJB bean class * * @param resource * @return {@link Class} */ private static Class<?> getFromHandlerInstance(Resource resource) { Class<?> handlerClass = null; Set<Object> handlers = resource.getHandlerInstances(); if (CollectionUtils.valid(handlers)) { Iterator<Object> iterator = handlers.iterator(); Object handler; RestInflector inflector; while (iterator.hasNext() && handlerClass == null) { handler = iterator.next(); if (handler instanceof RestInflector) { inflector = ObjectUtils.cast(handler, RestInflector.class); handlerClass = inflector.getBeanClass(); } } } return handlerClass; }
@Test public void map_DoesNotRegisterAnything_NoDefinitionFilesFound() throws IOException { // Arrange when(((ResourcePatternResolver) resourceLoader).getResources(anyString())).thenReturn( new org.springframework.core.io.Resource[0]); // Act requestMapper.map(httpConfigurationMock); // Assert verifyZeroInteractions(informationProductResourceProviderMock); verifyZeroInteractions(httpConfigurationMock); }
@Test public void map_DoesNotRegisterAnything_EmptyFile() throws IOException { // Arrange when(((ResourcePatternResolver) resourceLoader).getResources(anyString())).thenReturn( new org.springframework.core.io.Resource[] {new ByteArrayResource(new byte[0])}); // Act requestMapper.map(httpConfigurationMock); // Assert verifyZeroInteractions(informationProductResourceProviderMock); verifyZeroInteractions(httpConfigurationMock); }
@Test public void map_EndpointsCorrectly_WithValidData() throws IOException { // Arrange Property schema = mock(Property.class); mockDefinition().host(DBEERPEDIA.OPENAPI_HOST).basePath(DBEERPEDIA.OPENAPI_BASE_PATH).produces( ImmutableList.of(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON)).path( "/breweries", new Path().get(new Operation().vendorExtensions( ImmutableMap.of(OpenApiSpecificationExtensions.INFORMATION_PRODUCT, DBEERPEDIA.BREWERIES.stringValue())).response(Status.OK.getStatusCode(), new Response().schema(schema)))); when(informationProductResourceProviderMock.get(DBEERPEDIA.BREWERIES)).thenReturn( informationProductMock); // Act requestMapper.map(httpConfigurationMock); // Assert verify(httpConfigurationMock).registerResources(resourceCaptor.capture()); Resource resource = resourceCaptor.getValue(); assertThat(resourceCaptor.getAllValues(), hasSize(1)); assertThat(resource.getPath(), equalTo("/" + DBEERPEDIA.OPENAPI_HOST + DBEERPEDIA.OPENAPI_BASE_PATH + "/breweries")); assertThat(resource.getResourceMethods(), hasSize(1)); ResourceMethod method = resource.getResourceMethods().get(0); assertThat(method.getHttpMethod(), equalTo(HttpMethod.GET)); assertThat(method.getProducedTypes(), contains(MediaType.TEXT_PLAIN_TYPE, MediaType.APPLICATION_JSON_TYPE)); GetRequestHandler requestHandler = (GetRequestHandler) resource.getHandlerInstances().iterator().next(); assertThat(requestHandler, sameInstance(getRequestHandlerMock)); }
private Swagger mockDefinition() throws IOException { byte[] bytes = "spec".getBytes(Charsets.UTF_8); when(fileResourceMock.getInputStream()).thenReturn(new ByteArrayInputStream(bytes)); when(((ResourcePatternResolver) resourceLoader).getResources(anyString())).thenReturn( new org.springframework.core.io.Resource[] {fileResourceMock}); Map<String, Model> definitions = new HashMap<>(); Model myref = new ModelImpl(); definitions.put("myref", myref); Swagger swagger = (new Swagger()).info(new Info().description(DBEERPEDIA.OPENAPI_DESCRIPTION)); swagger.setDefinitions(definitions); when(openApiParserMock.parse("spec")).thenReturn(swagger); return swagger; }
@Override public void initialize(@NonNull HttpConfiguration httpConfiguration) { Resource.Builder resourceBuilder = Resource.builder().path(String.format("/{domain}/%s/{%s:\\d{3}}", SERVLET_ERROR_PATH_PREFIX, SERVLET_ERROR_STATUS_CODE_PARAMETER)); resourceBuilder.addMethod(HttpMethod.GET).handledBy(new ServletErrorHandler()).produces( MediaType.TEXT_PLAIN_TYPE); httpConfiguration.registerResources(resourceBuilder.build()); }
@Test public void loadRedirections_MapRedirection_WithValidData() { // Act ldRedirectionRequestMapper.loadRedirections(httpConfiguration); // Assert Resource resource = (Resource) httpConfiguration.getResources().toArray()[0]; ResourceMethod method = resource.getResourceMethods().get(0); assertThat(method.getHttpMethod(), equalTo(GET)); assertThat(httpConfiguration.getResources(), hasSize(1)); assertThat(resource.getPath(), equalTo("/dbeerpedia.org/special{any: \\/id\\/(.+)$}")); assertThat(resource.getResourceMethods(), hasSize(1)); }
@Test public void loadRepresentations_UsesPathDomainParameter_WithMatchAllDomain() { // Arrange when(supportedMediaTypesScanner.getMediaTypes(any())).thenReturn( new MediaType[] {MediaType.valueOf("text/turtle")}); Site site = new Site.Builder(DBEERPEDIA.BREWERIES).build(); Stage stage = new Stage.Builder(DBEERPEDIA.BREWERIES, site).basePath( DBEERPEDIA.BASE_PATH.stringValue()).build(); Representation representation = new Representation.Builder(DBEERPEDIA.BREWERIES).informationProduct( informationProduct).urlPattern(DBEERPEDIA.URL_PATTERN_VALUE).stage(stage).build(); Map<IRI, Representation> representationMap = new HashMap<>(); representationMap.put(representation.getIdentifier(), representation); when(representationResourceProvider.getAll()).thenReturn(representationMap); // Act ldRepresentationRequestMapper.loadRepresentations(httpConfiguration); // Assert assertThat(httpConfiguration.getResources(), hasSize(1)); Resource resource = (Resource) httpConfiguration.getResources().toArray()[0]; assertThat(resource.getPath(), equalTo("/" + Stage.PATH_DOMAIN_PARAMETER + DBEERPEDIA.BASE_PATH.getLabel() + DBEERPEDIA.URL_PATTERN_VALUE)); }
@Override public void initialize(HttpConfiguration httpConfiguration) { Resource.Builder builder = Resource.builder("/{domain}/runtime-exception"); builder.addMethod(HttpMethod.GET).handledBy(containerRequestContext -> { throw new RuntimeException("Message containing sensitive debug info"); }); httpConfiguration.registerResources(builder.build()); }
/** * Determines if a resource is a controller. * * @param resource resource to test. * @return outcome of controller test. */ private static boolean isController(Resource resource) { final Boolean b1 = resource.getHandlerClasses().stream() .map(c -> c.isAnnotationPresent(Controller.class)) .reduce(Boolean.FALSE, Boolean::logicalOr); final Boolean b2 = resource.getHandlerInstances().stream() .map(o -> o.getClass().isAnnotationPresent(Controller.class)) .reduce(Boolean.FALSE, Boolean::logicalOr); return b1 || b2; }
@Test public void processResourceModel() { ResourceModel.Builder rmb = new ResourceModel.Builder(false); Resource resource = Resource.builder(SomeController.class).build(); rmb.addResource(resource); ResourceModel processedModel = new OzarkModelProcessor().processResourceModel(rmb.build(), null); Resource processedResource = processedModel.getResources().get(0); processedResource.getResourceMethods().forEach(m -> assertTrue(m.getProducedTypes().contains(MediaType.TEXT_HTML_TYPE))); }
private void prepareAppEvent(String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final Method method = mockResource.getClass().getMethod(resourceMethodName); final ResourceMethod resourceMethod = builder.addMethod().handlingMethod(method).handledBy(mockResource, method).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(appEvent.getResourceModel()).thenReturn(model); when(uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
@Override public void onEvent(ApplicationEvent event) { if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { for (Resource resource : event.getResourceModel().getResources()) { resource.getAllMethods().forEach(this::registerUnitOfWorkAnnotations); for (Resource childResource : resource.getChildResources()) { childResource.getAllMethods().forEach(this::registerUnitOfWorkAnnotations); } } } }
private void buildMethod(Resource.Builder builder, Module module, Function fn) { logger.debug("buildMethod; got fn: {}", fn.getSignature()); Map<String, List<String>> annotations = fn.getAnnotations(); List<String> values = annotations.get(an_path); if (values != null) { String subPath = values.get(0); builder = builder.addChildResource(subPath); } //import module namespace tpox="http://tpox-benchmark.com/rest" at "../../etc/samples/tpox/rest_module.xq"; StringBuilder query = new StringBuilder("import module namespace "). append(module.getPrefix()).append("=\"").append(module.getNamespace()). append("\" at \"").append(module.getName()).append("\";\n"); // + int offset = query.length(); //tpox:security-by-id($id) query.append(fn.getPrefix()).append(":").append(fn.getMethod()).append("("); StringBuilder params = new StringBuilder(); int cnt = 0; //declare variable $id external; for (Parameter param: fn.getParameters()) { if (cnt > 0) { query.append(", "); } query.append("$").append(param.getName()); params.append("declare variable $").append(param.getName()).append(" external;\n"); cnt++; } query.append(")\n"); params.append("\n"); query.insert(offset, params.toString()); String full = query.toString(); for (String method: methods) { values = annotations.get("rest:" + method); if (values != null) { buildMethodHandler(builder, method, full, fn); } } }
private void registerCrudApi(String path, Inflector<ContainerRequestContext, Response> handler, Inflector<ContainerRequestContext, Response> linksHandler) { Resource.Builder core = Resource.builder(path); // list endpoints (both do the same thing) core.addMethod(GET).produces(JSON).handledBy(handler); core.addChildResource("search/{querytype}").addMethod(GET).produces(JSON).handledBy(handler); core.addChildResource("search").addMethod(GET).produces(JSON).handledBy(handler); // CRUD endpoints (non-batch) core.addMethod(POST).produces(JSON).consumes(JSON).handledBy(handler); core.addChildResource("{id}").addMethod(GET).produces(JSON).handledBy(handler); core.addChildResource("{id}").addMethod(PUT).produces(JSON).consumes(JSON).handledBy(handler); core.addChildResource("{id}").addMethod(PATCH).produces(JSON).consumes(JSON).handledBy(handler); core.addChildResource("{id}").addMethod(DELETE).produces(JSON).handledBy(handler); // links CRUD endpoints core.addChildResource("{id}/links/{type2}/{id2}").addMethod(GET).produces(JSON).handledBy(linksHandler); core.addChildResource("{id}/links/{type2}").addMethod(GET).produces(JSON).handledBy(linksHandler); core.addChildResource("{id}/links/{id2}").addMethod(POST).produces(JSON).handledBy(linksHandler); core.addChildResource("{id}/links/{id2}").addMethod(PUT).produces(JSON).handledBy(linksHandler); core.addChildResource("{id}/links/{type2}/{id2}").addMethod(DELETE).produces(JSON).handledBy(linksHandler); core.addChildResource("{id}/links").addMethod(DELETE).produces(JSON).handledBy(linksHandler); // CRUD endpoints (batch) Resource.Builder batch = Resource.builder("_batch"); batch.addMethod(POST).produces(JSON).consumes(JSON).handledBy(batchCreateHandler(null)); batch.addMethod(GET).produces(JSON).handledBy(batchReadHandler(null)); batch.addMethod(PUT).produces(JSON).consumes(JSON).handledBy(batchCreateHandler(null)); batch.addMethod(PATCH).produces(JSON).consumes(JSON).handledBy(batchUpdateHandler(null)); batch.addMethod(DELETE).produces(JSON).handledBy(batchDeleteHandler(null)); registerResources(core.build()); registerResources(batch.build()); }
@Override public boolean configure(FeatureContext context) { if (oAuth1Provider != null) { context.register(oAuth1Provider); } context.register(SensorSafeOAuth1ServerFilter.class); if (!context.getConfiguration().isRegistered(OAuth1SignatureFeature.class)) { context.register(OAuth1SignatureFeature.class); } final Map<String, Object> properties = context.getConfiguration().getProperties(); final Boolean propertyResourceEnabled = PropertiesHelper.getValue(properties, OAuth1ServerProperties.ENABLE_TOKEN_RESOURCES, null, Boolean.class); boolean registerResources = propertyResourceEnabled != null ? propertyResourceEnabled : requestTokenUri != null & accessTokenUri != null; if (registerResources) { String requestUri = PropertiesHelper.getValue(properties, OAuth1ServerProperties.REQUEST_TOKEN_URI, null, String.class); if (requestUri == null) { requestUri = requestTokenUri == null ? "requestToken" : requestTokenUri; } String accessUri = PropertiesHelper.getValue(properties, OAuth1ServerProperties.ACCESS_TOKEN_URI, null, String.class); if (accessUri == null) { accessUri = accessTokenUri == null ? "accessToken" : accessTokenUri; } final Resource requestResource = Resource.builder(RequestTokenResource.class).path(requestUri).build(); final Resource accessResource = Resource.builder(AccessTokenResource.class).path(accessUri).build(); context.register(new OAuthModelProcessor(requestResource, accessResource)); } return true; }
@Override public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { final ResourceModel.Builder builder = new ResourceModel.Builder(resourceModel, false); for (Resource resource : resources) { builder.addResource(resource); } return builder.build(); }
public static Set<Resource> getAll(Class<? extends Application> applicationClass, String basePath) { Set<Resource> resources = new HashSet<Resource>(); ApplicationHandler applicationHandler = new ApplicationHandler(applicationClass); ResourceConfig resourceConfig = applicationHandler.getConfiguration(); for (Class<?> aClass : resourceConfig.getClasses()) { if (isAnnotatedResourceClass(aClass)) { Resource resource = Resource.builder(aClass).build(); resources.add(resource); } } return resources; }
private Resource getResource(Inflector<ContainerRequestContext, ChunkedOutput<?>> inflector) { final Resource.Builder resourceBuilder = Resource.builder(); resourceBuilder.path("/"); final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET"); methodBuilder.produces(MediaType.TEXT_PLAIN_TYPE) .handledBy(inflector); return resourceBuilder.build(); }
private NettyContainer getNettyContainer(Resource resource, Class... classes) throws URISyntaxException { ResourceConfig rc = new ResourceConfig() .property(NettyContainer.PROPERTY_BASE_URI, new URI("http:/localhost:0")) .registerResources(resource) .registerInstances(new NettyContainerProvider()) .register(JacksonJsonProvider.class); for (Class aClass : classes) { rc.register(aClass); } return ContainerFactory.createContainer(NettyContainer.class, rc); }