org.mockserver.matchers.Times Java Examples

The following examples show how to use org.mockserver.matchers.Times. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LowLatencyMontageClientTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private void addRenderStackMetaDataResponse() {
    final String requestPath = getRenderStackRequestPath();
    final StackMetaData stackMetaData = new StackMetaData(acquireStackId, null);
    stackMetaData.setState(StackMetaData.StackState.LOADING);
    final JsonBody responseBody = json(stackMetaData.toJson());
    mockServer
            .when(
                    HttpRequest.request()
                            .withMethod("GET")
                            .withPath(requestPath),
                    Times.once()
            )
            .respond(
                    HttpResponse.response()
                            .withStatusCode(HttpStatus.SC_OK)
                            .withHeader("Content-Type", responseBody.getContentType())
                            .withBody(responseBody)
            );
}
 
Example #2
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public AcmeMockServerBuilder addCertificateRequestAndResponse(String certificateUrl, String expectedCertificateRequestBody, String certificateResponseBody, String certificateReplayNonce, int certificateStatusCode) {
    HttpResponse response = response()
            .withHeader("Cache-Control", "public, max-age=0, no-cache")
            .withHeader("Content-Type", "application/pem-certificate-chain")
            .withHeader("Replay-Nonce", certificateReplayNonce)
            .withBody(certificateResponseBody)
            .withStatusCode(certificateStatusCode);
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(certificateUrl)
                    .withBody(expectedCertificateRequestBody),
            Times.once())
            .respond(response);

    return this;
}
 
Example #3
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public AcmeMockServerBuilder addCheckOrderRequestAndResponse(String orderUrl, String expectedCheckCertificateRequestBody, String checkCertificateResponseBody, String checkOrderReplayNonce, int checkCertificateStatusCode) {
    HttpResponse response = response()
            .withHeader("Cache-Control", "public, max-age=0, no-cache")
            .withHeader("Content-Type", "application/json")
            .withHeader("Replay-Nonce", checkOrderReplayNonce)
            .withBody(checkCertificateResponseBody)
            .withStatusCode(checkCertificateStatusCode);
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(orderUrl)
                    .withBody(expectedCheckCertificateRequestBody),
            Times.once())
            .respond(response);

    return this;
}
 
Example #4
Source File: LowLatencyMontageClientTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private void addAcqNextTileResponse(final AcquisitionTileList acquisitionTileList) {

        final JsonBody responseBody = json(acquisitionTileList.toJson());

        mockServer
                .when(
                        HttpRequest.request()
                                .withMethod("POST")
                                .withPath(getBaseAcquisitionPath() + "/next-tile"),
                        Times.once()
                )
                .respond(
                        HttpResponse.response()
                                .withStatusCode(HttpStatus.SC_OK)
                                .withHeader("Content-Type", responseBody.getContentType())
                                .withBody(responseBody)
        );
    }
 
Example #5
Source File: TestAuth.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testEnableAuth() throws Exception {
  VaultConfiguration conf = VaultConfigurationBuilder.newVaultConfiguration()
      .withAddress(address)
      .withToken(token)
      .build();

  new MockServerClient(localhost, mockServerRule.getPort())
      .when(
      HttpRequest.request()
          .withMethod("POST")
          .withHeader(tokenHeader)
          .withPath("/v1/sys/auth/app-id")
          .withBody("{\"type\":\"app-id\"}"),
      Times.exactly(1)
  )
  .respond(
      HttpResponse.response()
          .withStatusCode(HttpStatusCode.NO_CONTENT_204.code())
          .withHeader(contentJson)
  );

  VaultClient vault = new VaultClient(conf);
  assertTrue(vault.sys().auth().enable("app-id", "app-id"));
}
 
Example #6
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public AcmeMockServerBuilder addCertificateRequestAndResponse(String certificateUrl, String certificateResponseBody, int certificateStatusCode, String certificateReplayNonce) {
    HttpResponse response = response()
            .withHeader("Retry-After", "0")
            .withHeader("Cache-Control", "public, max-age=0, no-cache")
            .withHeader("Content-Type", "application/pem-certificate-chain")
            .withHeader("Replay-Nonce", certificateReplayNonce)
            .withBody(certificateResponseBody)
            .withStatusCode(certificateStatusCode);
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(certificateUrl)
                    .withBody(""),
            Times.once())
            .respond(response);

    return this;
}
 
Example #7
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public AcmeMockServerBuilder addCheckOrderRequestAndResponse(String orderUrl, String checkCertificateResponseBody, int checkCertificateStatusCode, String checkOrderReplayNonce) {
    HttpResponse response = response()
            .withHeader("Retry-After", "0")
            .withHeader("Cache-Control", "public, max-age=0, no-cache")
            .withHeader("Content-Type", "application/json")
            .withHeader("Replay-Nonce", checkOrderReplayNonce)
            .withBody(checkCertificateResponseBody)
            .withStatusCode(checkCertificateStatusCode);
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(orderUrl)
                    .withBody(""),
            Times.once())
            .respond(response);

    return this;
}
 
Example #8
Source File: RsExplorerTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void findInvalidSitemapDocument() throws Exception {
  String path = "/.well-known/resourcesync";

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withBody(createValidXml())
    );

  RsExplorer explorer = new RsExplorer(getHttpclient(), getRsContext());
  ResultIndex index = new ResultIndex();
  Result<RsRoot> result = explorer.explore(composeUri(path), index, null);

  assertThat(result.getUri(), equalTo(composeUri(path)));
  assertThat(result.getStatusCode(), equalTo(200));
  assertThat(result.getErrors().isEmpty(), is(false));
  assertThat(result.getErrors().get(0), instanceOf(JAXBException.class));
  assertThat(result.getContent().isPresent(), is(false));
  //result.listErrors().forEach(Throwable::printStackTrace);
}
 
Example #9
Source File: RsExplorerTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void receiveStatusError() throws Exception {
  String path = "/.well-known/resourcesync";

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(404)
      .withBody("Document not found")
    );

  RsExplorer explorer = new RsExplorer(getHttpclient(), getRsContext());
  ResultIndex index = new ResultIndex();
  Result<RsRoot> result = explorer.explore(composeUri(path), index, null);

  assertThat(result.getUri(), equalTo(composeUri(path)));
  assertThat(result.getStatusCode(), equalTo(404));
  assertThat(result.getErrors().isEmpty(), is(false));
  assertThat(result.getErrors().get(0), instanceOf(RemoteException.class));
  assertThat(result.getContent().isPresent(), is(false));
  //result.getDataSetErrors().forEach(Throwable::printStackTrace);
}
 
Example #10
Source File: MockServerTestHelper.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
public MockServerTestHelper(ClientType clientType) {
    clientAndServer = ClientAndServer.startClientAndServer(8080);
    mockServerClient = new MockServerClient("127.0.0.1", 8080);
    mockServerClient
            .when(
                    HttpRequest.request()
                            .withMethod("GET")
                            .withPath("/api/hello")
                            .withHeader("client-type", clientType.getValue()),
                    Times.unlimited(),
                    TimeToLive.unlimited())
            .respond(
                    HttpResponse.response()
                            .withBody("Hello")
                            .withStatusCode(200)
            );
}
 
Example #11
Source File: LinkExplorerTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void findLinksInHeader() throws Exception {
  String path = "/foo/bar/page2.html";

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withHeader("Link", "<http://www.example.com/dataset1/capabilitylist.xml>; rel=\"resourcesync\"")
      .withHeader("Link", "</dataset2/capabilitylist.xml>; rel=\"resourcesync\"")
      .withHeader("Content-Type", "text/html; charset=utf-8")
      .withBody(createValidHtml())
    );

  LinkExplorer explorer = new LinkExplorer(getHttpclient(), getRsContext(), LinkExplorer.linkReader);
  ResultIndex index = new ResultIndex();
  Result<LinkList> result = explorer.explore(composeUri(path), index, null);

  result.getErrors().forEach(Throwable::printStackTrace);

  assertThat(result.getErrors().isEmpty(), is(true));
  assertThat(result.getContent().isPresent(), is(true));
  LinkList linkList = result.getContent().orElse(new LinkList());
  Set<URI> validUris = linkList.getValidUris();
  assertThat(validUris, containsInAnyOrder(
    composeUri("dataset2/capabilitylist.xml"),
    URI.create("http://www.example.com/dataset1/capabilitylist.xml")));
  assertThat(linkList.getInvalidUris().size(), equalTo(0));

  assertThat(index.contains(composeUri(path)), is(true));
}
 
Example #12
Source File: LinkExplorerTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void findLinksInRobotsTxt() {
  String path = "/robots.txt";

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withHeader("Content-Type", "text/plain; utf-8")
      .withBody(createRobotsTxt())
    );

  LinkExplorer explorer = new LinkExplorer(getHttpclient(), getRsContext(), LinkExplorer.robotsReader);
  ResultIndex index = new ResultIndex();
  Result<LinkList> result = explorer.explore(composeUri(path), index, null);

  result.getErrors().forEach(Throwable::printStackTrace);

  assertThat(result.getErrors().isEmpty(), is(true));
  assertThat(result.getContent().isPresent(), is(true));
  LinkList linkList = result.getContent().orElse(new LinkList());
  Set<URI> validUris = linkList.getValidUris();
  assertThat(validUris, containsInAnyOrder(
    composeUri("dataset1/resourcelist1.xml"),
    composeUri("/dataset2/resourcelist.xml"),
    composeUri("/some/other/just_a_sitemap.xml")));
  assertThat(linkList.getInvalidUris().size(), equalTo(0));

  assertThat(index.contains(composeUri(path)), is(true));
}
 
Example #13
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addAuthorizationResponseBody(String expectedAuthorizationUrl, String authorizationResponseBody, String authorizationReplayNonce) {
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(expectedAuthorizationUrl),
            Times.exactly(10))
            .respond(
                    response()
                            .withHeader("Retry-After", "0")
                            .withHeader("Cache-Control", "public, max-age=0, no-cache")
                            .withHeader("Content-Type", "application/json")
                            .withHeader("Replay-Nonce", authorizationReplayNonce)
                            .withBody(authorizationResponseBody));
    return this;
}
 
Example #14
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addNewNonceResponse(String newNonce) {
    server.when(
            request()
                    .withMethod("HEAD")
                    .withPath("/acme/new-nonce")
                    .withBody(""),
            Times.once())
            .respond(
                    response()
                            .withHeader("Retry-After", "0")
                            .withHeader("Cache-Control", "public, max-age=0, no-cache")
                            .withHeader("Replay-Nonce", newNonce)
                            .withStatusCode(204));
    return this;
}
 
Example #15
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addDirectoryResponseBody(String directoryResponseBody) {
    server.when(
            request()
                    .withMethod("GET")
                    .withPath("/directory")
                    .withBody(""),
            Times.once())
            .respond(
                    response()
                            .withHeader("Retry-After", "0")
                            .withHeader("Cache-Control", "public, max-age=0, no-cache")
                            .withHeader("Content-Type", "application/json")
                            .withBody(directoryResponseBody));
    return this;
}
 
Example #16
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addPostRequestAndResponse(String expectedPostRequestBody, String postPath, String responseBody, String replayNonce, String link, String location, int responseCode, boolean useProblemContentType) {
    HttpResponse response = response()
            .withHeader("Cache-Control", "public, max-age=0, no-cache")
            .withHeader("Replay-Nonce", replayNonce)
            .withStatusCode(responseCode);
    if (! responseBody.isEmpty()) {
        response = response
                .withHeader("Content-Type", useProblemContentType ? "application/problem+json" : "application/json")
                .withBody(responseBody);

    }
    if (! link.isEmpty()) {
        response = response.withHeader("Link", link);
    }
    if (! location.isEmpty()) {
        response = response.withHeader("Location", location);
    }
    HttpRequest request = request()
            .withMethod("POST")
            .withPath(postPath) ;
    if (! expectedPostRequestBody.isEmpty()) {
        request = request.withBody(expectedPostRequestBody);
    }
    server.when(
            request,
            Times.once())
            .respond(response);

    return this;
}
 
Example #17
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addPostRequestAndResponse(String expectedPostRequestBody, String postPath, String responseBody, String replayNonce, String link, String location, int responseCode, boolean useProblemContentType) {
    HttpResponse response = response()
            .withHeader("Retry-After", "0")
            .withHeader("Cache-Control", "public, max-age=0, no-cache")
            .withHeader("Replay-Nonce", replayNonce)
            .withStatusCode(responseCode);
    if (! responseBody.isEmpty()) {
        response = response
                .withHeader("Content-Type", useProblemContentType ? "application/problem+json" : "application/json")
                .withBody(responseBody);

    }
    if (! link.isEmpty()) {
        response = response.withHeader("Link", link);
    }
    if (! location.isEmpty()) {
        response = response.withHeader("Location", location);
    }
    HttpRequest request = request()
            .withMethod("POST")
            .withPath(postPath) ;
    if (! expectedPostRequestBody.isEmpty()) {
        request = request.withBody(expectedPostRequestBody);
    }
    server.when(
            request,
            Times.once())
            .respond(response);

    return this;
}
 
Example #18
Source File: RsExplorerTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private void verifyFindSourceDescription(String path) {
  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withBody(createValidSourceDescription())
    );

  URI uri = composeUri(path);

  RsExplorer explorer = new RsExplorer(getHttpclient(), getRsContext());
  ResultIndex index = new ResultIndex();
  Result<RsRoot> result = explorer.explore(uri, index, null);

  result.getErrors().forEach(Throwable::printStackTrace);

  assertThat(result.getUri(), equalTo(uri));
  assertThat(result.getStatusCode(), equalTo(200));
  assertThat(result.getErrors().isEmpty(), is(true));
  assertThat(result.getContent().isPresent(), is(true));
  assertThat(result.getContent().map(RsRoot::getMetadata).flatMap(RsMd::getCapability).orElse("invalid"),
    equalTo("description"));

  // index should contain the describedBy uri of the source description:
  assertThat(index.contains(composeUri("/info_about_source.xml")), is(true));
  // result should contain the describedByResult:
  Result<Description> descriptionResult = result.getDescriptionResult().get();
  assertThat(descriptionResult.getUri(), equalTo(composeUri("/info_about_source.xml")));
  assertThat(descriptionResult.getContent().isPresent(), is(false));
  assertThat(descriptionResult.getStatusCode(), equalTo(404));
}
 
Example #19
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addAuthorizationResponseBody(String expectedAuthorizationUrl, String expectedAuthorizationRequestBody, String authorizationResponseBody, String authorizationReplayNonce) {
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(expectedAuthorizationUrl)
                    .withBody(expectedAuthorizationRequestBody == null ? "" : expectedAuthorizationRequestBody),
            Times.exactly(10))
            .respond(
                    response()
                            .withHeader("Cache-Control", "public, max-age=0, no-cache")
                            .withHeader("Content-Type", "application/json")
                            .withHeader("Replay-Nonce", authorizationReplayNonce)
                            .withBody(authorizationResponseBody));
    return this;
}
 
Example #20
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addNewNonceResponse(String newNonce) {
    server.when(
            request()
                    .withMethod("HEAD")
                    .withPath("/acme/new-nonce")
                    .withBody(""),
            Times.once())
            .respond(
                    response()
                            .withHeader("Cache-Control", "public, max-age=0, no-cache")
                            .withHeader("Replay-Nonce", newNonce)
                            .withStatusCode(204));
    return this;
}
 
Example #21
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public AcmeMockServerBuilder addDirectoryResponseBody(String directoryResponseBody) {
    server.when(
            request()
                    .withMethod("GET")
                    .withPath("/directory")
                    .withBody(""),
            Times.once())
            .respond(
                    response()
                            .withHeader("Cache-Control", "public, max-age=0, no-cache")
                            .withHeader("Content-Type", "application/json")
                            .withBody(directoryResponseBody));
    return this;
}
 
Example #22
Source File: LowLatencyMontageClientTest.java    From render with GNU General Public License v2.0 5 votes vote down vote up
private void addAcqTileStateResponse() {
    mockServer
            .when(
                    HttpRequest.request()
                            .withMethod("PUT")
                            .withPath(getBaseAcquisitionPath() + "/tile-state"),
                    Times.once()
            )
            .respond(
                    HttpResponse.response()
                    .withStatusCode(HttpStatus.SC_OK)
    );

}
 
Example #23
Source File: LowLatencyMontageClientTest.java    From render with GNU General Public License v2.0 5 votes vote down vote up
private void addRenderResolvedTilesResponse() {
    final String requestPath = getRenderStackRequestPath() + "/resolvedTiles";
    mockServer
            .when(
                    HttpRequest.request()
                            .withMethod("PUT")
                            .withPath(requestPath),
                    Times.once()
            )
            .respond(
                    HttpResponse.response()
                            .withStatusCode(HttpStatus.SC_CREATED)
    );

}
 
Example #24
Source File: TestLease.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenew() throws Exception {
  VaultConfiguration conf = VaultConfigurationBuilder.newVaultConfiguration()
      .withAddress(address)
      .withToken(token)
      .build();

  String leaseId = "aws/creds/s3ReadOnly/895aad27-028e-301b-5475-906a6561f8f8";

  new MockServerClient(localhost, mockServerRule.getPort())
      .when(
      HttpRequest.request()
          .withMethod("PUT")
          .withHeader(tokenHeader)
          .withPath("/v1/sys/renew/" + leaseId),
      Times.exactly(1)
  )
  .respond(
      HttpResponse.response()
          .withStatusCode(HttpStatusCode.OK_200.code())
          .withHeader(contentJson)
          .withBody(getBody("sys_lease_renew.json"))
  );

  VaultClient vault = new VaultClient(conf);
  Secret secret = vault.sys().lease().renew(leaseId);
  Assert.assertEquals(leaseId, secret.getLeaseId());
  Assert.assertEquals(60, secret.getLeaseDuration());
  Assert.assertEquals(true, secret.isRenewable());
}
 
Example #25
Source File: RsExplorerTest.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void findWrongParentDocument() throws Exception {
  String path1 = "/foo/resourcedump.xml";
  String path2 = "/bla/resourcedump.xml";

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path1),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withBody(createValidResourceDump(path2))
    );

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path2),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withBody(createValidResourceDump("/bar/whatever.xml"))
    );

  URI uri = composeUri(path1);

  RsExplorer explorer = new RsExplorer(getHttpclient(), getRsContext());
  ResultIndex index = new ResultIndex();
  Result<RsRoot> result = explorer.explore(uri, index, null);

  //result.listErrors().forEach(Throwable::printStackTrace);

  assertThat(result.getUri(), equalTo(uri));
  assertThat(result.getStatusCode(), equalTo(200));
  assertThat(result.getErrors().isEmpty(), is(false));
  assertThat(result.getErrors().get(0).getMessage(), containsString("invalid up relation:"));
  assertThat(result.getContent().isPresent(), is(true));
  assertThat(result.getContent().map(RsRoot::getMetadata).flatMap(RsMd::getCapability).orElse("invalid"),
    equalTo("resourcedump"));

  URI uri2 = composeUri(path2);
  Result<RsRoot> parentResult = (Result<RsRoot>) result.getParents().get(uri2);

  parentResult.getErrors().forEach(Throwable::printStackTrace);

  assertThat(parentResult.getUri(), equalTo(uri2));
  assertThat(parentResult.getStatusCode(), equalTo(200));
  assertThat(parentResult.getErrors().isEmpty(), is(true));
  assertThat(parentResult.getContent().isPresent(), is(true));
  assertThat(parentResult.getContent().map(RsRoot::getMetadata).flatMap(RsMd::getCapability).orElse("invalid"),
    equalTo("resourcedump"));
}
 
Example #26
Source File: RsExplorerTest.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Test
@SuppressWarnings({"unchecked"})
public void findDescribedByDocuments() throws Exception {
  String path = "/.well-known/resourcesync";
  String pathDescriptionOfSource = "/info_about_source.xml";
  String pathDescriptionOfSet1 = "/info_about_set1_of_resources.xml";
  String pathDescriptionOfSet2 = "/info_about_set2_of_resources.xml";
  String pathDescriptionOfSet3 = "/info_about_set3_of_resources.xml";

  getMockServer()
    .when(HttpRequest.request()
                     .withMethod("GET")
                     .withPath(path),
      Times.exactly(1))
    .respond(HttpResponse.response()
                         .withStatusCode(200)
                         .withBody(createValidSourceDescription())
    );

  getMockServer()
    .when(HttpRequest.request()
                     .withMethod("GET")
                     .withPath(pathDescriptionOfSet1),
      Times.exactly(1))
    .respond(HttpResponse.response()
                         .withStatusCode(200)
                         .withBody(createDescriptionDocument())
    );

  getMockServer()
    .when(HttpRequest.request()
                     .withMethod("GET")
                     .withPath(pathDescriptionOfSet2),
      Times.exactly(1))
    .respond(HttpResponse.response()
                         .withStatusCode(404)
                         .withBody("Not Found")
    );

  getMockServer()
    .when(HttpRequest.request()
                     .withMethod("GET")
                     .withPath(pathDescriptionOfSet3),
      Times.exactly(1))
    .respond(HttpResponse.response()
                         .withStatusCode(200)
                         .withBody(createDescriptionDocument())
    );

  getMockServer()
    .when(HttpRequest.request()
                     .withMethod("GET")
                     .withPath(pathDescriptionOfSource),
      Times.exactly(1))
    .respond(HttpResponse.response()
                         .withStatusCode(200)
                         .withBody(createDescriptionDocument())
    );

  RsExplorer explorer = new RsExplorer(getHttpclient(), getRsContext());
  ResultIndex index = new ResultIndex();
  Result<RsRoot> result = explorer.explore(composeUri(path), index, null);

  assertThat(result.getStatusCode(), equalTo(200));
  assertThat(result.getDescriptionResult().isPresent(), is(true));
  Result<Description> describedByResult = result.getDescriptionResult().get();
  assertThat(describedByResult.getContent().isPresent(), is(true));
  assertThat(describedByResult.getContent().get().getRawContent(), equalTo(createDescriptionDocument()));

  Result<RsRoot> child1 = (Result<RsRoot>)
    result.getChildren().get(URI.create("http://example.com/capabilitylist1.xml"));
  assertThat(child1.getContent().isPresent(), is(false));
  assertThat(child1.getDescriptionResult().isPresent(), is(true));
  Result<Description> descriptionResult1 = child1.getDescriptionResult().get();
  descriptionResult1.getErrors().forEach(Throwable::printStackTrace);
  assertThat(descriptionResult1.getContent().isPresent(), is(true));
  assertThat(descriptionResult1.getContent().get().getRawContent(), equalTo(createDescriptionDocument()));

  Result<RsRoot> child3 = (Result<RsRoot>)
    result.getChildren().get(URI.create("http://example.com/capabilitylist3.xml"));
  assertThat(child3.getContent().isPresent(), is(false));
  assertThat(child3.getDescriptionResult().isPresent(), is(true));
  Result<Description> descriptionResult3 = child3.getDescriptionResult().get();
  descriptionResult3.getErrors().forEach(Throwable::printStackTrace);
  assertThat(descriptionResult3.getContent().isPresent(), is(true));
  assertThat(descriptionResult3.getContent().get().getRawContent(), equalTo(createDescriptionDocument()));

  Result<RsRoot> child2 = (Result<RsRoot>)
    result.getChildren().get(URI.create("http://example.com/capabilitylist2.xml"));
  assertThat(child2.getContent().isPresent(), is(false));
  assertThat(child2.getDescriptionResult().isPresent(), is(true));
  Result<Description> descriptionResult2 = child2.getDescriptionResult().get();
  assertThat(descriptionResult2.getContent().isPresent(), is(false));
  assertThat(descriptionResult2.getStatusCode(), is(404));
}
 
Example #27
Source File: ExpeditionTest.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
private void setUpServer(String path) {
  getMockServer().reset();

  //description
  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath("/.well-known/resourcesync"),
      Times.unlimited())

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withBody(createDescription(path))
    );

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath("/robots.txt"),
      Times.unlimited())

    .respond(HttpResponse.response()
      .withStatusCode(404)
      .withBody("No robots here.")
    );

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path),
      Times.unlimited()) // 2 x

    .respond(HttpResponse.response()
      .withStatusCode(404)
      .withBody("No foo.")
    );

  // capabilitylists
  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path + "/capabilitylist1.xml"),
      Times.unlimited())

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withBody(createCapabilityList(path))
    );

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path + "/capabilitylist2.xml"),
      Times.unlimited())

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withBody(createCapabilityList("/foo"))
    );
}
 
Example #28
Source File: LinkExplorerTest.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void findLinksInDocumentAndFindChildren() throws Exception {
  String path = "/foo/bar/page1.html";
  String capabilityListPath = "/foo/bar/dataset1/capabilitylist.xml";

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(path),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withHeader("Content-Type", "text/html; utf-8")
      .withBody(createValidHtmlWithLinks())
    );

  getMockServer()
    .when(HttpRequest.request()
        .withMethod("GET")
        .withPath(capabilityListPath),
      Times.exactly(1))

    .respond(HttpResponse.response()
      .withStatusCode(200)
      .withHeader("Content-Type", "text/xml; utf-8")
      .withBody(createCapabilityList())
    );

  LinkExplorer explorer = new LinkExplorer(getHttpclient(), getRsContext(), LinkExplorer.linkReader);
  URI uri = composeUri(path);
  ResultIndex index = new ResultIndex();
  Result<LinkList> result = explorer.explore(uri, index, null);

  result.getErrors().forEach(Throwable::printStackTrace);

  assertThat(result.getErrors().isEmpty(), is(true));
  assertThat(result.getContent().isPresent(), is(true));
  LinkList linkList = result.getContent().orElse(new LinkList());
  Set<URI> validUris = linkList.getValidUris();
  assertThat(validUris, containsInAnyOrder(
    composeUri(capabilityListPath),
    URI.create("http://www.example.com/dataset2/capabilitylist.xml")));
  assertThat(linkList.getInvalidUris().size(), equalTo(0));

  assertThat(index.contains(uri), is(true));
  assertThat(result.getChildren().keySet(), containsInAnyOrder(
    composeUri("/foo/bar/dataset1/capabilitylist.xml"),
    URI.create("http://www.example.com/dataset2/capabilitylist.xml")));

  Result<?> child1 = result.getChildren().get(composeUri(capabilityListPath));
  assertThat(child1.getParents().containsKey(result.getUri()), is(true));

  Result<?> child2 = result.getChildren().get(URI.create("http://www.example.com/dataset2/capabilitylist.xml"));
  assertThat(child2.getParents().containsKey(result.getUri()), is(true));

  assertThat(child1.getErrors().isEmpty(), is(true));
  assertThat(child2.getErrors().isEmpty(), is(false));
  //child2.listErrors().forEach(Throwable::printStackTrace); // RemoteException: 404 Not Found

  assertThat(child1.getContent().isPresent(), is(true));
  assertThat(child1.getContent().orElse(null), instanceOf(Urlset.class));
  assertThat(child1.getChildren().size(), equalTo(4));
  // LinkList --> capabilitylist --> resourcelist
  // assertThat result-with-resourcelist (404 btw) has parent result-with-capabilitylist.
  assertThat(child1.getChildren().get(
    URI.create("http://example.com/dataset1/resourcelist.xml"))
    .getParents().containsKey(child1.getUri()), is(true));
}
 
Example #29
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public AcmeMockServerBuilder addChallengeRequestAndResponse(String expectedChallengeRequestBody, String expectedChallengeUrl, String challengeResponseBody,
                                                            String challengeReplayNonce, String challengeLocation, String challengeLink,
                                                            int challengeStatusCode, boolean useProblemContentType, String verifyChallengePath,
                                                            String challengeFileContents, String expectedAuthorizationUrl, String authorizationResponseBody,
                                                            String authorizationReplayNonce) {
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(expectedChallengeUrl)
                    .withHeader("Content-Type", "application/jose+json"),
            Times.once())
            .respond(request -> {
                HttpResponse response = response()
                        .withHeader("Retry-After", "0")
                        .withHeader("Cache-Control", "public, max-age=0, no-cache")
                        .withHeader("Content-Type", useProblemContentType ? "application/problem+json" : "application/json")
                        .withHeader("Replay-Nonce", challengeReplayNonce)
                        .withBody(challengeResponseBody)
                        .withStatusCode(challengeStatusCode);
                if (! challengeLocation.isEmpty()) {
                    response = response.withHeader("Location", challengeLocation);
                }
                if (! challengeLink.isEmpty()) {
                    response = response.withHeader("Link", challengeLink);
                }

                byte[] challengeResponseBytes = null;
                try {
                    // Simply validate that the file was created and has the correct contents (attempting to retrieve
                    // the file via the challenge url would require the Undertow subsystem)
                    String jbossHome = TestSuiteEnvironment.getSystemProperty("jboss.inst");
                    if (jbossHome == null) {
                        jbossHome = TestSuiteEnvironment.getJBossHome();
                    }
                    Assert.assertNotNull("Could not find the JBoss home directory", jbossHome);

                    String challengeDir = jbossHome +  verifyChallengePath;
                    try (InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(challengeDir)))) {
                        challengeResponseBytes = IOUtils.toByteArray(inputStream);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                if (challengeFileContents.equals(new String(challengeResponseBytes, StandardCharsets.UTF_8))) {
                    addAuthorizationResponseBody(expectedAuthorizationUrl, authorizationResponseBody, authorizationReplayNonce);
                }
                return response;
            });
    return this;
}
 
Example #30
Source File: AcmeMockServerBuilder.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public AcmeMockServerBuilder addChallengeRequestAndResponse(String expectedChallengeRequestBody, String expectedChallengeUrl, String challengeResponseBody,
                                                            String challengeReplayNonce, String challengeLocation, String challengeLink,
                                                            int challengeStatusCode, boolean useProblemContentType, String verifyChallengePath,
                                                            String challengeFileContents, String expectedAuthorizationUrl, String authorizationResponseBody,
                                                            String authorizationReplayNonce) {
    server.when(
            request()
                    .withMethod("POST")
                    .withPath(expectedChallengeUrl)
                    .withHeader("Content-Type", "application/jose+json")
                    .withBody(expectedChallengeRequestBody),
            Times.once())
            .respond(request -> {
                HttpResponse response = response()
                        .withHeader("Cache-Control", "public, max-age=0, no-cache")
                        .withHeader("Content-Type", useProblemContentType ? "application/problem+json" : "application/json")
                        .withHeader("Replay-Nonce", challengeReplayNonce)
                        .withBody(challengeResponseBody)
                        .withStatusCode(challengeStatusCode);
                if (! challengeLocation.isEmpty()) {
                    response = response.withHeader("Location", challengeLocation);
                }
                if (! challengeLink.isEmpty()) {
                    response = response.withHeader("Link", challengeLink);
                }

                byte[] challengeResponseBytes = null;
                try {
                    // Simply validate that the file was created and has the correct contents (attempting to retrieve
                    // the file via the challenge url would require the Undertow subsystem)
                    try (InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(System.getProperty("jboss.home.dir") + verifyChallengePath)))) {
                        challengeResponseBytes = IOUtils.toByteArray(inputStream);
                    }
                } catch (Exception e) {
                    //
                }
                if (challengeFileContents.equals(new String(challengeResponseBytes, StandardCharsets.UTF_8))) {
                    addAuthorizationResponseBody(expectedAuthorizationUrl, null, authorizationResponseBody, authorizationReplayNonce);
                }
                return response;
            });
    return this;
}