Exemple #1
0
  private void initializeUserAccount(RestOperations client) {

    if (this.user == null) {

      UaaUser user = testAccounts.getUser();
      @SuppressWarnings("rawtypes")
      ResponseEntity<Map> results =
          client.getForEntity(
              serverRunning.getUserUri() + "?filter=userName eq '" + user.getUsername() + "'",
              Map.class);
      assertEquals(HttpStatus.OK, results.getStatusCode());
      @SuppressWarnings("unchecked")
      List<Map<String, ?>> resources = (List<Map<String, ?>>) results.getBody().get("resources");
      Map<String, ?> map;
      if (!resources.isEmpty()) {
        map = resources.get(0);
      } else {
        map = getUserAsMap(user);
        @SuppressWarnings("rawtypes")
        ResponseEntity<Map> response =
            client.postForEntity(serverRunning.getUserUri(), map, Map.class);
        Assert.state(
            response.getStatusCode() == HttpStatus.CREATED,
            "User account not created: status was " + response.getStatusCode());
        @SuppressWarnings("unchecked")
        Map<String, ?> value = response.getBody();
        map = value;
      }
      this.user = getUserFromMap(map);
    }
  }
  @Test
  @OAuth2ContextConfiguration(
      resource = OAuth2ContextConfiguration.Implicit.class,
      initialize = false)
  public void testUserMustSupplyOldPassword() throws Exception {

    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    parameters.set("source", "credentials");
    parameters.set("username", joe.getUserName());
    parameters.set("password", "pas5Word");
    context.getAccessTokenRequest().putAll(parameters);

    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("Newpasswo3d");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result =
        client.exchange(
            serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT,
            new HttpEntity<>(change, headers),
            Void.class,
            joe.getId());
    assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode());
  }
 @Override
 public void deleteApprovalsForClient(String clientId) {
   ResponseEntity<String> response =
       restTemplate.exchange(
           approvalsUrl + "?clientId=" + clientId, HttpMethod.DELETE, null, String.class);
   logger.debug("Delete approvals request for client " + clientId + " resulted in " + response);
 }
 public void restSend(String url) {
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.TEXT_PLAIN);
   HttpEntity<String> entity = new HttpEntity<String>("", headers);
   ResponseEntity<String> response =
       restTemplate.exchange(url, HttpMethod.GET, entity, String.class, "");
   System.out.println("Response:" + response.getBody());
 }
Exemple #5
0
  private ScimUser createUnapprovedUser() throws Exception {
    String userName = "******" + new RandomValueStringGenerator().generate();
    String userEmail = userName + "@example.com";

    RestOperations restTemplate = serverRunning.getRestTemplate();

    ScimUser user = new ScimUser();
    user.setUserName(userName);
    user.setPassword("s3Cretsecret");
    user.addEmail(userEmail);
    user.setActive(true);
    user.setVerified(true);

    ResponseEntity<ScimUser> result =
        restTemplate.postForEntity(serverRunning.getUrl("/Users"), user, ScimUser.class);
    assertEquals(HttpStatus.CREATED, result.getStatusCode());

    return user;
  }
 private ResponseEntity<ScimUser> createUser(
     String username, String firstName, String lastName, String email) {
   ScimUser user = new ScimUser();
   user.setUserName(username);
   user.setName(new ScimUser.Name(firstName, lastName));
   user.addEmail(email);
   user.setPassword("pas5Word");
   user.setVerified(true);
   return client.postForEntity(serverRunning.getUrl(userEndpoint), user, ScimUser.class);
 }
  @Test
  public void accessServiceUsingRestTemplate() {

    // Access root resource

    URI uri = URI.create(String.format(SERVICE_URI, port));
    RequestEntity<Void> request = RequestEntity.get(uri).accept(HAL_JSON).build();
    Resource<Object> rootLinks =
        restOperations.exchange(request, new ResourceType<Object>() {}).getBody();
    Links links = new Links(rootLinks.getLinks());

    // Follow stores link

    Link storesLink = links.getLink("stores").expand();
    request = RequestEntity.get(URI.create(storesLink.getHref())).accept(HAL_JSON).build();
    Resources<Store> stores =
        restOperations.exchange(request, new ResourcesType<Store>() {}).getBody();

    stores.getContent().forEach(store -> log.info("{} - {}", store.name, store.address));
  }
Exemple #8
0
 public ResponseEntity<String> postForString(
     String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
   if (headers.getContentType() == null) {
     headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
   }
   return client.exchange(
       getUrl(path),
       HttpMethod.POST,
       new HttpEntity<MultiValueMap<String, String>>(formData, headers),
       String.class);
 }
 public void save(String id, Object document) {
   Assert.notNull(document, "document must not be null for save");
   HttpEntity<?> httpEntity = createHttpEntity(document);
   try {
     ResponseEntity<Map> response =
         restOperations.exchange(defaultDocumentUrl, HttpMethod.PUT, httpEntity, Map.class, id);
     // TODO update the document revision id on the object from the returned value
     // TODO better exception translation
   } catch (RestClientException e) {
     throw new UncategorizedCouchDataAccessException(e);
   }
 }
  @Test
  public void instanceJobs_emptyResponse_returnsEmptyMap() {
    when(rest.exchange(
            Matchers.any(URI.class),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(new ResponseEntity<String>("", HttpStatus.OK));

    Map<JenkinsJob, Set<Build>> jobs = defaultJenkinsClient.getInstanceJobs(URL);

    assertThat(jobs.size(), is(0));
  }
  @Override
  public Map<String, List<DescribedApproval>> getCurrentApprovalsByClientId() {
    Map<String, List<DescribedApproval>> result = new HashMap<>();
    ResponseEntity<Set<Approval>> approvalsResponse =
        restTemplate.exchange(
            approvalsUrl, HttpMethod.GET, null, new ParameterizedTypeReference<Set<Approval>>() {});
    Set<Approval> uaaapprovals = approvalsResponse.getBody();
    List<DescribedApproval> approvals = new ArrayList<>();
    for (Approval approval : uaaapprovals) {
      DescribedApproval describedApproval = new DescribedApproval(approval);
      approvals.add(describedApproval);
    }

    for (DescribedApproval approval : approvals) {
      List<DescribedApproval> clientApprovals = result.get(approval.getClientId());
      if (clientApprovals == null) {
        clientApprovals = new ArrayList<>();
        result.put(approval.getClientId(), clientApprovals);
      }

      String scope = approval.getScope();
      if (!scope.contains(".")) {
        approval.setDescription("Access your data with scope '" + scope + "'");
        clientApprovals.add(approval);
      } else {
        String resource = scope.substring(0, scope.lastIndexOf("."));
        if (Origin.UAA.equals(resource)) {
          // special case: don't need to prompt for internal uaa
          // scopes
          continue;
        }
        String access = scope.substring(scope.lastIndexOf(".") + 1);
        approval.setDescription(
            "Access your '" + resource + "' resources with scope '" + access + "'");
        clientApprovals.add(approval);
      }
    }
    for (List<DescribedApproval> approvalList : result.values()) {
      Collections.sort(
          approvalList,
          new Comparator<DescribedApproval>() {
            @Override
            public int compare(DescribedApproval o1, DescribedApproval o2) {
              return o1.getScope().compareTo(o2.getScope());
            }
          });
    }
    return result;
  }
 public <T> T findOne(URI uri, Class<T> targetClass) {
   Assert.state(uri != null, "uri must be set to use this method");
   try {
     return restOperations.getForObject(uri, targetClass);
     // TODO check this exception translation and centralize.
   } catch (HttpClientErrorException clientError) {
     if (clientError.getStatusCode() == HttpStatus.NOT_FOUND) {
       throw new DocumentRetrievalFailureException(uri.getPath());
     }
     throw new CouchUsageException(clientError);
   } catch (HttpServerErrorException serverError) {
     throw new CouchServerResourceUsageException(serverError);
   } catch (RestClientException otherError) {
     throw new UncategorizedCouchDataAccessException(otherError);
   }
 }
  // curl -v -H "Content-Type: application/json" -X PUT -H
  // "Accept: application/json" --data
  // "{\"password\":\"newpassword\",\"schemas\":[\"urn:scim:schemas:core:1.0\"]}"
  // http://localhost:8080/uaa/User/{id}/password
  @Test
  @OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class)
  public void testChangePasswordSucceeds() throws Exception {
    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("Newpasswo3d");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result =
        client.exchange(
            serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT,
            new HttpEntity<>(change, headers),
            Void.class,
            joe.getId());
    assertEquals(HttpStatus.OK, result.getStatusCode());
  }
  @Test
  @OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class)
  public void testChangePasswordSameAsOldFails() {
    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("pas5Word");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result =
        client.exchange(
            serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT,
            new HttpEntity<>(change, headers),
            Void.class,
            joe.getId());
    assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, result.getStatusCode());
  }
Exemple #15
0
  @Test
  public void testImplicitGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("source", "credentials");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Void> responseEntity =
        restOperations.exchange(
            loginUrl + "/oauth/authorize",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents =
        UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()).build();
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(
        Arrays.asList(scopes),
        containsInAnyOrder(
            "scim.userids",
            "password.write",
            "cloud_controller.write",
            "openid",
            "cloud_controller.read",
            "uaa.user"));

    validateToken("access_token", params.toSingleValueMap(), scopes, aud);
    validateToken("id_token", params.toSingleValueMap(), openid, new String[] {"cf"});
  }
  @Test
  public void shouldGetAllConcepts() throws Exception {
    URI url = config.toInstancePath("/concept?v=full");

    when(restOperations.exchange(
            eq(url), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class)))
        .thenReturn(getResponse(CONCEPT_LIST_RESPONSE_JSON));

    ConceptListResult result = conceptResource.getAllConcepts(config);

    verify(restOperations)
        .exchange(eq(url), eq(HttpMethod.GET), requestCaptor.capture(), eq(String.class));

    assertThat(result, equalTo(readFromFile(CONCEPT_LIST_RESPONSE_JSON, ConceptListResult.class)));
    assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForGet(config)));
    assertThat(requestCaptor.getValue().getBody(), nullValue());
  }
  @Test
  public void verifyAuthCredentialsBySettings() throws Exception {
    // TODO: This change to clear a JAVA Warning should be correct but test fails, need to
    // investigate
    // HttpEntity<HttpHeaders> headers = new
    // HttpEntity<HttpHeaders>(defaultJenkinsClient.createHeaders("user:pass"));
    @SuppressWarnings({"rawtypes", "unchecked"})
    HttpEntity headers = new HttpEntity(defaultJenkinsClient.createHeaders("does:matter"));
    when(rest.exchange(Matchers.any(URI.class), eq(HttpMethod.GET), eq(headers), eq(String.class)))
        .thenReturn(new ResponseEntity<>("", HttpStatus.OK));

    settings.setApiKey("matter");
    settings.setUsername("does");
    defaultJenkinsClient.makeRestCall("http://jenkins.com");
    verify(rest)
        .exchange(Matchers.any(URI.class), eq(HttpMethod.GET), eq(headers), eq(String.class));
  }
Exemple #18
0
  @Test
  public void testPasswordGrant() throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("cf:").getBytes()));

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", basicDigestHeaderValue);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("grant_type", "password");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Map> responseEntity =
        restOperations.exchange(
            loginUrl + "/oauth/token",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Map.class);

    Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());

    Map<String, Object> params = responseEntity.getBody();

    Assert.assertTrue(params.get("jti") != null);
    Assert.assertEquals("bearer", params.get("token_type"));
    Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode((String) params.get("scope"), "UTF-8").split(" ");
    Assert.assertThat(
        Arrays.asList(scopes),
        containsInAnyOrder(
            "scim.userids",
            "password.write",
            "cloud_controller.write",
            "openid",
            "cloud_controller.read",
            "uaa.user"));

    validateToken("access_token", params, scopes, aud);
    validateToken("id_token", params, openid, new String[] {"cf"});
  }
  @Test
  public void shouldGetConceptById() throws Exception {
    String conceptId = "LLL";
    URI url = config.toInstancePathWithParams("/concept/{uuid}", conceptId);

    when(restOperations.exchange(
            eq(url), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class)))
        .thenReturn(getResponse(CONCEPT_CREATE_JSON));

    Concept concept = conceptResource.getConceptById(config, conceptId);

    verify(restOperations)
        .exchange(eq(url), eq(HttpMethod.GET), requestCaptor.capture(), eq(String.class));

    assertThat(concept, equalTo(readFromFile(CONCEPT_CREATE_JSON, Concept.class)));
    assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForGet(config)));
    assertThat(requestCaptor.getValue().getBody(), nullValue());
  }
  @Test
  public void shouldUpdateConcept() throws Exception {
    Concept concept = prepareConcept();
    URI url = config.toInstancePathWithParams("/concept/{uuid}", concept.getUuid());

    when(restOperations.exchange(
            eq(url), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class)))
        .thenReturn(getResponse(CONCEPT_RESPONSE_JSON));

    Concept updated = conceptResource.updateConcept(config, concept);

    verify(restOperations)
        .exchange(eq(url), eq(HttpMethod.POST), requestCaptor.capture(), eq(String.class));

    assertThat(updated, equalTo(concept));
    assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForPost(config)));
    assertThat(
        JsonUtils.readJson(requestCaptor.getValue().getBody(), JsonObject.class),
        equalTo(readFromFile(CONCEPT_CREATE_JSON, JsonObject.class)));
  }
  @Test
  public void testUserLoginViaPasswordGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.add("Authorization", ((UaaTestAccounts) testAccounts).getAuthorizationHeader("cf", ""));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("grant_type", "password");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity =
        restOperations.exchange(
            baseUrl + "/oauth/token",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Void.class);

    Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
  }
  void submitProposedConcept(final ProposedConceptPackage conceptPackage) {

    checkNotNull(submissionRestTemplate);

    //
    // Could not figure out how to get Spring to send a basic authentication request using the
    // "proper" object approach
    // see: https://github.com/johnsyweb/openmrs-cpm/wiki/Gotchas
    //

    AdministrationService service = Context.getAdministrationService();
    SubmissionDto submission = submissionDtoFactory.create(conceptPackage);

    HttpHeaders headers =
        httpHeaderFactory.create(
            service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
            service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    // headers = createHeaders(service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
    //        service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    final HttpEntity requestEntity = new HttpEntity<SubmissionDto>(submission, headers);

    final String url =
        service.getGlobalProperty(CpmConstants.SETTINGS_URL_PROPERTY)
            + "/ws/cpm/dictionarymanager/proposals";
    ResponseEntity responseEntity =
        submissionRestTemplate.exchange(
            url, HttpMethod.POST, requestEntity, SubmissionResponseDto.class);

    //		final SubmissionResponseDto result =
    // submissionRestTemplate.postForObject("http://localhost:8080/openmrs/ws/cpm/dictionarymanager/proposals", submission, SubmissionResponseDto.class);
    //
    //        TODO: Find out how to determine success/failure for the submission returned by
    // dictionarymanagercontroller
    if (responseEntity == null || !responseEntity.getStatusCode().equals(HttpStatus.SC_OK)) {
      //            throw new ConceptProposalSubmissionException("Error in submitting proposed
      // concept");
      log.error("REsponseEntity status code is " + responseEntity.getStatusCode());
    }
    conceptPackage.setStatus(PackageStatus.SUBMITTED);
    Context.getService(ProposedConceptService.class).saveProposedConceptPackage(conceptPackage);
  }
Exemple #23
0
 public HttpStatus getStatusCode(String path, final HttpHeaders headers) {
   RequestCallback requestCallback = new NullRequestCallback();
   if (headers != null) {
     requestCallback =
         new RequestCallback() {
           public void doWithRequest(ClientHttpRequest request) throws IOException {
             request.getHeaders().putAll(headers);
           }
         };
   }
   return client
       .execute(
           getUrl(path),
           HttpMethod.GET,
           requestCallback,
           new ResponseExtractor<ResponseEntity<String>>() {
             public ResponseEntity<String> extractData(ClientHttpResponse response)
                 throws IOException {
               return new ResponseEntity<String>(response.getStatusCode());
             }
           })
       .getStatusCode();
 }
  @Test
  public void instanceJobs_twoJobsTwoBuilds() throws Exception {
    when(rest.exchange(
            Matchers.any(URI.class),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(
            new ResponseEntity<String>(
                getJson("instanceJobs_twoJobsTwoBuilds.json"), HttpStatus.OK));

    Map<JenkinsJob, Set<Build>> jobs = defaultJenkinsClient.getInstanceJobs(URL);

    assertThat(jobs.size(), is(2));
    Iterator<JenkinsJob> jobIt = jobs.keySet().iterator();

    // First job
    JenkinsJob job = jobIt.next();
    assertJob(job, "job1", "http://server/job/job1/");

    Iterator<Build> buildIt = jobs.get(job).iterator();
    assertBuild(buildIt.next(), "2", "http://server/job/job1/2/");
    assertBuild(buildIt.next(), "1", "http://server/job/job1/1/");
    assertThat(buildIt.hasNext(), is(false));

    // Second job
    job = jobIt.next();
    assertJob(job, "job2", "http://server/job/job2/");

    buildIt = jobs.get(job).iterator();
    assertBuild(buildIt.next(), "2", "http://server/job/job2/2/");
    assertBuild(buildIt.next(), "1", "http://server/job/job2/1/");
    assertThat(buildIt.hasNext(), is(false));

    assertThat(jobIt.hasNext(), is(false));
  }
 @Override
 public void updateApprovals(List<DescribedApproval> approvals) {
   restTemplate.put(approvalsUrl, approvals);
 }
 private ResponseEntity<String> exchange(
     Config config, URI url, HttpMethod method, String body, HttpHeaders headers) {
   headers.add("Authorization", "Basic " + prepareCredentials(config));
   return restOperations.exchange(url, method, new HttpEntity<>(body, headers), String.class);
 }
Exemple #27
0
  @Test
  public void testApprovingAnApp() throws Exception {
    ResponseEntity<SearchResults<ScimGroup>> getGroups =
        restTemplate.exchange(
            baseUrl + "/Groups?filter=displayName eq '{displayName}'",
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<SearchResults<ScimGroup>>() {},
            "cloud_controller.read");
    ScimGroup group = getGroups.getBody().getResources().stream().findFirst().get();

    group.setDescription("Read about your clouds.");
    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", Integer.toString(group.getVersion()));
    HttpEntity request = new HttpEntity(group, headers);
    restTemplate.exchange(
        baseUrl + "/Groups/{group-id}", HttpMethod.PUT, request, Object.class, group.getId());

    ScimUser user = createUnapprovedUser();

    // Visit app
    webDriver.get(appUrl);

    // Sign in to login server
    webDriver.findElement(By.name("username")).sendKeys(user.getUserName());
    webDriver.findElement(By.name("password")).sendKeys(user.getPassword());
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();

    // Authorize the app for some scopes
    Assert.assertEquals(
        "Application Authorization", webDriver.findElement(By.cssSelector("h1")).getText());

    webDriver
        .findElement(By.xpath("//label[text()='Change your password']/preceding-sibling::input"))
        .click();
    webDriver
        .findElement(
            By.xpath(
                "//label[text()='Read user IDs and retrieve users by ID']/preceding-sibling::input"))
        .click();
    webDriver.findElement(
        By.xpath("//label[text()='Read about your clouds.']/preceding-sibling::input"));

    webDriver.findElement(By.xpath("//button[text()='Authorize']")).click();

    Assert.assertEquals("Sample Home Page", webDriver.findElement(By.cssSelector("h1")).getText());

    // View profile on the login server
    webDriver.get(baseUrl + "/profile");

    Assert.assertFalse(
        webDriver.findElement(By.xpath("//input[@value='app-password.write']")).isSelected());
    Assert.assertFalse(
        webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.read']"))
            .isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.write']"))
            .isSelected());

    // Add approvals
    webDriver.findElement(By.xpath("//input[@value='app-password.write']")).click();
    webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).click();

    webDriver.findElement(By.xpath("//button[text()='Update']")).click();

    Assert.assertTrue(
        webDriver.findElement(By.xpath("//input[@value='app-password.write']")).isSelected());
    Assert.assertTrue(
        webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.read']"))
            .isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.write']"))
            .isSelected());

    // Revoke app
    webDriver.findElement(By.linkText("Revoke Access")).click();

    Assert.assertEquals(
        "Are you sure you want to revoke access to The Ultimate Oauth App?",
        webDriver.findElement(By.cssSelector(".revocation-modal p")).getText());

    // click cancel
    webDriver.findElement(By.cssSelector("#app-form .revocation-cancel")).click();

    webDriver.findElement(By.linkText("Revoke Access")).click();

    // click confirm
    webDriver.findElement(By.cssSelector("#app-form .revocation-confirm")).click();

    Assert.assertThat(
        webDriver.findElements(By.xpath("//input[@value='app-password.write']")), Matchers.empty());
  }
Exemple #28
0
 private boolean clientExists(RestOperations client, OAuth2ProtectedResourceDetails resource) {
   ResponseEntity<String> response =
       client.getForEntity(
           serverRunning.getClientsUri() + "/" + resource.getClientId(), String.class);
   return response != null && response.getStatusCode() == HttpStatus.OK;
 }
Exemple #29
0
 private void createClient(RestOperations client, ClientDetails clientDetails) {
   ResponseEntity<String> response =
       client.postForEntity(serverRunning.getClientsUri(), clientDetails, String.class);
   assertEquals(HttpStatus.CREATED, response.getStatusCode());
 }
  @Test
  public void test_endToend() throws Exception {

    String artifacts = getJson("job-artifacts.json");
    String cucumberJson = getJson("two-features.json");

    URI lastBuildArtifactUri =
        URI.create(
            "http://server/job/job1/lastSuccessfulBuild/api/json?tree=timestamp,duration,number,fullDisplayName,building,artifacts[fileName,relativePath]");
    URI cucumberJsonUri =
        URI.create(
            "http://server/job/job1/lastSuccessfulBuild/artifact/job1/test1/report/web/cucumber.json");
    when(rest.exchange(
            eq(lastBuildArtifactUri),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(new ResponseEntity<String>(artifacts, HttpStatus.OK));
    when(rest.exchange(
            eq(cucumberJsonUri),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(new ResponseEntity<String>(cucumberJson, HttpStatus.OK));
    TestResult testResult = defaultJenkinsClient.getCucumberTestResult("http://server/job/job1/");
    Collection<TestCapability> capabilities = testResult.getTestCapabilities();
    assertThat(capabilities, notNullValue());

    Iterator<TestCapability> capabilityIterator = capabilities.iterator();

    TestCapability capability = capabilityIterator.next();
    List<TestSuite> suites = (List<TestSuite>) capability.getTestSuites();
    assertThat(suites, notNullValue());

    Iterator<TestSuite> suiteIt = suites.iterator();
    Iterator<TestCase> testCaseIt;
    TestSuite suite;

    suite = suiteIt.next();
    testCaseIt = suite.getTestCases().iterator();
    assertSuite(suite, "Feature:eCUKE Feature", 4, 0, 0, 4, 15019839l);

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;i-say-hi",
        "Scenario:I say hi",
        4001555l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(true));

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;you-say-hi",
        "Scenario:You say hi",
        1001212l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(true));

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;eating-cucumbers",
        "Scenario Outline:Eating Cucumbers",
        2013197l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(true));

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;eating-cucumbers",
        "Scenario Outline:Eating Cucumbers",
        8003875l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(false));
  }