@Test
  public void testCustomerResource() throws Exception {
    System.out.println("*** Create a new Customer ***");
    Customer newCustomer = new Customer();
    newCustomer.setFirstName("Bill");
    newCustomer.setLastName("Burke");
    newCustomer.setStreet("256 Clarendon Street");
    newCustomer.setCity("Boston");
    newCustomer.setState("MA");
    newCustomer.setZip("02115");
    newCustomer.setCountry("USA");

    Response response =
        client
            .target("http://localhost:8080/services/customers")
            .request()
            .post(Entity.xml(newCustomer));
    if (response.getStatus() != 201) throw new RuntimeException("Failed to create");
    String location = response.getLocation().toString();
    System.out.println("Location: " + location);
    response.close();

    System.out.println("*** GET XML Created Customer **");
    String xml =
        client.target(location).request().accept(MediaType.APPLICATION_XML_TYPE).get(String.class);
    System.out.println(xml);

    System.out.println("*** GET JSON Created Customer **");
    String json =
        client.target(location).request().accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
    System.out.println(json);
  }
Example #2
0
 @Test
 public void sayHello() {
   Entity<Hello> helloEntity = Entity.entity(new Hello("Bob"), MediaType.APPLICATION_JSON_TYPE);
   Response response = target("/hello").request().post(helloEntity);
   assertEquals(201, response.getStatus());
   assertEquals("http://localhost:9998/hello/Bob", response.getLocation().toString());
 }
  // KEYCLOAK-2102
  @Test
  public void spnegoCaseInsensitiveTest() throws Exception {
    KeycloakRule keycloakRule = getKeycloakRule();
    AssertEvents events = getAssertEvents();

    Response spnegoResponse = spnegoLogin("MyDuke", "theduke");
    Assert.assertEquals(302, spnegoResponse.getStatus());

    events
        .expectLogin()
        .client("kerberos-app")
        .user(keycloakRule.getUser("test", "myduke").getId())
        .detail(Details.REDIRECT_URI, KERBEROS_APP_URL)
        // .detail(Details.AUTH_METHOD, "spnego")
        .detail(Details.USERNAME, "myduke")
        .assertEvent();

    String location = spnegoResponse.getLocation().toString();
    driver.navigate().to(location);

    String pageSource = driver.getPageSource();
    Assert.assertTrue(
        pageSource.contains("Kerberos Test")
            && pageSource.contains("Kerberos servlet secured content"));

    spnegoResponse.close();
    events.clear();
  }
  /**
   * Creates a new data set.
   *
   * @param providerId provider identifier (required)
   * @param dataSetId data set identifier (required)
   * @param description data set description (not required)
   * @return URI to created data set
   * @throws DataSetAlreadyExistsException when data set with given id (for given provider) already
   *     exists
   * @throws ProviderNotExistsException when provider with given id does not exist
   * @throws MCSException on unexpected situations
   */
  public URI createDataSet(String providerId, String dataSetId, String description)
      throws ProviderNotExistsException, DataSetAlreadyExistsException, MCSException {

    WebTarget target =
        client
            .target(this.baseUrl)
            .path(dataSetsPath)
            .resolveTemplate(ParamConstants.P_PROVIDER, providerId);

    Form form = new Form();
    form.param(ParamConstants.F_DATASET, dataSetId);
    form.param(ParamConstants.F_DESCRIPTION, description);

    Response response =
        target.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));

    if (response.getStatus() == Status.CREATED.getStatusCode()) {
      return response.getLocation();
    }

    // TODO this does not function correctly,
    // details are filled with "MessageBodyReader not found for media type=text/html;
    // charset=utf-8, type=class eu.europeana.cloud.common.response.ErrorInfo,
    // genericType=class eu.europeana.cloud.common.response.ErrorInfo."
    // simple strings like 'adsfd' get entitised correctly
    ErrorInfo errorInfo = response.readEntity(ErrorInfo.class);
    throw MCSExceptionProvider.generateException(errorInfo);
  }
  protected void testGetSpec(String acceptMimeType) throws Exception {
    String appName = "ent-with-spec";

    // Create an app with a yaml spec
    String yaml =
        Joiner.on("\n")
            .join("name: " + appName, "services:", "- type: " + BasicEntity.class.getName());
    Response appResponse =
        client().path("/applications").header("Content-Type", "text/x-yaml").post(yaml);
    waitForApplicationToBeRunning(appResponse.getLocation());

    // Retrieve the yaml spec, and confirm it is as expected (not wrapped in quotes, and treating \n
    // sensibly)
    Response response;
    if (acceptMimeType != null) {
      response =
          client()
              .path("/applications/" + appName + "/entities/" + appName + "/spec")
              .accept(acceptMimeType)
              .get();
    } else {
      response = client().path("/applications/" + appName + "/entities/" + appName + "/spec").get();
    }
    String data = response.readEntity(String.class);

    assertEquals(data.trim(), yaml.trim());
  }
Example #6
0
 public static String getCreatedId(Response response) {
   URI location = response.getLocation();
   if (location == null) {
     return null;
   }
   String path = location.getPath();
   return path.substring(path.lastIndexOf('/') + 1);
 }
 protected Response spnegoLogin(String username, String password) {
   SpnegoAuthenticator.bypassChallengeJavascript = true;
   driver.navigate().to(KERBEROS_APP_URL);
   String kcLoginPageLocation = driver.getCurrentUrl();
   String location =
       "http://localhost:8081/auth/realms/test/protocol/openid-connect/auth?response_type=code&client_id=kerberos-app&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Fkerberos-portal&state=0%2F88a96ddd-84fe-4e77-8a46-02394d7b3a7d&login=true";
   // Request for SPNEGO login sent with Resteasy client
   spnegoSchemeFactory.setCredentials(username, password);
   Response response = client.target(kcLoginPageLocation).request().get();
   SpnegoAuthenticator.bypassChallengeJavascript = false;
   if (response.getStatus() == 302) {
     if (response.getLocation() == null) return response;
     String uri = response.getLocation().toString();
     if (uri.contains("login-actions/required-action")) {
       response = client.target(uri).request().get();
     }
   }
   return response;
 }
  @Test
  public void shouldCreateRecord() throws Exception {

    RecordPayload recordPayload = RecordPayload.instanceOf(7);

    when(mockService.create(argThat(isRecord(null, 7)))).thenReturn(TEST_ID);
    when(mockUriInfo.getAbsolutePathBuilder())
        .thenReturn(UriBuilder.fromPath("http://localhost:8080/services/webapi/myresource"));

    Response response = recordResource.createRecord(recordPayload);

    assertThat(
        response.getLocation().toString(),
        is("http://localhost:8080/services/webapi/myresource/a02"));
    assertThat(response.getStatus(), is(HttpStatus.CREATED.value()));
  }
Example #9
0
  public void startTransaction() {
    if (transactionPath != null) {
      throw new RuntimeException("Fedora transaction already active, can't start new one.");
    }

    Response response =
        ClientBuilder.newClient().target(FEDORA_ENDPOINT + "fcr:tx").request().post(null);
    if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
      throw new RuntimeException("Fedora responded with error when starting transaction.");
    }

    URI txLocation = response.getLocation();
    if (txLocation == null) {
      throw new RuntimeException("There was no transaction info in fedora's response.");
    }
    toUpdate.clear();
    toDelete.clear();
    transactionPath = txLocation.toString();
  }
  @BeforeClass(alwaysRun = true)
  public void setUp() throws Exception {
    // Deploy application
    startServer();
    Response deploy = clientDeploy(simpleSpec);
    waitForApplicationToBeRunning(deploy.getLocation());

    // Add tag
    entity =
        (EntityInternal)
            Iterables.find(
                getManagementContext().getEntityManager().getEntities(),
                new Predicate<Entity>() {
                  @Override
                  public boolean apply(@Nullable Entity input) {
                    return "RestMockSimpleEntity".equals(input.getEntityType().getSimpleName());
                  }
                });
  }
  @Test
  public void testPostGetDeleteMessage() {

    // test POST [app/messages]
    Response response =
        webTarget
            .request()
            .post(Entity.entity("Hello World !!!", MediaType.TEXT_PLAIN), Response.class);
    assertEquals(Status.CREATED.getStatusCode(), response.getStatus());

    // test GET [app/messages/{number}]
    URI location = response.getLocation();
    String resourceNum = location.getPath().substring(location.getPath().lastIndexOf("/") + 1);
    Message message =
        webTarget.path(resourceNum).request(MediaType.APPLICATION_XML).get(Message.class);
    assertEquals("Hello World !!!", message.getMessage());

    // test DELETE [app/messages/{number}]
    response = webTarget.path(resourceNum).request().delete();
    assertNotSame(Status.NOT_FOUND.getStatusCode(), response.getStatus());
  }
Example #12
0
  public static String dumpResponse(Response r, boolean detailed, String fieldDelim) {
    String s = "[Response obiect] ";
    s += "status=" + r.getStatus();
    s += fieldDelim + "statusInfo=" + r.getStatusInfo();
    s += fieldDelim + "location=" + r.getLocation();

    if (!detailed) return s;

    MultivaluedMap<String, String> headersStrings = r.getStringHeaders();
    Iterator<String> it = headersStrings.keySet().iterator();
    s += "\n---- headers ---";
    while (it.hasNext()) {
      String theKey = it.next();
      s += "\n" + theKey + ":";
      List<String> valuesList = headersStrings.get(theKey);
      for (String value : valuesList) {
        s += value + ",";
      }
    }

    return s;
  }
  @Test
  public void usernamePasswordLoginTest() throws Exception {
    KeycloakRule keycloakRule = getKeycloakRule();
    AssertEvents events = getAssertEvents();

    // Change editMode to READ_ONLY
    updateProviderEditMode(UserFederationProvider.EditMode.READ_ONLY);

    // Login with username/password from kerberos
    changePasswordPage.open();
    // Only needed if you are providing a click thru to bypass kerberos.  Currently there is a
    // javascript
    // to forward the user if kerberos isn't enabled.
    // bypassPage.isCurrent();
    // bypassPage.clickContinue();
    loginPage.assertCurrent();
    loginPage.login("jduke", "theduke");
    changePasswordPage.assertCurrent();

    // Change password is not possible as editMode is READ_ONLY
    changePasswordPage.changePassword("theduke", "newPass", "newPass");
    Assert.assertTrue(
        driver
            .getPageSource()
            .contains("You can't update your password as your account is read only"));

    // Change editMode to UNSYNCED
    updateProviderEditMode(UserFederationProvider.EditMode.UNSYNCED);

    // Successfully change password now
    changePasswordPage.changePassword("theduke", "newPass", "newPass");
    Assert.assertTrue(driver.getPageSource().contains("Your password has been updated."));
    changePasswordPage.logout();

    // Only needed if you are providing a click thru to bypass kerberos.  Currently there is a
    // javascript
    // to forward the user if kerberos isn't enabled.
    // bypassPage.isCurrent();
    // bypassPage.clickContinue();
    // Login with old password doesn't work, but with new password works
    loginPage.login("jduke", "theduke");
    loginPage.assertCurrent();
    loginPage.login("jduke", "newPass");
    changePasswordPage.assertCurrent();
    changePasswordPage.logout();

    // Assert SPNEGO login still with the old password as mode is unsynced
    events.clear();
    Response spnegoResponse = spnegoLogin("jduke", "theduke");
    Assert.assertEquals(302, spnegoResponse.getStatus());
    String redirect = spnegoResponse.getLocation().toString();
    events
        .expectLogin()
        .client("kerberos-app")
        .user(keycloakRule.getUser("test", "jduke").getId())
        .detail(Details.REDIRECT_URI, KERBEROS_APP_URL)
        // .detail(Details.AUTH_METHOD, "spnego")
        .detail(Details.USERNAME, "jduke")
        .assertEvent();
    spnegoResponse.close();
  }
Example #14
0
  @Test
  public void testScoped() throws Exception {
    System.out.println(realmInfo.getAuthorizationUrl());
    WebTarget authUrl =
        client
            .target(realmInfo.getAuthorizationUrl())
            .queryParam("client_id", "oauthclient")
            .queryParam("redirect_uri", "http://localhost:8081/oauthclient/redirect");

    String form = authUrl.request().get(String.class);
    System.out.println(form);

    Pattern p = Pattern.compile("action=\"([^\"]+)\"");
    Matcher matcher = p.matcher(form);
    String loginUrl = null;
    if (matcher.find()) {
      loginUrl = matcher.group(1);
    }
    Assert.assertNotNull(loginUrl);

    Pattern sp = Pattern.compile("name=\"scope\" value=\"([^\"]+)\"");
    matcher = sp.matcher(form);
    String scopeParam = null;
    if (matcher.find()) {
      scopeParam = matcher.group(1);
    }
    Assert.assertNotNull(scopeParam);

    Form loginform =
        new Form()
            .param("username", "wburke")
            .param("Password", "userpassword")
            .param("client_id", "oauthclient")
            .param("scope", scopeParam)
            .param("redirect_uri", "http://localhost:8081/loginclient/redirect");

    System.out.println("LoginUrl: " + loginUrl);
    Response response = client.target(loginUrl).request().post(Entity.form(loginform));
    Assert.assertEquals(302, response.getStatus());
    URI uri = response.getLocation();
    response.close();
    Assert.assertNotNull(uri);
    System.out.println(uri);
    Pattern q = Pattern.compile("code=([^&]+)");
    matcher = q.matcher(uri.getRawQuery());
    String code = null;
    if (matcher.find()) {
      code = matcher.group(1);
    }
    System.out.println("Code: " + code);
    Assert.assertNotNull(code);
    WebTarget codes = client.target(realmInfo.getCodeUrl());
    Form codeForm =
        new Form()
            .param("code", code)
            .param("client_id", "oauthclient")
            .param("Password", "clientpassword");
    Response res = codes.request().post(Entity.form(codeForm));
    if (res.getStatus() == 400) {
      System.out.println(res.readEntity(String.class));
    }
    Assert.assertEquals(200, res.getStatus());
    AccessTokenResponse tokenResponse = res.readEntity(AccessTokenResponse.class);
    res.close();

    ResourceMetadata metadata = new ResourceMetadata();
    metadata.setRealm("test-realm");
    metadata.setResourceName("Application");
    metadata.setRealmKey(realmInfo.getPublicKey());
    SkeletonKeyToken token = RSATokenVerifier.verifyToken(tokenResponse.getToken(), metadata);
    Assert.assertEquals(token.getPrincipal(), "wburke");
    Assert.assertTrue(token.getResourceAccess("Application").getRoles().contains("user"));
  }
Example #15
0
  @Test
  public void testCreateCancelPurge() throws Exception {
    String base = "http://localhost:8080/services/shop";
    Response response = client.target(base).request().head();

    Link customers = response.getLink("customers");
    Link orders = response.getLink("orders");
    response.close();

    System.out.println("** Create a customer through this URL: " + customers.getUri().toString());

    Customer customer = new Customer();
    customer.setFirstName("Bill");
    customer.setLastName("Burke");
    customer.setStreet("10 Somewhere Street");
    customer.setCity("Westford");
    customer.setState("MA");
    customer.setZip("01711");
    customer.setCountry("USA");

    response = client.target(customers).request().post(Entity.xml(customer));
    Assert.assertEquals(201, response.getStatus());
    response.close();

    Order order = new Order();
    order.setTotal("$199.99");
    order.setCustomer(customer);
    order.setDate(new Date().toString());
    LineItem item = new LineItem();
    item.setCost("$199.99");
    item.setProduct("iPhone");
    order.setLineItems(new ArrayList<LineItem>());
    order.getLineItems().add(item);

    System.out.println();
    System.out.println("** Create an order through this URL: " + orders.getUri().toString());
    response = client.target(orders).request().post(Entity.xml(order));
    Assert.assertEquals(201, response.getStatus());
    URI createdOrderUrl = response.getLocation();
    response.close();

    System.out.println();
    System.out.println("** New list of orders");
    response = client.target(orders).request().get();
    String orderList = response.readEntity(String.class);
    System.out.println(orderList);
    Link purge = response.getLink("purge");
    response.close();

    response = client.target(createdOrderUrl).request().head();
    Link cancel = response.getLink("cancel");
    response.close();
    if (cancel != null) {
      System.out.println("** Canceling the order at URL: " + cancel.getUri().toString());
      response = client.target(cancel).request().post(null);
      Assert.assertEquals(204, response.getStatus());
      response.close();
    }

    System.out.println();
    System.out.println("** New list of orders after cancel: ");
    orderList = client.target(orders).request().get(String.class);
    System.out.println(orderList);

    System.out.println();
    System.out.println("** Purge cancelled orders at URL: " + purge.getUri().toString());
    response = client.target(purge).request().post(null);
    Assert.assertEquals(204, response.getStatus());
    response.close();

    System.out.println();
    System.out.println("** New list of orders after purge: ");
    orderList = client.target(orders).request().get(String.class);
    System.out.println(orderList);
  }