Esempio n. 1
0
 /**
  * Allows filtering after its handling by the target Restlet. Does nothing by default.
  *
  * @param request The request to filter.
  * @param response The response to filter.
  */
 @Override
 public void afterHandle(Request request, Response response) {
   // Check if encoding of the response entity is needed
   if (isEncodingResponse() && canEncode(response.getEntity())) {
     response.setEntity(encode(request.getClientInfo(), response.getEntity()));
   }
 }
  @Override
  public void setUp() throws Exception {
    super.setUp();

    try {
      if (!testKeystoreFile.exists()) {
        // Prepare a temporary directory for the tests
        BioUtils.delete(this.testDir, true);
        this.testDir.mkdir();
        // Copy the keystore into the test directory
        Response response =
            new Client(Protocol.CLAP)
                .handle(new Request(Method.GET, "clap://class/org/restlet/test/engine/dummy.jks"));

        if (response.getEntity() != null) {
          OutputStream outputStream = new FileOutputStream(testKeystoreFile);
          response.getEntity().write(outputStream);
          outputStream.flush();
          outputStream.close();
        } else {
          throw new Exception("Unable to find the dummy.jks file in the classpath.");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /** @see ProviderTestService#mMapPost(javax.ws.rs.core.MultivaluedMap) */
 public void testMultivaluedMapPost() throws Exception {
   final Response response = post("MultivaluedMap", createForm().getWebRepresentation());
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final MediaType respMediaType = response.getEntity().getMediaType();
   assertEqualMediaType(MediaType.TEXT_PLAIN, respMediaType);
   final String respEntity = response.getEntity().getText();
   assertEquals("[(lastname,Merkel), (firstname,Angela)]", respEntity);
 }
  public void testDecoded1() throws Exception {
    Response response = get("decoded/x");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("x", response.getEntity().getText());

    response = get("decoded/sjkg");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("sjkg", response.getEntity().getText());
  }
  public void testX2() throws Exception {
    Response response = get("abcdef/1234");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("bcd\n12", response.getEntity().getText());

    response = get("aXYZef/AB34");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("XYZ\nAB", response.getEntity().getText());
  }
  public void testX() throws Exception {
    Response response = get("abc123");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("123", response.getEntity().getText());

    response = get("abcdef");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("def", response.getEntity().getText());
  }
  public void testGetMediaType() throws IOException {
    Response response = get("MediaType/467");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("467/*", response.getEntity().getText());

    response = get("MediaType/abc");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc/*", response.getEntity().getText());
  }
 @Override
 protected void afterHandle(Request request, Response response) {
   if (response.isEntityAvailable()
       && response.getEntity().getEncodings().contains(Encoding.FREEMARKER)) {
     TemplateRepresentation representation =
         new TemplateRepresentation(
             response.getEntity(), this.configuration, response.getEntity().getMediaType());
     representation.setDataModel(createDataModel(request, response));
     response.setEntity(representation);
   }
 }
  public void testWithDefault() throws Exception {
    Request request = createGetRequest("headerWithDefault");
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME, "abc");
    Response response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());

    request = createGetRequest("headerWithDefault");
    response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("default", response.getEntity().getText());
  }
  public void testEncodedWithDefault() throws Exception {
    Response response = get("encodedWithDefault;m=1;m=2;x=3");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("[1, 2]", response.getEntity().getText());

    response = get("encodedWithDefault;m=1;i=2;x=3");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("[1]", response.getEntity().getText());

    response = get("encodedWithDefault;a=1;i=2;x=3");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("[default]", response.getEntity().getText());
  }
  /**
   * Redirects a given call to a target reference. In the default implementation, the request HTTP
   * headers, stored in the request's attributes, are removed before dispatching. After dispatching,
   * the response HTTP headers are also removed to prevent conflicts with the main call.
   *
   * @param targetRef The target reference with URI variables resolved.
   * @param request The request to handle.
   * @param response The response to update.
   */
  protected void outboundServerRedirect(Reference targetRef, Request request, Response response) {
    Restlet next = (getApplication() == null) ? null : getApplication().getOutboundRoot();

    if (next == null) {
      next = getContext().getClientDispatcher();
    }

    serverRedirect(next, targetRef, request, response);
    if (response.getEntity() != null
        && !request.getResourceRef().getScheme().equalsIgnoreCase(targetRef.getScheme())) {
      // Distinct protocol, this data cannot be exposed.
      response.getEntity().setLocationRef((Reference) null);
    }
  }
  /**
   * Returns the list of identifiers for the mails in the inbox
   *
   * @return The list of identifiers.
   * @throws ResourceException
   */
  protected List<String> getMailIdentifiers() throws ResourceException {
    final List<String> result = new ArrayList<String>();

    // 1 - Get to mailbox content
    final Request request = new Request(Method.GET, getMailboxUri());
    if (getMailboxChallengeScheme() != null) {
      final ChallengeResponse challengeResponse =
          new ChallengeResponse(
              getMailboxChallengeScheme(), getMailboxLogin(), getMailboxPassword());
      request.setChallengeResponse(challengeResponse);
    }
    final Response response = getContext().getClientDispatcher().handle(request);

    if (!response.getStatus().isSuccess()) {
      throw new ResourceException(response.getStatus(), "Cannot get the mail iddentifiers.");
    }

    // 2 - Parse the list of mails
    if (response.isEntityAvailable()) {
      final DomRepresentation rep = new DomRepresentation(response.getEntity());
      for (final Node node : rep.getNodes("/emails/email/@href")) {
        final String href = node.getNodeValue();
        if (href.startsWith("/")) {
          result.add(href.substring(1));
        } else {
          result.add(href);
        }
      }
    }

    return result;
  }
Esempio n. 13
0
  @Override
  public void sendResponse(Response response) throws IOException {
    // Add call headers
    Header header;

    for (Iterator<Header> iter = getResponseHeaders().iterator(); iter.hasNext(); ) {
      header = iter.next();
      getConnection().getResponse().addHeader(header.getName(), header.getValue());
    }

    // Set the status code in the response. We do this after adding the
    // headers because when we have to rely on the 'sendError' method,
    // the Servlet containers are expected to commit their response.
    if (Status.isError(getStatusCode()) && (response.getEntity() == null)) {
      try {
        getConnection().getResponse().sendError(getStatusCode(), getReasonPhrase());
      } catch (IOException ioe) {
        getLogger().log(Level.WARNING, "Unable to set the response error status", ioe);
      }
    } else {
      // Send the response entity
      getConnection().getResponse().setStatus(getStatusCode());
      super.sendResponse(response);
    }
  }
  /**
   * Tests partial Get requests.
   *
   * @throws IOException
   * @throws NoSuchAlgorithmException
   */
  @Test
  public void testGet() throws IOException, NoSuchAlgorithmException {
    Client client = new Client(Protocol.HTTP);

    // Test partial Get.
    Request request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/");
    StringRepresentation rep = new StringRepresentation("0123456789");
    try {
      DigesterRepresentation digester = new DigesterRepresentation(rep);
      // Such representation computes the digest while
      // consuming the wrapped representation.
      digester.exhaust();
      // Set the digest with the computed one
      digester.setDigest(digester.computeDigest());
      request.setEntity(digester);

      Response response = client.handle(request);

      assertEquals(Status.SUCCESS_OK, response.getStatus());
      digester = new DigesterRepresentation(response.getEntity());
      digester.exhaust();
      assertTrue(digester.checkDigest());

      client.stop();
    } catch (Exception e) {
      fail(e.getMessage());
    }
  }
  public Response sendRequest(Request request) throws IOException {
    injectCustomSecurityMechanism(request);

    if (log.isLoggable(Level.FINE)) {
      RestClientLogHelper.logHttpRequest(log, Level.FINE, request);
    }

    Client client = initClient();
    Response response = client.handle(request);

    if (log.isLoggable(Level.FINE)) {
      RestClientLogHelper.logHttpResponse(log, Level.FINE, response);
    }

    if (response.getStatus().isSuccess()) {
      return response;
    } else if (response.getStatus().equals(Status.CLIENT_ERROR_UNAUTHORIZED)) {
      // retry request with additional authentication
      Request retryRequest = createChallengeResponse(response);
      return sendRequest(retryRequest);
    }

    throw new RepositoryException(
        "Encountered error while retrieving http response (HttpStatus: "
            + response.getStatus()
            + ", Body: "
            + response.getEntity().getText()
            + ")");
  }
 public void testXmlTransformPost() throws Exception {
   final Response response =
       post("source", new StringRepresentation("abcdefg", MediaType.TEXT_XML));
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   assertEquals("abcdefg", response.getEntity().getText());
 }
 public void testCookies() throws IOException {
   final Request request = createGetRequest("cookies/cookieName");
   request.getCookies().add(new Cookie("cookieName", "cookie-value"));
   final Response response = accessServer(request);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   assertEquals("cookieName=cookie-value", response.getEntity().getText());
 }
 public void testCharSequenceGet() throws Exception {
   final Response response = get("CharSequence");
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final Representation entity = response.getEntity();
   assertEquals(ProviderTestService.createCS(), entity.getText());
 }
 public void testXmlTransformGet() throws Exception {
   final Response response = get("source");
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final String entity = response.getEntity().getText();
   assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><abc/>", entity);
 }
 public void testByteArrayPost() throws Exception {
   final Representation entity =
       new StringRepresentation("big test", MediaType.APPLICATION_OCTET_STREAM);
   final Response response = post("byteArray", entity);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   assertEquals("big test", response.getEntity().getText());
 }
  public void testGetBigDecimal() throws IOException {
    Response response = get("BigDecimal/413624654744743534745767");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("413624654744743534745767", response.getEntity().getText());

    response = get("BigDecimal/abc");
    assertTrue(response.getStatus().isError());
  }
  public void testGetInt() throws IOException {
    Response response = get("int/467");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("467", response.getEntity().getText());

    response = get("int/abc");
    assertTrue(response.getStatus().isError());
  }
  public void testWithoutPath() throws Exception {
    Response response = get(";firstname=Angela;lastname=Merkel");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("Angela Merkel", response.getEntity().getText());

    response = get(";lastname=Merkel;firstname=Angela");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("Angela Merkel", response.getEntity().getText());

    response = get(";firstname=Goofy");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("Goofy null", response.getEntity().getText());

    response = get(";lastname=Goofy");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("null Goofy", response.getEntity().getText());
  }
  public void testGetMn() throws IOException {
    Response response = get("mn467");
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("467", response.getEntity().getText());

    response = get("mnabc");
    assertTrue(response.getStatus().isError());
    assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus());
  }
  public void testStringGet() throws Exception {
    getAndExpectAlphabet("String");

    final Response response = get("String2");
    sysOutEntityIfError(response);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    final Representation entity = response.getEntity();
    assertEquals(ProviderTestService.STRING2, entity.getText());
  }
 public void testBufferedReaderPost() throws Exception {
   Representation entity =
       new StringRepresentation("big test", MediaType.APPLICATION_OCTET_STREAM);
   final Response response = post("BufferedReader", entity);
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   entity = response.getEntity();
   assertEquals("big test", entity.getText());
 }
  /**
   * @param subPath
   * @throws IOException
   */
  private Response getAndExpectAlphabet(String subPath) throws IOException {
    Response response = get(subPath);
    sysOutEntityIfError(response);
    assertEquals(Status.SUCCESS_OK, response.getStatus());

    Representation entity = response.getEntity();
    assertEquals(ProviderTestService.ALPHABET, entity.getText());
    return response;
  }
  public void testHttpHeaders() throws IOException {
    Request request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME);
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME, "abc");
    Response response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());

    request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME);
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME.toLowerCase(), "abc");
    response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());

    request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME);
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME.toUpperCase(), "abc");
    response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());
  }
Esempio n. 29
0
  private NettyHttpResponse writeEntity(Response ares, Representation entity) {
    InputStream in = null;
    try {
      setHeader(ares);

      if (!ares.getStatus().isSuccess()) {
        if (ares.getStatus().getCode() == 401) {
          header("WWW-Authenticate", "Basic realm=\"secure\"");
        }
        if (ares.getEntity() == null || ares.getEntity().getStream() == null) return end();
        InputStream istream = ares.getEntity().getStream();
        try {
          return content(IOUtil.toByteArray(istream)).end();
        } finally {
          IOUtil.closeQuietly(istream);
        }
      }

      // TODO: Shouldn't have to do this, but without it we sometimes seem to get two Content-Length
      // headers in the response.
      header("Content-Length", (String) null);
      header("Content-Length", entity.getSize());
      header("Content-Type", entity.getMediaType().getName());

      in = entity.getStream();
      // byte[] data = IOUtil.toByteArray(in) ;
      // content(data) ;

      byte[] data = new byte[1024 * 16];
      int nRead = 0;
      while ((nRead = in.read(data, 0, data.length)) != -1) {
        content(ChannelBuffers.copiedBuffer(data, 0, nRead));
      }

    } catch (Throwable ex) {
      error(ex);
    } finally {
      IOUtil.closeQuietly(in);
      end();
    }
    return this;
  }
Esempio n. 30
0
 public void testHead2() throws Exception {
   final Response responseGett = get("headTest2", MediaType.TEXT_HTML);
   final Response responseHead = head("headTest2", MediaType.TEXT_HTML);
   if (responseGett.getStatus().isError()) {
     System.out.println(responseGett.getEntity().getText());
   }
   assertEquals(Status.SUCCESS_OK, responseGett.getStatus());
   if (responseHead.getStatus().isError()) {
     System.out.println(responseHead.getEntity().getText());
   }
   assertEquals(Status.SUCCESS_OK, responseHead.getStatus());
   final Representation entityGett = responseGett.getEntity();
   final Representation entityHead = responseHead.getEntity();
   assertNotNull(entityGett);
   assertNotNull("Must not be null to read the entity headers", entityHead);
   assertEqualMediaType(MediaType.TEXT_HTML, entityGett.getMediaType());
   assertEqualMediaType(MediaType.TEXT_HTML, entityHead.getMediaType());
   assertEquals("4711", entityGett.getText());
   assertEquals("The entity text of the head request must be null", null, entityHead.getText());
 }