Beispiel #1
0
          @Override
          public void handle(Request request, Response response) {
            if (request.getMethod() == Method.GET) {
              List<String> listDBs = null;
              String r = null;
              try {
                listDBs = storageInstance.retrieveDBs(); //
                Logger.stderr(listDBs.toString());
              } catch (StorageException e) {
                e.printStackTrace();
              }

              ObjectMapper om = new ObjectMapper();

              try {
                r = om.writeValueAsString(listDBs);
                response.setEntity(r, MediaType.APPLICATION_JSON);
              } catch (Exception e) {
                Logger.stderr(OBJECT_MAPPING_ERROR_MESSAGE + e);
                return;
              }

              response.setEntity(r, MediaType.APPLICATION_JSON);
            }
          }
Beispiel #2
0
  /**
   * Handles a call for a local entity. By default, only GET and HEAD methods are implemented.
   *
   * @param request The request to handle.
   * @param response The response to update.
   * @param decodedPath The URL decoded entity path.
   */
  @Override
  protected void handleLocal(Request request, Response response, String decodedPath) {
    int spi = decodedPath.indexOf("!/");
    String fileUri;
    String entryName;
    if (spi != -1) {
      fileUri = decodedPath.substring(0, spi);
      entryName = decodedPath.substring(spi + 2);
    } else {
      fileUri = decodedPath;
      entryName = "";
    }

    LocalReference fileRef = new LocalReference(fileUri);
    if (Protocol.FILE.equals(fileRef.getSchemeProtocol())) {
      final File file = fileRef.getFile();
      if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) {
        handleGet(request, response, file, entryName, getMetadataService());
      } else if (Method.PUT.equals(request.getMethod())) {
        handlePut(request, response, file, entryName);
      } else {
        response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
        response.getAllowedMethods().add(Method.GET);
        response.getAllowedMethods().add(Method.HEAD);
        response.getAllowedMethods().add(Method.PUT);
      }
    } else {
      response.setStatus(Status.SERVER_ERROR_NOT_IMPLEMENTED, "Only works on local files.");
    }
  }
  @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();
    }
  }
Beispiel #4
0
  @Override
  protected int beforeHandle(Request request, Response response) {
    if (Method.OPTIONS.equals(request.getMethod())) {
      Series<Header> requestHeaders =
          (Series<Header>) request.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
      String origin = requestHeaders.getFirstValue("Origin", false, "*");
      String rh = requestHeaders.getFirstValue("Access-Control-Request-Headers", false, "*");
      Series<Header> responseHeaders =
          (Series<Header>) response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
      if (responseHeaders == null) {
        responseHeaders = new Series<Header>(Header.class);
      }
      responseHeaders.add("Access-Control-Allow-Origin", origin);
      responseHeaders.set("Access-Control-Expose-Headers", "Authorization, Link");
      responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
      responseHeaders.add("Access-Control-Allow-Headers", rh);
      responseHeaders.add("Access-Control-Allow-Credentials", "true");
      responseHeaders.add("Access-Control-Max-Age", "60");
      response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders);
      response.setEntity(new EmptyRepresentation());
      return SKIP;
    }

    return super.beforeHandle(request, response);
  }
  /**
   * Allows filtering before its handling by the target Restlet. By default it parses the template
   * variable, adjust the base reference, then extracts the attributes from form parameters (query,
   * cookies, entity) and finally tries to validate the variables as indicated by the {@link
   * #validate(String, boolean, String)} method.
   *
   * @param request The request to filter.
   * @param response The response to filter.
   * @return The {@link Filter#CONTINUE} status.
   */
  @Override
  protected int beforeHandle(Request request, Response response) {
    if (this.validations != null) {
      for (ValidateInfo validate : getValidations()) {
        if (validate.required && !request.getAttributes().containsKey(validate.attribute)) {
          response.setStatus(
              Status.CLIENT_ERROR_BAD_REQUEST,
              "Unable to find the \""
                  + validate.attribute
                  + "\" attribute in the request. Please check your request.");
        } else if (validate.format != null) {
          Object value = request.getAttributes().get(validate.attribute);

          if ((value != null) && !Pattern.matches(validate.format, value.toString())) {
            response.setStatus(
                Status.CLIENT_ERROR_BAD_REQUEST,
                "Unable to validate the value of the \""
                    + validate.attribute
                    + "\" attribute. The expected format is: "
                    + validate.format
                    + " (Java Regex). Please check your request.");
          }
        }
      }
    }

    return CONTINUE;
  }
 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 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());
 }
Beispiel #10
0
  /**
   * Handles a call. The default behavior is to initialize the Restlet by setting the current
   * context using the {@link Context#setCurrent(Context)} method and by attempting to start it,
   * unless it was already started. If an exception is thrown during the start action, then the
   * response status is set to {@link Status#SERVER_ERROR_INTERNAL}.
   *
   * <p>Subclasses overriding this method should make sure that they call super.handle(request,
   * response) before adding their own logic.
   *
   * @param request The request to handle.
   * @param response The response to update.
   */
  public void handle(Request request, Response response) {
    // Associate the response to the current thread
    Response.setCurrent(response);

    // Associate the context to the current thread
    if (getContext() != null) {
      Context.setCurrent(getContext());
    }

    // Check if the Restlet was started
    if (isStopped()) {
      try {
        start();
      } catch (Exception e) {
        // Occurred while starting the Restlet
        getContext().getLogger().log(Level.WARNING, UNABLE_TO_START, e);
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
      }

      if (!isStarted()) {
        // No exception raised but the Restlet somehow couldn't be
        // started
        getContext().getLogger().log(Level.WARNING, UNABLE_TO_START);
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
      }
    }
  }
  @Test
  @SuppressWarnings("unchecked")
  public void shouldSetAnyOtherExceptionResponse() throws Exception {

    // Given
    Request request = mock(Request.class);
    Response response = mock(Response.class);
    Exception exception = new Exception("MESSAGE");
    Status status = new Status(444, exception);

    given(response.getStatus()).willReturn(status);

    // When
    exceptionFilter.afterHandle(request, response);

    // Then
    ArgumentCaptor<JacksonRepresentation> exceptionResponseCaptor =
        ArgumentCaptor.forClass(JacksonRepresentation.class);
    verify(response).setEntity(exceptionResponseCaptor.capture());
    Map<String, String> responseBody =
        (Map<String, String>) exceptionResponseCaptor.getValue().getObject();
    assertThat(responseBody)
        .containsOnly(entry("error", "server_error"), entry("error_description", "MESSAGE"));

    ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
    verify(response).setStatus(statusCaptor.capture());
    assertThat(statusCaptor.getValue().getCode()).isEqualTo(500);
    assertThat(statusCaptor.getValue().getThrowable()).isEqualTo(exception);
  }
  @Override
  protected int doHandle(Request request, Response response) {

    super.doHandle(request, response);

    if (response.getStatus().isSuccess() && request.getMethod().equals(Method.GET)) {
      boolean isHtml = false;
      for (Preference<MediaType> mt : request.getClientInfo().getAcceptedMediaTypes()) {
        if (mt.getMetadata().includes(MediaType.APPLICATION_XHTML)
            || mt.getMetadata().includes(MediaType.TEXT_HTML)) {
          isHtml = true;
          break;
        }
      }
      if (isHtml) {
        try {
          response.setEntity(toHtml(request, response));
        } catch (SlipStreamException e) {
          // ok it failed generating html... do we care?
        }
      }
    }

    return CONTINUE;
  }
 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 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()
            + ")");
  }
Beispiel #15
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 synchronized void commit(Response response) {
   if ((response != null) && !response.isCommitted()) {
     getConnection().commit(response);
     response.setCommitted(true);
   }
 }
  /**
   * 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;
  }
  /**
   * 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 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());
  }
 /** @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 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());
  }
 /** Tests status getting/setting. */
 public void testStatus() throws Exception {
   final Request request = getRequest();
   final Response response = getResponse(request);
   response.setStatus(Status.SUCCESS_OK);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
   assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, response.getStatus());
 }
  /**
   * @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 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 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());
  }
  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 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 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 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());
 }
  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());
  }