Example #1
0
 protected void testForbiddenImpersonation(String admin, String adminRealm) {
   Client client = createClient(admin, adminRealm);
   WebTarget impersonate = createImpersonateTarget(client);
   Response response = impersonate.request().post(null);
   response.close();
   client.close();
 }
 public void testErrorHandling() throws Exception {
   ErrorServlet.authError = null;
   Client client = ClientBuilder.newClient();
   // make sure
   Response response = client.target(APP_SERVER_BASE_URL + "/employee-sig/").request().get();
   response.close();
   SAML2ErrorResponseBuilder builder =
       new SAML2ErrorResponseBuilder()
           .destination(APP_SERVER_BASE_URL + "/employee-sig/saml")
           .issuer(AUTH_SERVER_URL + "/realms/demo")
           .status(JBossSAMLURIConstants.STATUS_REQUEST_DENIED.get());
   BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder().relayState(null);
   Document document = builder.buildDocument();
   URI uri =
       binding
           .redirectBinding(document)
           .generateURI(APP_SERVER_BASE_URL + "/employee-sig/saml", false);
   response = client.target(uri).request().get();
   String errorPage = response.readEntity(String.class);
   response.close();
   Assert.assertTrue(errorPage.contains("Error Page"));
   client.close();
   Assert.assertNotNull(ErrorServlet.authError);
   SamlAuthenticationError error = (SamlAuthenticationError) ErrorServlet.authError;
   Assert.assertEquals(SamlAuthenticationError.Reason.ERROR_STATUS, error.getReason());
   Assert.assertNotNull(error.getStatus());
   ErrorServlet.authError = null;
 }
Example #3
0
  public static void uploadSP() {
    String token = createToken();
    final String authHeader = "Bearer " + token;
    ClientRequestFilter authFilter =
        new ClientRequestFilter() {
          @Override
          public void filter(ClientRequestContext requestContext) throws IOException {
            requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader);
          }
        };
    Client client = ClientBuilder.newBuilder().register(authFilter).build();
    UriBuilder authBase = UriBuilder.fromUri("http://localhost:8081/auth");
    WebTarget adminRealms = client.target(AdminRoot.realmsUrl(authBase));

    MultipartFormDataOutput formData = new MultipartFormDataOutput();
    InputStream is = SamlBindingTest.class.getResourceAsStream("/saml/sp-metadata.xml");
    Assert.assertNotNull(is);
    formData.addFormData("file", is, MediaType.APPLICATION_XML_TYPE);

    WebTarget upload =
        adminRealms.path("demo/application-importers/saml2-entity-descriptor/upload");
    System.out.println(upload.getUri());
    Response response =
        upload.request().post(Entity.entity(formData, MediaType.MULTIPART_FORM_DATA));
    Assert.assertEquals(204, response.getStatus());
    response.close();
    client.close();
  }
 /** Clean up resources. */
 @Override
 public void destroyResources() {
   if (eurekaConnCleaner != null) {
     // Execute the connection cleaner one final time during shutdown
     eurekaConnCleaner.execute(connectionCleanerTask);
     eurekaConnCleaner.shutdown();
   }
   if (apacheHttpClient != null) {
     apacheHttpClient.close();
   }
 }
 @Override
 public void shutDown() {
   try {
     try {
       client.close();
     } finally {
       executorService.shutdown();
     }
   } finally {
     super.shutDown();
   }
   LOGGER.info("The documents4j remote converter has shut down successfully (URI: {})", baseUri);
 }
  @Test
  public void testGetChaptersAsJson() throws JsonParseException, JsonMappingException, IOException {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(AppHelper.getServiceUrl("chapters"));

    String content = target.request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    ObjectMapper mapper = new ObjectMapper();
    Chapters chapters = mapper.readValue(content, Chapters.class);

    assertEquals(new Integer(50), chapters.getSize());
    assertEquals(MAX_ELEMENTS_BY_QUERY, chapters.getChapters().size());
  }
  @Test
  public void testGetChaptersAsXml() throws JAXBException {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(AppHelper.getServiceUrl("chapters"));

    String content = target.request(MediaType.APPLICATION_XML).get(String.class);
    client.close();

    Unmarshaller u = JAXBContext.newInstance(Chapters.class).createUnmarshaller();
    Chapters chapters = (Chapters) u.unmarshal(new StringReader(content));

    assertEquals(new Integer(50), chapters.getSize());
    assertEquals(MAX_ELEMENTS_BY_QUERY, chapters.getChapters().size());
  }
  @Test
  public void testGetChapterAsJson() throws JsonParseException, JsonMappingException, IOException {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(AppHelper.getServiceUrl("chapters/1"));

    String content = target.request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    ObjectMapper mapper = new ObjectMapper();
    Chapter chapter = mapper.readValue(content, Chapter.class);

    assertEquals(new Integer(1), chapter.getChapterId());
    assertEquals(new Integer(1), chapter.getBookId());
    assertEquals("1", chapter.getNumber());
  }
  @Test
  public void testGetChapterAsXml() throws JAXBException {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(AppHelper.getServiceUrl("chapters/1"));

    String content = target.request(MediaType.APPLICATION_XML).get(String.class);
    client.close();

    Unmarshaller u = JAXBContext.newInstance(Chapters.class).createUnmarshaller();
    Chapter chapter = (Chapter) u.unmarshal(new StringReader(content));

    assertEquals(new Integer(1), chapter.getChapterId());
    assertEquals(new Integer(1), chapter.getBookId());
    assertEquals("1", chapter.getNumber());
  }
Example #10
0
  /**
   * Utility method that safely closes a client instance without throwing an exception.
   *
   * @param clients client instances to close. Each instance may be {@code null}.
   * @since 2.5
   */
  public static void closeIfNotNull(final Client... clients) {
    if (clients == null || clients.length == 0) {
      return;
    }

    for (final Client c : clients) {
      if (c == null) {
        continue;
      }
      try {
        c.close();
      } catch (final Throwable t) {
        LOGGER.log(Level.WARNING, "Error closing a client instance.", t);
      }
    }
  }
Example #11
0
  public synchronized void dispose() {
    if (httpClient != null) {
      try {
        httpClient.close();
      } catch (IOException e) {
        // eat it
      }
      httpClient = null;
    }

    if (client != null) {
      client.close();
      client = null;
    }

    disposed = true;
  }
Example #12
0
  protected void testSuccessfulImpersonation(String admin, String adminRealm) {
    Client client = createClient(admin, adminRealm);
    WebTarget impersonate = createImpersonateTarget(client);
    Map data = impersonate.request().post(null, Map.class);
    Assert.assertNotNull(data);
    Assert.assertNotNull(data.get("redirect"));

    events
        .expect(EventType.IMPERSONATE)
        .session(AssertEvents.isUUID())
        .user(impersonatedUserId)
        .detail(Details.IMPERSONATOR, admin)
        .detail(Details.IMPERSONATOR_REALM, adminRealm)
        .client((String) null)
        .assertEvent();

    client.close();
  }
Example #13
0
  /** Shutdown this processor. */
  @PreDestroy
  public void shutDown() {
    dequeuerIsActive = false;
    cleanerIsActive = false;

    // CHECKSTYLE:OFF
    if (workers != null) {
      try {
        workers.shutdown();
      } catch (Exception ignore) {
      }
    }
    if (client != null) {
      try {
        client.close();
      } catch (Exception ignore) {
      }
    }
    // CHECKSTYLE:ON
  }
  public void testSavedPostRequest() throws Exception {
    // test login to customer-portal which does a bearer request to customer-db
    driver.navigate().to(APP_SERVER_BASE_URL + "/input-portal");
    System.err.println("*********** Current url: " + driver.getCurrentUrl());
    Assert.assertTrue(driver.getCurrentUrl().startsWith(APP_SERVER_BASE_URL + "/input-portal"));
    inputPage.execute("hello");

    assertAtLoginPagePostBinding();
    loginPage.login("*****@*****.**", "password");
    System.out.println("Current url: " + driver.getCurrentUrl());
    Assert.assertEquals(driver.getCurrentUrl(), APP_SERVER_BASE_URL + "/input-portal/secured/post");
    String pageSource = driver.getPageSource();
    System.out.println(pageSource);
    Assert.assertTrue(pageSource.contains("parameter=hello"));
    // test that user principal and KeycloakSecurityContext available
    driver.navigate().to(APP_SERVER_BASE_URL + "/input-portal/insecure");
    System.out.println("insecure: ");
    System.out.println(driver.getPageSource());
    Assert.assertTrue(driver.getPageSource().contains("Insecure Page"));
    if (System.getProperty("insecure.user.principal.unsupported") == null)
      Assert.assertTrue(driver.getPageSource().contains("UserPrincipal"));

    // test logout

    driver.navigate().to(APP_SERVER_BASE_URL + "/input-portal?GLO=true");

    // test unsecured POST KEYCLOAK-901

    Client client = ClientBuilder.newClient();
    Form form = new Form();
    form.param("parameter", "hello");
    String text =
        client
            .target(APP_SERVER_BASE_URL + "/input-portal/unsecured")
            .request()
            .post(Entity.form(form), String.class);
    Assert.assertTrue(text.contains("parameter=hello"));
    client.close();
  }
  @Test
  public void testGetEmployee() throws IOException {
    if (null == cookie) {
      fail("cannot login!!!");
    }

    Client client = new ResteasyClientBuilder().build();
    client.register(new CookieRequestFilter(cookie));
    WebTarget target = client.target(baseUrl + "/rest/ag/employee/100");
    Response response = target.request().get();

    // System.out.println( response.readEntity(String.class));
    int status = response.getStatus();
    System.out.println("response status code: " + status);
    boolean hasEntity = response.hasEntity();
    System.out.println("response has entity? " + hasEntity);

    Employee epl = response.readEntity(Employee.class);
    System.out.println(epl.toString());

    client.close();
    assertEquals("same first name", "Beyond", epl.getFirstName());
  }
Example #16
0
 @AfterClass
 public static void after() throws Exception {
   client.close();
   client = null;
 }
 @AfterClass
 public static void closeClient() {
   client.close();
 }
 @Override
 public void close() throws IOException {
   client.close();
 }
  /**
   * uploads zip file using the input HTTP URL
   *
   * @param httpURL
   * @param filePath
   * @param filename
   * @return
   * @throws Exception
   */
  public static String testUploadService(String httpURL, File filePath) throws Exception {

    // local variables
    ClientConfig clientConfig = null;
    Client client = null;
    WebTarget webTarget = null;
    Invocation.Builder invocationBuilder = null;
    Response response = null;
    FileDataBodyPart fileDataBodyPart = null;
    FormDataMultiPart formDataMultiPart = null;
    int responseCode;
    String responseMessageFromServer = null;
    String responseString = null;

    try {
      // invoke service after setting necessary parameters
      clientConfig = new ClientConfig();
      clientConfig.register(MultiPartFeature.class);
      client = ClientBuilder.newClient(clientConfig);
      webTarget = client.target(httpURL);

      // set file upload values
      fileDataBodyPart =
          new FileDataBodyPart("uploadFile", filePath, MediaType.APPLICATION_OCTET_STREAM_TYPE);
      formDataMultiPart = new FormDataMultiPart();
      formDataMultiPart.bodyPart(fileDataBodyPart);

      StreamDataBodyPart bodyPart = new StreamDataBodyPart();

      // invoke service
      invocationBuilder = webTarget.request();
      //          invocationBuilder.header("Authorization", "Basic " + authorization);
      response =
          invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

      // get response code
      responseCode = response.getStatus();
      System.out.println("Response code: " + responseCode);

      if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
      }

      // get response message
      responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
      System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

      // get response string
      responseString = response.readEntity(String.class);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      // release resources, if any
      fileDataBodyPart.cleanup();
      formDataMultiPart.cleanup();
      formDataMultiPart.close();
      response.close();
      client.close();
    }
    return responseString;
  }
Example #20
0
 @Override
 public void dispose(Client instance) {
   instance.close();
 }
 @After
 public void tearDown() throws Exception {
   client.close();
 }
Example #22
0
 @After
 public void after() {
   client.close();
 }
 @After
 public void tear() {
   client.close();
 }
Example #24
0
 @AfterClass
 public static void afterClass() {
   client.close();
 }
 public void close() {
   client.close();
 }
 public void close() {
   // client.destroy();
   client.close();
 }
Example #27
0
 @AfterClass
 public static void cleanup() {
   client.close();
 }
 @Override
 public void close() throws IOException {
   checkNotNull(client, "Factory not initialized. You probably forgot to call init()!");
   client.close();
 }