private void _test(ApplicationHandler handler, String requestUri, String expected)
     throws InterruptedException, ExecutionException {
   final ContainerResponse response =
       handler.apply(RequestContextBuilder.from(requestUri, "GET").build()).get();
   assertEquals(200, response.getStatus());
   assertEquals(expected, response.getEntity());
 }
 @Test
 public void testBadURIResource() throws ExecutionException, InterruptedException {
   initiateWebApplication(BadURIResource.class, URIStringReaderProvider.class);
   final ContainerResponse responseContext =
       getResponseContext(UriBuilder.fromPath("/").queryParam("d", "::::123").build().toString());
   assertEquals(404, responseContext.getStatus());
 }
  @Test
  public void testDefaultPathParamValueFoo() throws ExecutionException, InterruptedException {
    initiateWebApplication(FooResource.class);

    ContainerResponse response = getResponseContext("/foo");
    Assert.assertEquals("default-id", response.getEntity());
  }
  @Override
  public ContainerResponse apply(final ContainerRequest requestContext) {
    final Object resource = routingContextFactory.get().peekMatchedResource();

    final ProcessingContext processingCtx = invocationContextFactory.get();
    if (method.isSuspendDeclared()) {
      processingCtx.setSuspendTimeout(method.getSuspendTimeout(), method.getSuspendTimeoutUnit());
    }
    requestContext.setProperty(ReaderInterceptorExecutor.INTERCEPTORS, getReaderInterceptors());
    requestContext.setProperty(WriterInterceptorExecutor.INTERCEPTORS, getWriterInterceptors());
    final Response response = dispatcher.dispatch(resource, requestContext);

    if (method.isSuspendDeclared()) {
      processingCtx.setResponse(resource);
      processingCtx.trySuspend();
    }

    final ContainerResponse responseContext = new ContainerResponse(requestContext, response);
    final Invocable invocable = method.getInvocable();
    responseContext.setEntityAnnotations(invocable.getHandlingMethod().getDeclaredAnnotations());

    if (responseContext.hasEntity()
        && !(responseContext.getEntityType() instanceof ParameterizedType)) {
      Type invocableType = invocable.getResponseType();
      if (invocableType != null
          && Void.TYPE != invocableType
          && Void.class != invocableType
          && invocableType != Response.class) {
        responseContext.setEntityType(invocableType);
      }
    }

    return responseContext;
  }
  @Test
  public void testDefaultPathParamValueOnAnotherResource1()
      throws ExecutionException, InterruptedException {
    initiateWebApplication(AnotherResource.class);

    ContainerResponse response = getResponseContext("/foo/test/bar/barrr");
    Assert.assertEquals("test:barrr", response.getEntity());
  }
 @Test
 public void testLazyConverter() throws Exception {
   final ApplicationHandler application =
       new ApplicationHandler(new ResourceConfig(MyLazyParamProvider.class, Resource.class));
   final ContainerResponse response =
       application.apply(RequestContextBuilder.from("/resource", "GET").build()).get();
   assertEquals(400, response.getStatus());
 }
 @Test
 public void testClientAndServerProvider2() throws ExecutionException, InterruptedException {
   final ResourceConfig resourceConfig =
       new ResourceConfig(Resource.class, MyServerAndClientContrainedToClientFilter.class);
   ApplicationHandler handler = new ApplicationHandler(resourceConfig);
   final ContainerResponse response =
       handler.apply(RequestContextBuilder.from("/resource", "GET").build()).get();
   Assert.assertEquals(200, response.getStatus());
 }
  @Test
  public void testBadPrimitiveWrapperValue() throws ExecutionException, InterruptedException {
    final ContainerResponse responseContext =
        apply(
            RequestContextBuilder.from("/wrappers", "GET")
                .accept("application/int")
                .header("int", "abcdef")
                .build());

    assertEquals(400, responseContext.getStatus());
  }
  @Test
  public void testListOfStringReaderProvider() throws ExecutionException, InterruptedException {
    initiateWebApplication(ListOfStringResource.class, ListOfStringReaderProvider.class);
    final ContainerResponse responseContext =
        getResponseContext(
            UriBuilder.fromPath("/").queryParam("l", "1,2," + "3").build().toString());

    final String s = (String) responseContext.getEntity();

    assertEquals(Collections.singletonList(Arrays.asList("1", "2", "3")).toString(), s);
  }
 @Test
 public void testInvalidSubResource() throws ExecutionException, InterruptedException {
   ApplicationHandler handler = new ApplicationHandler(new ResourceConfig(WrongResource.class));
   _test(handler, "/wrong", "ok");
   try {
     final ContainerResponse response =
         handler.apply(RequestContextBuilder.from("/wrong/locator", "GET").build()).get();
     assertEquals(500, response.getStatus());
     fail("Should throw exception caused by validation errors of Sub Resource.");
   } catch (Throwable e) {
     // ok - Should throw exception caused by validation errors of Sub Resource.
   }
 }
 @Test
 public void testResourceAndProviderConstrainedToServer()
     throws ExecutionException, InterruptedException {
   final ResourceConfig resourceConfig =
       new ResourceConfig(ResourceAndProviderConstrainedToServer.class);
   ApplicationHandler handler = new ApplicationHandler(resourceConfig);
   final ContainerResponse response =
       handler
           .apply(RequestContextBuilder.from("/resource-and-provider-server", "GET").build())
           .get();
   Assert.assertEquals(200, response.getStatus());
   Assert.assertEquals(
       "called", response.getHeaderString("ResourceAndProviderConstrainedToServer"));
 }
 public ContainerResponse call(ContainerRequest containerRequest) {
   ByteBuffer byteBuf = ByteBuffer.allocate(BUFFER_CAPACITY);
   ContainerResponse response;
   try {
     response = handler.apply(containerRequest, new ByteBufferOutputStream(byteBuf)).get();
   } catch (Exception e) {
     logger.debug("Failed while handling the request - " + containerRequest, e);
     response = new ContainerResponse(containerRequest, Response.serverError().build());
   }
   ContainerResponseWriter responseWriter = containerRequest.getResponseWriter();
   OutputStream os = responseWriter.writeResponseStatusAndHeaders(response.getLength(), response);
   response.setEntityStream(os);
   return response;
 }
    @Test
    public void testEmptyProduces() throws Exception {
      final ResourceConfig rc = new ResourceConfig(EmptyProducesTestResource.class);
      rc.property(ServerProperties.WADL_FEATURE_DISABLE, false);

      final ApplicationHandler applicationHandler = new ApplicationHandler(rc);

      final ContainerResponse containerResponse =
          applicationHandler
              .apply(
                  new ContainerRequest(
                      URI.create("/"),
                      URI.create("/application.wadl"),
                      "GET",
                      null,
                      new MapPropertiesDelegate()))
              .get();

      assertEquals(200, containerResponse.getStatus());

      ((ByteArrayInputStream) containerResponse.getEntity()).reset();

      final DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
      bf.setNamespaceAware(true);
      bf.setValidating(false);
      if (!SaxHelper.isXdkDocumentBuilderFactory(bf)) {
        bf.setXIncludeAware(false);
      }
      final DocumentBuilder b = bf.newDocumentBuilder();
      final Document d = b.parse((InputStream) containerResponse.getEntity());
      printSource(new DOMSource(d));
      final XPath xp = XPathFactory.newInstance().newXPath();
      xp.setNamespaceContext(
          new SimpleNamespaceResolver("wadl", "http://wadl.dev.java.net/2009/02"));

      final NodeList responseElements =
          (NodeList)
              xp.evaluate(
                  "/wadl:application/wadl:resources[@path!='application.wadl']//wadl:method/wadl:response",
                  d,
                  XPathConstants.NODESET);

      for (int i = 0; i < responseElements.getLength(); i++) {
        final Node item = responseElements.item(i);

        assertEquals(0, item.getChildNodes().getLength());
        assertEquals(0, item.getAttributes().getLength());
      }
    }
 @Test
 public void testFiltersAnnotated() throws ExecutionException, InterruptedException {
   final ResourceConfig resourceConfig =
       new ResourceConfig(
           MyServerFilter.class,
           MyClientFilter.class,
           MyServerWrongFilter.class,
           MyServerFilterWithoutConstraint.class,
           Resource.class);
   resourceConfig.registerInstances(new MyServerWrongFilter2(), new MyServerFilter2());
   ApplicationHandler handler = new ApplicationHandler(resourceConfig);
   final ContainerResponse response =
       handler.apply(RequestContextBuilder.from("/resource", "GET").build()).get();
   Assert.assertEquals("called", response.getHeaderString("MyServerFilter"));
   Assert.assertEquals("called", response.getHeaderString("MyServerFilter2"));
   Assert.assertEquals("called", response.getHeaderString("MyServerFilterWithoutConstraint"));
 }
 @Test
 public void testSpecificApplication() throws ExecutionException, InterruptedException {
   Application app =
       new Application() {
         @Override
         public Set<Class<?>> getClasses() {
           final HashSet<Class<?>> classes = Sets.newHashSet();
           classes.add(Resource.class);
           classes.add(MyClientFilter.class);
           classes.add(MyServerWrongFilter.class);
           return classes;
         }
       };
   ApplicationHandler handler = new ApplicationHandler(app);
   final ContainerResponse response =
       handler.apply(RequestContextBuilder.from("/resource", "GET").build()).get();
   Assert.assertEquals(200, response.getStatus());
 }
    @Test
    public void testEnableWadl() throws ExecutionException, InterruptedException {
      final ResourceConfig rc = new ResourceConfig(WidgetsResource.class, ExtraResource.class);
      rc.property(ServerProperties.WADL_FEATURE_DISABLE, false);

      final ApplicationHandler applicationHandler = new ApplicationHandler(rc);

      final ContainerResponse containerResponse =
          applicationHandler
              .apply(
                  new ContainerRequest(
                      URI.create("/"),
                      URI.create("/application.wadl"),
                      "GET",
                      null,
                      new MapPropertiesDelegate()))
              .get();

      assertEquals(200, containerResponse.getStatus());
    }
 public String test(HttpMethodOverrideFilter.Source... sources) {
   ResourceConfig rc = new ResourceConfig(Resource.class);
   HttpMethodOverrideFilter.enableFor(rc, sources);
   ApplicationHandler handler = new ApplicationHandler(rc);
   try {
     ContainerResponse response =
         handler
             .apply(
                 RequestContextBuilder.from("", "/?_method=DELETE", "POST")
                     .header("X-HTTP-Method-Override", "PUT")
                     .build())
             .get();
     if (Response.Status.OK.equals(response.getStatusInfo())) {
       return (String) response.getEntity();
     } else {
       return "" + response.getStatus();
     }
   } catch (Exception e) {
     e.printStackTrace();
     return e.getMessage();
   }
 }
    /**
     * Test overriding WADL's /application/resources/@base attribute.
     *
     * @throws Exception in case of unexpected test failure.
     */
    @Test
    public void testCustomWadlResourcesBaseUri() throws Exception {
      final ResourceConfig rc = new ResourceConfig(WidgetsResource.class, ExtraResource.class);
      rc.property(ServerProperties.WADL_GENERATOR_CONFIG, MyWadlGeneratorConfig.class.getName());

      final ApplicationHandler applicationHandler = new ApplicationHandler(rc);

      final ContainerResponse containerResponse =
          applicationHandler
              .apply(
                  new ContainerRequest(
                      URI.create("/"),
                      URI.create("/application.wadl"),
                      "GET",
                      null,
                      new MapPropertiesDelegate()))
              .get();

      final DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
      bf.setNamespaceAware(true);
      bf.setValidating(false);
      if (!SaxHelper.isXdkDocumentBuilderFactory(bf)) {
        bf.setXIncludeAware(false);
      }
      final DocumentBuilder b = bf.newDocumentBuilder();

      ((ByteArrayInputStream) containerResponse.getEntity()).reset();

      final Document d = b.parse((InputStream) containerResponse.getEntity());
      printSource(new DOMSource(d));
      final XPath xp = XPathFactory.newInstance().newXPath();
      xp.setNamespaceContext(
          new SimpleNamespaceResolver("wadl", "http://wadl.dev.java.net/2009/02"));
      // check base URI
      final String val =
          (String) xp.evaluate("/wadl:application/wadl:resources/@base", d, XPathConstants.STRING);
      assertEquals(val, MyWadlGeneratorConfig.MyWadlGenerator.CUSTOM_RESOURCES_BASE_URI);
    }
Exemple #19
0
  @Override
  public void filter(
      ContainerRequestContext requestContext, ContainerResponseContext responseContext)
      throws IOException {
    if (!responseContext.hasEntity()
        && !((ContainerResponse) responseContext).isMappedFromException()
        && responseContext.getStatus() >= 400
        && responseContext.getStatus() < 600) {
      throw new WebApplicationException(responseContext.getStatus());
    }

    if (responseContext.getStatus() == 406 || responseContext.getStatus() == 415) {
      List<MediaType> types =
          workersProvider.get().getMessageBodyWriterMediaTypesByType(Object.class);
      MediaType mediaType;
      if (types.size() > 0) {
        mediaType = types.get(0);
      } else {
        mediaType = MediaType.WILDCARD_TYPE;
      }
      ((ContainerResponse) responseContext).setMediaType(mediaType);
    }
  }
 /**
  * Gets byte buffer from container response
  *
  * @param response
  * @return
  */
 protected ByteBuffer getContent(ContainerResponse response) {
   return ((ByteBufferOutputStream) response.getEntityStream()).getBuffer();
 }