javax.ws.rs.core.Response

Here are the examples of the java api class javax.ws.rs.core.Response taken from open source projects.

1. JacksonTest#testJackson()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testJackson() throws Exception {
    WebTarget target = client.target(generateURL("/products/333"));
    Response response = target.request().get();
    Product p = response.readEntity(Product.class);
    Assert.assertEquals(333, p.getId());
    Assert.assertEquals("Iphone", p.getName());
    response.close();
    target = client.target(generateURL("/products"));
    Response response2 = target.request().get();
    String entity2 = response2.readEntity(String.class);
    System.out.println(entity2);
    Assert.assertEquals(200, response2.getStatus());
    response2.close();
    target = client.target(generateURL("/products/333"));
    response = target.request().post(Entity.entity(p, "application/foo+json"));
    p = response.readEntity(Product.class);
    Assert.assertEquals(333, p.getId());
    Assert.assertEquals("Iphone", p.getName());
    response.close();
}

2. JacksonTest#testJackson()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testJackson() throws Exception {
    WebTarget target = client.target(generateURL("/products/333"));
    Response response = target.request().get();
    Product p = response.readEntity(Product.class);
    Assert.assertEquals(333, p.getId());
    Assert.assertEquals("Iphone", p.getName());
    response.close();
    target = client.target(generateURL("/products"));
    Response response2 = target.request().get();
    System.out.println(response2.readEntity(String.class));
    Assert.assertEquals(200, response2.getStatus());
    response2.close();
    target = client.target(generateURL("/products/333"));
    response = target.request().post(Entity.entity(p, "application/foo+json"));
    p = response.readEntity(Product.class);
    Assert.assertEquals(333, p.getId());
    Assert.assertEquals("Iphone", p.getName());
    response.close();
}

3. CustomerResourceTest#testCustomerResource()

Project: Resteasy
Source File: CustomerResourceTest.java
View license
@Test
public void testCustomerResource() throws Exception {
    WebTarget customerTarget = client.target("http://localhost:8080/services/customers/1");
    Response response = customerTarget.request().get();
    Assert.assertEquals(200, response.getStatus());
    Customer cust = response.readEntity(Customer.class);
    EntityTag etag = response.getEntityTag();
    response.close();
    System.out.println("Doing a conditional GET with ETag: " + etag.toString());
    response = customerTarget.request().header("If-None-Match", etag).get();
    Assert.assertEquals(304, response.getStatus());
    response.close();
    // Update and send a bad etag with conditional PUT
    cust.setCity("Bedford");
    response = customerTarget.request().header("If-Match", "JUNK").put(Entity.xml(cust));
    Assert.assertEquals(412, response.getStatus());
    response.close();
}

4. JacksonTest#testJacksonString()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testJacksonString() throws Exception {
    WebTarget target = client.target(generateURL("/products/333"));
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println(entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("{\"name\":\"Iphone\",\"id\":333}", entity);
    response.close();
    target = client.target(generateURL("/products"));
    Response response2 = target.request().get();
    String entity2 = response2.readEntity(String.class);
    System.out.println(entity2);
    Assert.assertEquals(200, response2.getStatus());
    Assert.assertEquals("[{\"name\":\"Iphone\",\"id\":333},{\"name\":\"macbook\",\"id\":44}]", entity2);
    response2.close();
}

5. JacksonTest#testXmlString()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testXmlString() throws Exception {
    WebTarget target = client.target(generateURL("/xml/products/333"));
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println(entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(entity.startsWith("{\"product"));
    response.close();
    target = client.target(generateURL("/xml/products"));
    Response response2 = target.request().get();
    String entity2 = response2.readEntity(String.class);
    System.out.println(entity2);
    Assert.assertEquals(200, response2.getStatus());
    Assert.assertTrue(entity2.startsWith("[{\"product"));
    response2.close();
}

6. JacksonTest#testJacksonString()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testJacksonString() throws Exception {
    WebTarget target = client.target(generateURL("/products/333"));
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println(entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("{\"name\":\"Iphone\",\"id\":333}", entity);
    response.close();
    target = client.target(generateURL("/products"));
    Response response2 = target.request().get();
    String entity2 = response2.readEntity(String.class);
    System.out.println(entity2);
    Assert.assertEquals(200, response2.getStatus());
    Assert.assertEquals("[{\"name\":\"Iphone\",\"id\":333},{\"name\":\"macbook\",\"id\":44}]", entity2);
    response2.close();
}

7. JacksonTest#testXmlString()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testXmlString() throws Exception {
    WebTarget target = client.target(generateURL("/xml/products/333"));
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println(entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(entity.startsWith("{\"product"));
    response.close();
    target = client.target(generateURL("/xml/products"));
    Response response2 = target.request().get();
    String entity2 = response2.readEntity(String.class);
    System.out.println(entity2);
    Assert.assertEquals(200, response2.getStatus());
    Assert.assertTrue(entity2.startsWith("[{\"product"));
    response2.close();
}

8. MultipleEndpointsWarningTest#testUnique()

View license
@Test
public void testUnique() throws Exception {
    Client client = ClientBuilder.newClient();
    Response response = client.target(generateURL("/unique")).request().accept(MediaType.TEXT_PLAIN, MediaType.WILDCARD).get();
    response.close();
    Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
    response = client.target(generateURL("/unique")).request().get();
    response.close();
    Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
    response = client.target(generateURL("/unique")).request().accept(MediaType.TEXT_PLAIN).get();
    response.close();
    Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
}

9. MultipleEndpointsWarningTest#testDifferentVerbs()

View license
@Test
public void testDifferentVerbs() throws Exception {
    Client client = ClientBuilder.newClient();
    Response response = client.target(generateURL("/verbs")).request().accept(MediaType.TEXT_PLAIN).get();
    response.close();
    Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
    response = client.target(generateURL("/verbs")).request().accept(MediaType.TEXT_PLAIN, MediaType.WILDCARD).get();
    response.close();
    Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
    response = client.target(generateURL("/verbs")).request().get();
    response.close();
    Assert.assertEquals("Incorrectly logged " + MESSAGE_CODE, 0, logHandler.messagesLogged);
}

10. ConverterTest#testToInputStream()

Project: camel
Source File: ConverterTest.java
View license
@Test
public void testToInputStream() throws Exception {
    CamelContext context = new DefaultCamelContext();
    Exchange exchange = new DefaultExchange(context);
    Response response = EasyMock.createMock(Response.class);
    InputStream is = EasyMock.createMock(InputStream.class);
    response.getEntity();
    EasyMock.expectLastCall().andReturn(is);
    EasyMock.replay(response);
    InputStream result = CxfConverter.toInputStream(response, exchange);
    assertEquals("We should get the inputStream here ", is, result);
    EasyMock.verify(response);
    EasyMock.reset(response);
    response.getEntity();
    EasyMock.expectLastCall().andReturn("Hello World");
    EasyMock.replay(response);
    result = CxfConverter.toInputStream(response, exchange);
    assertTrue("We should get the inputStream here ", result instanceof ByteArrayInputStream);
    EasyMock.verify(response);
}

11. AdapterTestStrategy#testNullBearerToken()

Project: keycloak
Source File: AdapterTestStrategy.java
View license
/**
     * KEYCLOAK-518
     * @throws Exception
     */
public void testNullBearerToken() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(APP_SERVER_BASE_URL + "/customer-db/");
    Response response = target.request().get();
    Assert.assertEquals(401, response.getStatus());
    response.close();
    response = target.request().header(HttpHeaders.AUTHORIZATION, "Bearer null").get();
    Assert.assertEquals(401, response.getStatus());
    response.close();
    client.close();
}

12. AbstractDemoServletsAdapterTest#testNullBearerToken()

View license
@Test
public void testNullBearerToken() {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(customerDb.toString());
    Response response = target.request().get();
    assertEquals(401, response.getStatus());
    response.close();
    response = target.request().header(HttpHeaders.AUTHORIZATION, "Bearer null").get();
    assertEquals(401, response.getStatus());
    response.close();
    client.close();
}

13. UserFederationMapperTest#initFederationProviders()

View license
@Before
public void initFederationProviders() {
    UserFederationProviderRepresentation ldapRep = UserFederationProviderBuilder.create().displayName("ldap-1").providerName("ldap").priority(1).build();
    Response resp = realm.userFederation().create(ldapRep);
    this.ldapProviderId = ApiUtil.getCreatedId(resp);
    resp.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userFederationResourcePath(this.ldapProviderId), ldapRep);
    UserFederationProviderRepresentation dummyRep = UserFederationProviderBuilder.create().displayName("dummy-1").providerName("dummy").priority(2).build();
    resp = realm.userFederation().create(dummyRep);
    this.dummyProviderId = ApiUtil.getCreatedId(resp);
    resp.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userFederationResourcePath(this.dummyProviderId), dummyRep);
}

14. JaxrsAsyncTest#testCancel()

Project: Resteasy
Source File: JaxrsAsyncTest.java
View license
@Test
public void testCancel() throws Exception {
    Client client = ClientBuilder.newClient();
    Response response = client.target("http://localhost:8080/jaxrs/cancel").request().get();
    Assert.assertEquals(503, response.getStatus());
    response.close();
    response = client.target("http://localhost:8080/jaxrs/cancelled").request().get();
    Assert.assertEquals(204, response.getStatus());
    response.close();
    client.close();
}

15. CallbackTest#argumentContainsExceptionInTwoCallbackClassesTest()

Project: Resteasy
Source File: CallbackTest.java
View license
@Test
public void argumentContainsExceptionInTwoCallbackClassesTest() throws Exception {
    invokeClear();
    invokeReset();
    Future<Response> suspend = client.target("http://localhost:8080/resource/suspend").request().async().get();
    Future<Response> register = client.target("http://localhost:8080/resource/registerclasses?stage=0").request().async().get();
    assertString(register, Resource.FALSE);
    Future<Response> exception = client.target("http://localhost:8080/resource/exception?stage=1").request().async().get();
    Response response = exception.get();
    Response suspendResponse = suspend.get();
    Assert.assertEquals(suspendResponse.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR);
    suspendResponse.close();
    Future<Response> error = client.target("http://localhost:8080/resource/error").request().async().get();
    assertString(error, RuntimeException.class.getName());
    error = client.target("http://localhost:8080/resource/seconderror").request().async().get();
    assertString(error, RuntimeException.class.getName());
}

16. CallbackTest#argumentContainsExceptionInTwoCallbackInstancesTest()

Project: Resteasy
Source File: CallbackTest.java
View license
@Test
public void argumentContainsExceptionInTwoCallbackInstancesTest() throws Exception {
    invokeClear();
    invokeReset();
    Future<Response> suspend = client.target("http://localhost:8080/resource/suspend").request().async().get();
    Future<Response> register = client.target("http://localhost:8080/resource/registerobjects?stage=0").request().async().get();
    assertString(register, Resource.FALSE);
    Future<Response> exception = client.target("http://localhost:8080/resource/exception?stage=1").request().async().get();
    Response response = exception.get();
    Response suspendResponse = suspend.get();
    Assert.assertEquals(suspendResponse.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR);
    suspendResponse.close();
    Future<Response> error = client.target("http://localhost:8080/resource/error").request().async().get();
    assertString(error, RuntimeException.class.getName());
    error = client.target("http://localhost:8080/resource/seconderror").request().async().get();
    assertString(error, RuntimeException.class.getName());
}

17. CallbackTest#argumentContainsExceptionWhenSendingIoExceptionTest()

Project: Resteasy
Source File: CallbackTest.java
View license
@Test
public void argumentContainsExceptionWhenSendingIoExceptionTest() throws Exception {
    invokeClear();
    invokeReset();
    Future<Response> suspend = client.target("http://localhost:8080/resource/suspend").request().async().get();
    Future<Response> register = client.target("http://localhost:8080/resource/register?stage=0").request().async().get();
    assertString(register, Resource.FALSE);
    Future<Response> exception = client.target("http://localhost:8080/resource/resumechecked?stage=1").request().async().get();
    Response response = exception.get();
    Response suspendResponse = suspend.get();
    Assert.assertEquals(suspendResponse.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR);
    suspendResponse.close();
    Future<Response> error = client.target("http://localhost:8080/resource/error").request().async().get();
    assertString(error, IOException.class.getName());
}

18. ProxyWithGenericReturnTypeJacksonTest#test()

View license
@Test
public void test() throws Exception {
    ResteasyClient client = new ResteasyClientBuilder().build();
    WebTarget target = client.target("http://localhost:8081/test/one/");
    System.out.println("Sending request");
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println("Received response: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue("Type property is missing.", entity.contains("type"));
    response.close();
    target = client.target("http://localhost:8081/test/list/");
    System.out.println("Sending request");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received response: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue("Type property is missing.", entity.contains("type"));
    response.close();
    client.close();
}

19. ProxyWithGenericReturnTypeJacksonTest#test()

View license
@Test
public void test() throws Exception {
    ResteasyClient client = new ResteasyClientBuilder().build();
    WebTarget target = client.target("http://localhost:8081/test/one/");
    System.out.println("Sending request");
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println("Received response: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue("Type property is missing.", entity.contains("type"));
    response.close();
    target = client.target("http://localhost:8081/test/list/");
    System.out.println("Sending request");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received response: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue("Type property is missing.", entity.contains("type"));
    response.close();
    client.close();
}

20. StreamResetTest#testJBEAP2138()

Project: Resteasy
Source File: StreamResetTest.java
View license
@Test
public void testJBEAP2138() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(TestPortProvider.generateURL("/test"));
    Response response = target.request().get();
    response.bufferEntity();
    try {
        response.readEntity(Place.class);
    } catch (Exception e) {
    }
    response.readEntity(Person.class);
}

21. InternalDispatcherTest#testClientResponse()

View license
@Test
public void testClientResponse() throws Exception {
    Client proxy = client.target(generateBaseUrl()).proxy(Client.class);
    Assert.assertEquals("basic", proxy.getBasic());
    Assert.assertEquals("basic", proxy.getForwardBasic());
    Assert.assertEquals("object1", proxy.getObject(1).readEntity(String.class));
    Assert.assertEquals("object1", proxy.getForwardedObject(1).readEntity(String.class));
    Response cr = proxy.getObject(0);
    Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
    cr.close();
    cr = proxy.getForwardedObject(0);
    Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
    cr.close();
    proxy.putForwardBasic("testBasic");
    Assert.assertEquals("testBasic", proxy.getBasic());
    proxy.postForwardBasic("testBasic1");
    Assert.assertEquals("testBasic1", proxy.getBasic());
    proxy.deleteForwardBasic();
    Assert.assertEquals("basic", proxy.getBasic());
}

22. ResponseTest#testHead()

Project: Resteasy
Source File: ResponseTest.java
View license
@Test
public void testHead() {
    // mucks up stream so create our own client.
    //Client client = ClientBuilder.newClient();
    Response response = client.target(generateURL("/head")).request().head();
    Assert.assertEquals(200, response.getStatus());
    if (response.hasEntity()) {
        String str = response.readEntity(String.class);
    }
    response.close();
//client.close();
}

23. ResponseTest#readEntityGenericTypeTest()

Project: Resteasy
Source File: ResponseTest.java
View license
@Test
public void readEntityGenericTypeTest() throws Exception {
    Response response = client.target(generateURL("/entity")).request().get();
    Assert.assertEquals(200, response.getStatus());
    response.bufferEntity();
    String line;
    Reader reader = response.readEntity(new GenericType<Reader>(Reader.class));
    line = readLine(reader);
    Assert.assertTrue(Resource.ENTITY.equals(line));
    byte[] buffer = new byte[0];
    buffer = response.readEntity(generic(buffer.getClass()));
    Assert.assertNotNull(buffer);
    line = new String(buffer);
    Assert.assertTrue(Resource.ENTITY.equals(line));
    response.close();
}

24. JaxrsAsyncTest#testCancelled()

Project: Resteasy
Source File: JaxrsAsyncTest.java
View license
@Test(timeout = REQUEST_TIMEOUT)
public void testCancelled() throws Exception {
    Response response = null;
    response = client.target(BASE_URI).path("jaxrs/cancelled").request().put(null);
    Assert.assertEquals(204, response.getStatus());
    response.close();
    Thread.sleep(100);
    response = client.target(BASE_URI).path("jaxrs/cancelled").request().get();
    Assert.assertEquals(500, response.getStatus());
    response.close();
    Thread.sleep(100);
}

25. HttpNotificationSender#sendNotification()

Project: digdag
Source File: HttpNotificationSender.java
View license
@Override
public void sendNotification(Notification notification) throws NotificationException {
    Response response = target.request().headers(headers).method(method, Entity.entity(notification, "application/json"));
    response.close();
    if (response.getStatusInfo().getFamily() != SUCCESSFUL) {
        throw new NotificationException("Failed to send HTTP notification: status=" + response.getStatusInfo());
    }
}

26. PushEndpointTest#testUnregister()

Project: divide
Source File: PushEndpointTest.java
View license
//
@Test
public void testUnregister() throws Exception {
    Credentials user = AuthenticationEndpointTest.signUpUser(this);
    PublicKey key = AuthenticationEndpointTest.getPublicKey(this);
    Response tokenResponse = registerToken(user, key, this);
    String newAuthToken = tokenResponse.getHeaderString("Authorization");
    Response response = target("/push").request().header(ContainerRequest.AUTHORIZATION, "CUSTOM " + newAuthToken).delete();
    int statusCode = response.getStatus();
    assertEquals(200, statusCode);
    Collection<TransientObject> list = container.serverDao.get(Query.safeTable(Credentials.class), user.getObjectKey());
    TransientObject o = ObjectUtils.get1stOrNull(list);
    user = TestUtils.convert(o, Credentials.class);
    assertNotNull(user);
    // check the token was actually saved
    assertEquals("", user.getPushMessagingKey());
}

27. AuthCmdExec#execute()

Project: docker-java
Source File: AuthCmdExec.java
View license
@Override
protected AuthResponse execute(AuthCmd command) {
    WebTarget webResource = getBaseResource().path("/auth");
    LOGGER.trace("POST: {}", webResource);
    Response response = webResource.request().accept(MediaType.APPLICATION_JSON).post(entity(command.getAuthConfig(), MediaType.APPLICATION_JSON));
    if (response.getStatus() == 401) {
        throw new UnauthorizedException("Unauthorized");
    }
    return response.readEntity(AuthResponse.class);
}

28. HttpSessionFactoryTest#passesInHttpSessions()

View license
@Test
public void passesInHttpSessions() throws Exception {
    Response firstResponse = target("/session/").request(MediaType.TEXT_PLAIN).post(Entity.entity("Mr. Peeps", MediaType.TEXT_PLAIN));
    final Map<String, NewCookie> cookies = firstResponse.getCookies();
    firstResponse.close();
    Invocation.Builder builder = target("/session/").request().accept(MediaType.TEXT_PLAIN);
    for (NewCookie cookie : cookies.values()) {
        builder.cookie(cookie);
    }
    assertThat(builder.get(String.class)).isEqualTo("Mr. Peeps");
}

29. ConstraintViolationExceptionMapperTest#getInvalidQueryParamsIs400()

View license
@Test
public void getInvalidQueryParamsIs400() throws Exception {
    // query parameter is too short and so will fail validation
    final Response response = target("/valid/bar").queryParam("name", "hi").request().get();
    assertThat(response.getStatus()).isEqualTo(400);
    String ret = "{\"errors\":[\"query param name length must be between 3 and 2147483647\"]}";
    assertThat(response.readEntity(String.class)).isEqualTo(ret);
    // Send another request to trigger reflection cache
    final Response cache = target("/valid/bar").queryParam("name", "hi").request().get();
    assertThat(cache.getStatus()).isEqualTo(400);
    assertThat(cache.readEntity(String.class)).isEqualTo(ret);
}

30. ConstraintViolationExceptionMapperTest#cacheIsForParamNamesOnly()

View license
@Test
public void cacheIsForParamNamesOnly() throws Exception {
    // query parameter must not be null, and must be at least 3
    final Response response = target("/valid/fhqwhgads").queryParam("num", 2).request().get();
    assertThat(response.getStatus()).isEqualTo(400);
    String ret = "{\"errors\":[\"query param num must be greater than or equal to 3\"]}";
    assertThat(response.readEntity(String.class)).isEqualTo(ret);
    // Send another request to trigger reflection cache. This one is invalid in a different way
    // and should get a different message.
    final Response cache = target("/valid/fhqwhgads").request().get();
    assertThat(cache.getStatus()).isEqualTo(400);
    ret = "{\"errors\":[\"query param num may not be null\"]}";
    assertThat(cache.readEntity(String.class)).isEqualTo(ret);
}

31. ConstraintViolationExceptionMapperTest#functionWithSameNameReturnDifferentErrors()

View license
@Test
public void functionWithSameNameReturnDifferentErrors() throws Exception {
    // This test is to make sure that functions with the same name and
    // number of parameters (but different parameter types), don't return
    // the same validation error due to any caching effects
    final Response response = target("/valid/head").request().get();
    String ret = "{\"errors\":[\"header cheese may not be empty\"]}";
    assertThat(response.readEntity(String.class)).isEqualTo(ret);
    final Response response2 = target("/valid/headCopy").request().get();
    String ret2 = "{\"errors\":[\"query param cheese may not be null\"]}";
    assertThat(response2.readEntity(String.class)).isEqualTo(ret2);
}

32. ThingTest#testPositionChange()

Project: freedomotic
Source File: ThingTest.java
View license
@Test
public void testPositionChange() {
    init();
    Entity<EnvObject> cmdEntity = Entity.entity(getItem(), getRepresentation());
    final Response response1 = target(getPATH()).request().post(cmdEntity);
    assertEquals("POST response HTTP status code not as expected", Response.Status.CREATED.getStatusCode(), response1.getStatus());
    final Response response = target(getPATH()).path(getUuid(getItem()) + "/move/10/10").request().post(null);
    assertEquals("Move POST response HTTP status code not as expected", Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
    EnvObject objPre = target(getPATH()).path(getUuid(getItem())).request(getRepresentation()).get(getSingleType());
    assertEquals("X position after move", 10, objPre.getRepresentations().get(0).getOffset().getX());
    assertEquals("Y position after move", 10, objPre.getRepresentations().get(0).getOffset().getY());
//  Response resDELETE = target(getPATH()).path(getUuid(getItem())).request(getRepresentation()).delete();
//  assertEquals("DELETE test", Response.Status.OK.getStatusCode(), resDELETE.getStatus());
}

33. AdapterTestStrategy#testBasicAuthErrorHandling()

Project: keycloak
Source File: AdapterTestStrategy.java
View license
/**
     * KEYCLOAK-3016
     * @throws Exception
     */
public void testBasicAuthErrorHandling() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(APP_SERVER_BASE_URL + "/customer-db/");
    Response response = target.request().get();
    Assert.assertEquals(401, response.getStatus());
    response.close();
    // The number of iterations should be HttpClient's connection pool size + 1.
    final int LIMIT = ConnManagerParams.DEFAULT_MAX_TOTAL_CONNECTIONS + 1;
    for (int i = 0; i < LIMIT; i++) {
        System.out.println("Testing Basic Auth with bad credentials " + i);
        response = target.request().header(HttpHeaders.AUTHORIZATION, "Basic dXNlcm5hbWU6cGFzc3dvcmQ=").get();
        Assert.assertEquals(401, response.getStatus());
        response.close();
    }
    client.close();
}

34. AdapterTestStrategy#testBadUser()

Project: keycloak
Source File: AdapterTestStrategy.java
View license
/**
     * KEYCLOAK-518
     * @throws Exception
     */
public void testBadUser() throws Exception {
    Client client = ClientBuilder.newClient();
    UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_URL);
    URI uri = OIDCLoginProtocolService.tokenUrl(builder).build("demo");
    WebTarget target = client.target(uri);
    String header = BasicAuthHelper.createHeader("customer-portal", "password");
    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD).param("username", "[email protected]").param("password", "password");
    Response response = target.request().header(HttpHeaders.AUTHORIZATION, header).post(Entity.form(form));
    Assert.assertEquals(401, response.getStatus());
    response.close();
    client.close();
}

35. AbstractKerberosTest#spnegoNotAvailableTest()

Project: keycloak
Source File: AbstractKerberosTest.java
View license
@Test
public void spnegoNotAvailableTest() throws Exception {
    initHttpClient(false);
    SpnegoAuthenticator.bypassChallengeJavascript = true;
    driver.navigate().to(KERBEROS_APP_URL);
    String kcLoginPageLocation = driver.getCurrentUrl();
    Response response = client.target(kcLoginPageLocation).request().get();
    Assert.assertEquals(401, response.getStatus());
    Assert.assertEquals(KerberosConstants.NEGOTIATE, response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
    String responseText = response.readEntity(String.class);
    responseText.contains("Log in to test");
    response.close();
    SpnegoAuthenticator.bypassChallengeJavascript = false;
}

36. AbstractKerberosTest#spnegoLoginTestImpl()

Project: keycloak
Source File: AbstractKerberosTest.java
View license
protected void spnegoLoginTestImpl() throws Exception {
    KeycloakRule keycloakRule = getKeycloakRule();
    AssertEvents events = getAssertEvents();
    Response spnegoResponse = spnegoLogin("hnelson", "secret");
    Assert.assertEquals(302, spnegoResponse.getStatus());
    events.expectLogin().client("kerberos-app").user(keycloakRule.getUser("test", "hnelson").getId()).detail(Details.REDIRECT_URI, KERBEROS_APP_URL).detail(//.detail(Details.AUTH_METHOD, "spnego")
    Details.USERNAME, "hnelson").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();
}

37. AbstractKerberosTest#spnegoCaseInsensitiveTest()

Project: keycloak
Source File: AbstractKerberosTest.java
View license
// 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(//.detail(Details.AUTH_METHOD, "spnego")
    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();
}

38. JaxrsFilterTest#testSslRequired()

Project: keycloak
Source File: JaxrsFilterTest.java
View license
@Test
public void testSslRequired() {
    keycloakRule.update(new KeycloakRule.KeycloakSetup() {

        @Override
        public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
            Map<String, String> initParams = new TreeMap<String, String>();
            initParams.put(CONFIG_FILE_INIT_PARAM, "classpath:jaxrs-test/jaxrs-keycloak-ssl.json");
            keycloakRule.deployJaxrsApplication("JaxrsSimpleApp", "/jaxrs-simple", JaxrsTestApplication.class, initParams);
        }
    });
    // Retrieve token
    OAuthClient.AccessTokenResponse accessTokenResp = retrieveAccessToken();
    String authHeader = "Bearer " + accessTokenResp.getAccessToken();
    // Fail due to non-https
    Response getResp = client.target(JAXRS_APP_URL).request().header(HttpHeaders.AUTHORIZATION, authHeader).get();
    Assert.assertEquals(getResp.getStatus(), 403);
    getResp.close();
}

39. JaxrsFilterTest#testCxfExample()

Project: keycloak
Source File: JaxrsFilterTest.java
View license
// @Test
public void testCxfExample() {
    //String uri = "http://localhost:9000/customerservice/customers/123";
    String uri = "http://localhost:8080/jax_rs_basic_servlet/services/service1/customerservice/customers/123";
    Response resp = client.target(uri).request().get();
    Assert.assertEquals(resp.getStatus(), 401);
    resp.close();
    // Retrieve token
    OAuthClient.AccessTokenResponse accessTokenResp = retrieveAccessToken();
    String authHeader = "Bearer " + accessTokenResp.getAccessToken();
    String resp2 = client.target(uri).request().header(HttpHeaders.AUTHORIZATION, authHeader).get(String.class);
    System.out.println(resp2);
}

40. AbstractKerberosAdapterTest#spnegoNotAvailableTest()

View license
@Test
public void spnegoNotAvailableTest() throws Exception {
    initHttpClient(false);
    String kcLoginPageLocation = client.target(kerberosPortal.getInjectedUrl().toString()).request().get().getLocation().toString();
    Response response = client.target(kcLoginPageLocation).request().get();
    Assert.assertEquals(401, response.getStatus());
    Assert.assertEquals(KerberosConstants.NEGOTIATE, response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
    String responseText = response.readEntity(String.class);
    responseText.contains("Log in to test");
    response.close();
}

41. AbstractKerberosAdapterTest#spnegoLoginTestImpl()

View license
protected void spnegoLoginTestImpl() throws Exception {
    Response spnegoResponse = spnegoLogin("hnelson", "secret");
    Assert.assertEquals(302, spnegoResponse.getStatus());
    List<UserRepresentation> users = testRealmResource().users().search("hnelson", 0, 1);
    String userId = users.get(0).getId();
    events.expectLogin().client("kerberos-app").user(userId).detail(Details.REDIRECT_URI, kerberosPortal.toString()).detail(//.detail(Details.AUTH_METHOD, "spnego")
    Details.USERNAME, "hnelson").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();
}

42. AbstractKerberosAdapterTest#spnegoCaseInsensitiveTest()

View license
// KEYCLOAK-2102
@Test
public void spnegoCaseInsensitiveTest() throws Exception {
    Response spnegoResponse = spnegoLogin(ldapTestConfiguration.isCaseSensitiveLogin() ? "MyDuke" : "myduke", "theduke");
    Assert.assertEquals(302, spnegoResponse.getStatus());
    List<UserRepresentation> users = testRealmResource().users().search("myduke", 0, 1);
    String userId = users.get(0).getId();
    events.expectLogin().client("kerberos-app").user(userId).detail(Details.REDIRECT_URI, kerberosPortal.toString()).detail(//.detail(Details.AUTH_METHOD, "spnego")
    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();
}

43. AbstractKerberosAdapterTest#spnegoLogin()

View license
protected Response spnegoLogin(String username, String password) {
    kerberosPortal.navigateTo();
    Response res = client.target(kerberosPortal.getInjectedUrl().toString()).request().get();
    String kcLoginPageLocation = res.getLocation().toString();
    if (driver.manage().getCookieNamed("OAuth_Token_Request_State") != null) {
        kcLoginPageLocation = res.getLocation().toString().replaceFirst("state=.*&", "state=" + driver.manage().getCookieNamed("OAuth_Token_Request_State").getValue() + "&");
    }
    // Request for SPNEGO login sent with Resteasy client
    spnegoSchemeFactory.setCredentials(username, password);
    Response response = client.target(kcLoginPageLocation).request().get();
    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;
}

44. AbstractKerberosStandaloneAdapterTest#updateProfileEnabledTest()

View license
@Test
public void updateProfileEnabledTest() throws Exception {
    // Switch updateProfileOnFirstLogin to on
    RealmRepresentation realm = testRealmResource().toRepresentation();
    UserFederationProviderRepresentation kerberosProviderRepresentation = realm.getUserFederationProviders().get(0);
    kerberosProviderRepresentation.getConfig().put(KerberosConstants.UPDATE_PROFILE_FIRST_LOGIN, "true");
    testRealmResource().update(realm);
    // Assert update profile page is displayed
    Response spnegoResponse = spnegoLogin("hnelson", "secret");
    Assert.assertEquals(200, spnegoResponse.getStatus());
    String responseText = spnegoResponse.readEntity(String.class);
    Assert.assertTrue(responseText.contains("You need to update your user profile to activate your account."));
    Assert.assertTrue(responseText.contains("hnelson@" + getConfig().get(KerberosConstants.KERBEROS_REALM).toLowerCase()));
    spnegoResponse.close();
    // Assert user was imported and has required action on him
    assertUser("hnelson", "hnelson@" + getConfig().get(KerberosConstants.KERBEROS_REALM).toLowerCase(), null, null, true);
    // Switch updateProfileOnFirstLogin to off
    kerberosProviderRepresentation = realm.getUserFederationProviders().get(0);
    kerberosProviderRepresentation.getConfig().put(KerberosConstants.UPDATE_PROFILE_FIRST_LOGIN, "false");
    testRealmResource().update(realm);
}

45. AbstractDemoServletsAdapterTest#testBadUser()

View license
@Test
@Ignore
public void testBadUser() {
    Client client = ClientBuilder.newClient();
    URI uri = OIDCLoginProtocolService.tokenUrl(authServerPage.createUriBuilder()).build("demo");
    WebTarget target = client.target(uri);
    String header = BasicAuthHelper.createHeader("customer-portal", "password");
    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD).param("username", "[email protected]").param("password", "password");
    Response response = target.request().header(HttpHeaders.AUTHORIZATION, header).post(Entity.form(form));
    assertEquals(401, response.getStatus());
    response.close();
    client.close();
}

46. AbstractSAMLServletsAdapterTest#salesMetadataTest()

View license
@Test
public void salesMetadataTest() throws Exception {
    Document doc = loadXML(AbstractSAMLServletsAdapterTest.class.getResourceAsStream("/adapter-test/keycloak-saml/sp-metadata.xml"));
    modifyDocElementAttribute(doc, "SingleLogoutService", "Location", "8080", System.getProperty("app.server.http.port", null));
    modifyDocElementAttribute(doc, "AssertionConsumerService", "Location", "8080", System.getProperty("app.server.http.port", null));
    ClientRepresentation clientRep = testRealmResource().convertClientDescription(IOUtil.documentToString(doc));
    String appServerUrl;
    if (Boolean.parseBoolean(System.getProperty("app.server.ssl.required"))) {
        appServerUrl = "https://localhost:" + System.getProperty("app.server.https.port", "8543") + "/";
    } else {
        appServerUrl = "http://localhost:" + System.getProperty("app.server.http.port", "8280") + "/";
    }
    clientRep.setAdminUrl(appServerUrl + "sales-metadata/saml");
    Response response = testRealmResource().clients().create(clientRep);
    assertEquals(201, response.getStatus());
    response.close();
    testSuccessfulAndUnauthorizedLogin(salesMetadataServletPage, testRealmSAMLPostLoginPage);
}

47. AuthenticatorConfigTest#testCreateConfig()

View license
@Test
public void testCreateConfig() {
    AuthenticatorConfigRepresentation cfg = newConfig("foo", IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION, "true");
    // Attempt to create config for non-existent execution
    Response response = authMgmtResource.newExecutionConfig("exec-id-doesnt-exists", cfg);
    Assert.assertEquals(404, response.getStatus());
    response.close();
    // Create config success
    String cfgId = createConfig(executionId, cfg);
    // Assert found
    AuthenticatorConfigRepresentation cfgRep = authMgmtResource.getAuthenticatorConfig(cfgId);
    assertConfig(cfgRep, cfgId, "foo", IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION, "true");
    // Cleanup
    authMgmtResource.removeAuthenticatorConfig(cfgId);
    assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionConfigPath(cfgId));
}

48. FlowTest#addExecutionFlow()

Project: keycloak
Source File: FlowTest.java
View license
@Test
public // KEYCLOAK-2580
void addExecutionFlow() {
    HashMap<String, String> params = new HashMap<>();
    params.put("newName", "parent");
    Response response = authMgmtResource.copy("browser", params);
    Assert.assertEquals(201, response.getStatus());
    response.close();
    assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params);
    params = new HashMap<>();
    params.put("alias", "child");
    params.put("description", "Description");
    params.put("provider", "registration-page-form");
    params.put("type", "basic-flow");
    authMgmtResource.addExecutionFlow("parent", params);
    assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("parent"), params);
}

49. ClientProtocolMapperTest#testCreateSamlProtocolMapper()

View license
@Test
public void testCreateSamlProtocolMapper() {
    //{"protocol":"saml",
    // "config":{"role":"account.view-profile","new.role.name":"new-role-name"},
    // "consentRequired":true,
    // "consentText":"My consent text",
    // "name":"saml-role-name-maper",
    // "protocolMapper":"saml-role-name-mapper"}
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper");
    int totalMappers = samlMappersRsc.getMappers().size();
    int totalSamlMappers = samlMappersRsc.getMappersPerProtocol("saml").size();
    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), rep);
    assertEquals(totalMappers + 1, samlMappersRsc.getMappers().size());
    assertEquals(totalSamlMappers + 1, samlMappersRsc.getMappersPerProtocol("saml").size());
    ProtocolMapperRepresentation created = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, created);
}

50. ClientProtocolMapperTest#testCreateOidcProtocolMapper()

View license
@Test
public void testCreateOidcProtocolMapper() {
    //{"protocol":"openid-connect",
    // "config":{"role":"myrole"},
    // "consentRequired":true,
    // "consentText":"My consent text",
    // "name":"oidc-hardcoded-role-mapper",
    // "protocolMapper":"oidc-hardcoded-role-mapper"}
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper");
    int totalMappers = oidcMappersRsc.getMappers().size();
    int totalOidcMappers = oidcMappersRsc.getMappersPerProtocol("openid-connect").size();
    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(oidcClientId, createdId), rep);
    assertEquals(totalMappers + 1, oidcMappersRsc.getMappers().size());
    assertEquals(totalOidcMappers + 1, oidcMappersRsc.getMappersPerProtocol("openid-connect").size());
    //findByName(samlMappersRsc, "saml-role-name-mapper");
    ProtocolMapperRepresentation created = oidcMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, created);
}

51. ClientProtocolMapperTest#testUpdateSamlMapper()

View license
@Test
public void testUpdateSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper2");
    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), rep);
    rep.getConfig().put("role", "account.manage-account");
    rep.setId(createdId);
    rep.setConsentRequired(false);
    samlMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), rep);
    ProtocolMapperRepresentation updated = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}

52. ClientProtocolMapperTest#testUpdateOidcMapper()

View license
@Test
public void testUpdateOidcMapper() {
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper2");
    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(oidcClientId, createdId), rep);
    rep.getConfig().put("role", "myotherrole");
    rep.setId(createdId);
    rep.setConsentRequired(false);
    oidcMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientProtocolMapperPath(oidcClientId, createdId), rep);
    ProtocolMapperRepresentation updated = oidcMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}

53. ClientProtocolMapperTest#testDeleteSamlMapper()

View license
@Test
public void testDeleteSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper3");
    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), rep);
    samlMappersRsc.delete(createdId);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId));
    try {
        samlMappersRsc.getMapperById(createdId);
        Assert.fail("Not expected to find mapper");
    } catch (NotFoundException nfe) {
    }
}

54. ClientProtocolMapperTest#testDeleteOidcMapper()

View license
@Test
public void testDeleteOidcMapper() {
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper3");
    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(oidcClientId, createdId), rep);
    oidcMappersRsc.delete(createdId);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientProtocolMapperPath(oidcClientId, createdId));
    try {
        oidcMappersRsc.getMapperById(createdId);
        Assert.fail("Not expected to find mapper");
    } catch (NotFoundException nfe) {
    }
}

55. ClientTemplateProtocolMapperTest#test04CreateSamlProtocolMapper()

View license
@Test
public void test04CreateSamlProtocolMapper() {
    //{"protocol":"saml",
    // "config":{"role":"account.view-profile","new.role.name":"new-role-name"},
    // "consentRequired":true,
    // "consentText":"My consent text",
    // "name":"saml-role-name-maper",
    // "protocolMapper":"saml-role-name-mapper"}
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper");
    int totalMappers = samlMappersRsc.getMappers().size();
    int totalSamlMappers = samlMappersRsc.getMappersPerProtocol("saml").size();
    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientTemplateProtocolMapperPath(samlClientTemplateId, createdId), rep);
    assertEquals(totalMappers + 1, samlMappersRsc.getMappers().size());
    assertEquals(totalSamlMappers + 1, samlMappersRsc.getMappersPerProtocol("saml").size());
    ProtocolMapperRepresentation created = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, created);
}

56. ClientTemplateProtocolMapperTest#test05CreateOidcProtocolMapper()

View license
@Test
public void test05CreateOidcProtocolMapper() {
    //{"protocol":"openid-connect",
    // "config":{"role":"myrole"},
    // "consentRequired":true,
    // "consentText":"My consent text",
    // "name":"oidc-hardcoded-role-mapper",
    // "protocolMapper":"oidc-hardcoded-role-mapper"}
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper");
    int totalMappers = oidcMappersRsc.getMappers().size();
    int totalOidcMappers = oidcMappersRsc.getMappersPerProtocol("openid-connect").size();
    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientTemplateProtocolMapperPath(oidcClientTemplateId, createdId), rep);
    assertEquals(totalMappers + 1, oidcMappersRsc.getMappers().size());
    assertEquals(totalOidcMappers + 1, oidcMappersRsc.getMappersPerProtocol("openid-connect").size());
    //findByName(samlMappersRsc, "saml-role-name-mapper");
    ProtocolMapperRepresentation created = oidcMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, created);
}

57. ClientTemplateProtocolMapperTest#test06UpdateSamlMapper()

View license
@Test
public void test06UpdateSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper2");
    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientTemplateProtocolMapperPath(samlClientTemplateId, createdId), rep);
    rep.getConfig().put("role", "account.manage-account");
    rep.setId(createdId);
    rep.setConsentRequired(false);
    samlMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientTemplateProtocolMapperPath(samlClientTemplateId, createdId), rep);
    ProtocolMapperRepresentation updated = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}

58. ClientTemplateProtocolMapperTest#test07UpdateOidcMapper()

View license
@Test
public void test07UpdateOidcMapper() {
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper2");
    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientTemplateProtocolMapperPath(oidcClientTemplateId, createdId), rep);
    rep.getConfig().put("role", "myotherrole");
    rep.setId(createdId);
    rep.setConsentRequired(false);
    oidcMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientTemplateProtocolMapperPath(oidcClientTemplateId, createdId), rep);
    ProtocolMapperRepresentation updated = oidcMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}

59. ClientTemplateProtocolMapperTest#testDeleteSamlMapper()

View license
@Test
public void testDeleteSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper3");
    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientTemplateProtocolMapperPath(samlClientTemplateId, createdId), rep);
    samlMappersRsc.delete(createdId);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientTemplateProtocolMapperPath(samlClientTemplateId, createdId));
    try {
        samlMappersRsc.getMapperById(createdId);
        Assert.fail("Not expected to find mapper");
    } catch (NotFoundException nfe) {
    }
}

60. ClientTemplateProtocolMapperTest#testDeleteOidcMapper()

View license
@Test
public void testDeleteOidcMapper() {
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper3");
    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientTemplateProtocolMapperPath(oidcClientTemplateId, createdId), rep);
    oidcMappersRsc.delete(createdId);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientTemplateProtocolMapperPath(oidcClientTemplateId, createdId));
    try {
        oidcMappersRsc.getMapperById(createdId);
        Assert.fail("Not expected to find mapper");
    } catch (NotFoundException nfe) {
    }
}

61. ClientTemplateProtocolMapperTest#createTemplate()

View license
private String createTemplate(String templateName, String protocol) {
    ClientTemplateRepresentation rep = new ClientTemplateRepresentation();
    rep.setName(templateName);
    rep.setFullScopeAllowed(false);
    rep.setProtocol(protocol);
    Response resp = clientTemplates().create(rep);
    Assert.assertEquals(201, resp.getStatus());
    resp.close();
    String templateId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientTemplateResourcePath(templateId), rep);
    return templateId;
}

62. ClientTest#createClient()

Project: keycloak
Source File: ClientTest.java
View license
private ClientRepresentation createClient() {
    ClientRepresentation rep = new ClientRepresentation();
    rep.setClientId("my-app");
    rep.setDescription("my-app description");
    rep.setEnabled(true);
    Response response = realm.clients().create(rep);
    response.close();
    String id = ApiUtil.getCreatedId(response);
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), rep);
    rep.setId(id);
    return rep;
}

63. ClientTest#createAppClient()

Project: keycloak
Source File: ClientTest.java
View license
private ClientRepresentation createAppClient() {
    String redirectUri = oauth.getRedirectUri().replace("/master/", "/" + REALM_NAME + "/");
    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("test-app");
    client.setAdminUrl(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/app/admin");
    client.setRedirectUris(Collections.singletonList(redirectUri));
    client.setSecret("secret");
    int notBefore = Time.currentTime() - 60;
    client.setNotBefore(notBefore);
    Response response = realm.clients().create(client);
    String id = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), client);
    client.setId(id);
    return client;
}

64. ImpersonationTest#testImpersonateByMasterImpersonator()

Project: keycloak
Source File: ImpersonationTest.java
View license
@Test
public void testImpersonateByMasterImpersonator() {
    Response response = adminClient.realm("master").users().create(UserBuilder.create().username("master-impersonator").build());
    String userId = ApiUtil.getCreatedId(response);
    response.close();
    UserResource user = adminClient.realm("master").users().get(userId);
    user.resetPassword(CredentialBuilder.create().password("password").build());
    ClientResource testRealmClient = ApiUtil.findClientResourceByClientId(adminClient.realm("master"), "test-realm");
    List<RoleRepresentation> roles = new LinkedList<>();
    roles.add(ApiUtil.findClientRoleByName(testRealmClient, AdminRoles.VIEW_USERS).toRepresentation());
    roles.add(ApiUtil.findClientRoleByName(testRealmClient, ImpersonationConstants.IMPERSONATION_ROLE).toRepresentation());
    user.roles().clientLevel(testRealmClient.toRepresentation().getId()).add(roles);
    testSuccessfulImpersonation("master-impersonator", Config.getAdminRealm());
    adminClient.realm("master").users().get(userId).remove();
}

65. PartialImportTest#createClientForClientRoles()

Project: keycloak
Source File: PartialImportTest.java
View license
@Before
public void createClientForClientRoles() {
    ClientRepresentation client = new ClientRepresentation();
    client.setClientId(CLIENT_ROLES_CLIENT);
    client.setName(CLIENT_ROLES_CLIENT);
    client.setRootUrl("foo");
    client.setProtocol("openid-connect");
    Response resp = testRealmResource().clients().create(client);
    // for some reason, findAll() will later fail unless readEntity is called here
    resp.readEntity(String.class);
//testRealmResource().clients().findAll();
}

66. RealmTest#clearUserCache()

Project: keycloak
Source File: RealmTest.java
View license
@Test
public void clearUserCache() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("clearcacheuser");
    Response response = realm.users().create(user);
    String userId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userId), user);
    realm.users().get(userId).toRepresentation();
    assertTrue(testingClient.testing().isCached("users", userId));
    realm.clearUserCache();
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, "clear-user-cache");
    assertFalse(testingClient.testing().isCached("users", userId));
}

67. RealmTest#logoutAll()

Project: keycloak
Source File: RealmTest.java
View license
@Test
public void logoutAll() {
    setupTestAppAndUser();
    Response response = realm.users().create(UserBuilder.create().username("user").build());
    String userId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userId));
    realm.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build());
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResetPasswordPath(userId));
    oauth.doLogin("user", "password");
    GlobalRequestResult globalRequestResult = realm.logoutAll();
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, "logout-all", globalRequestResult);
    assertEquals(1, globalRequestResult.getSuccessRequests().size());
    assertEquals("http://localhost:8180/auth/realms/master/app/admin", globalRequestResult.getSuccessRequests().get(0));
    assertNull(globalRequestResult.getFailedRequests());
    assertNotNull(testingClient.testApp().getAdminLogoutAction());
}

68. UserTest#createDuplicatedUser1()

Project: keycloak
Source File: UserTest.java
View license
@Test
public void createDuplicatedUser1() {
    createUser();
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());
    assertAdminEvents.assertEmpty();
    // Just to show how to retrieve underlying error message
    ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
    Assert.assertEquals("User exists with same username", error.getErrorMessage());
    response.close();
}

69. UserTest#createDuplicatedUser7()

Project: keycloak
Source File: UserTest.java
View license
@Test
public void createDuplicatedUser7() {
    createUser("user1", "[email protected]");
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user2");
    user.setEmail("[email protected]");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());
    response.close();
    assertAdminEvents.assertEmpty();
}

70. LoginTest#testBrowserSecurityHeaders()

Project: keycloak
Source File: LoginTest.java
View license
@Test
public void testBrowserSecurityHeaders() {
    Client client = ClientBuilder.newClient();
    Response response = client.target(oauth.getLoginFormUrl()).request().get();
    Assert.assertEquals(200, response.getStatus());
    for (Map.Entry<String, String> entry : BrowserSecurityHeaders.defaultHeaders.entrySet()) {
        String headerName = BrowserSecurityHeaders.headerAttributeMap.get(entry.getKey());
        String headerValue = response.getHeaderString(headerName);
        Assert.assertNotNull(headerValue);
        Assert.assertEquals(headerValue, entry.getValue());
    }
    response.close();
}

71. UserInfoTest#testSuccessfulUserInfoRequest()

Project: keycloak
Source File: UserInfoTest.java
View license
@Test
public void testSuccessfulUserInfoRequest() throws Exception {
    Client client = ClientBuilder.newClient();
    UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
    URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
    WebTarget grantTarget = client.target(grantUri);
    AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(grantTarget);
    Response response = executeUserInfoRequest(accessTokenResponse.getToken());
    assertEquals(Status.OK.getStatusCode(), response.getStatus());
    UserInfo userInfo = response.readEntity(UserInfo.class);
    response.close();
    assertNotNull(userInfo);
    assertNotNull(userInfo.getSubject());
    assertEquals("[email protected]", userInfo.getEmail());
    assertEquals("[email protected]", userInfo.getPreferredUsername());
    client.close();
}

72. UserInfoTest#testSessionExpired()

Project: keycloak
Source File: UserInfoTest.java
View license
@Test
public void testSessionExpired() throws Exception {
    Client client = ClientBuilder.newClient();
    UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
    URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
    WebTarget grantTarget = client.target(grantUri);
    AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(grantTarget);
    testingClient.testing().removeUserSessions("test");
    Response response = executeUserInfoRequest(accessTokenResponse.getToken());
    assertEquals(Status.FORBIDDEN.getStatusCode(), response.getStatus());
    response.close();
    client.close();
}

73. UserInfoTest#executeGrantAccessTokenRequest()

Project: keycloak
Source File: UserInfoTest.java
View license
private AccessTokenResponse executeGrantAccessTokenRequest(WebTarget grantTarget) {
    String header = BasicAuthHelper.createHeader("test-app", "password");
    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD).param("username", "[email protected]").param("password", "password");
    Response response = grantTarget.request().header(HttpHeaders.AUTHORIZATION, header).post(Entity.form(form));
    assertEquals(200, response.getStatus());
    AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class);
    response.close();
    return accessTokenResponse;
}

74. ITQueryApiTests#testDeleteOnInMemoryResult()

Project: lens
Source File: ITQueryApiTests.java
View license
//LENS-928
@Test
public void testDeleteOnInMemoryResult() throws Exception {
    sHelper.setAndValidateParam(LensConfConstants.QUERY_PERSISTENT_RESULT_SET, "false");
    sHelper.setAndValidateParam(LensConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, "false");
    sHelper.setAndValidateParam("lens.query.enable.mail.notify", "false");
    MapBuilder query = new MapBuilder("sessionid", sessionHandleString, "fromindex", "0", "fetchsize", "100");
    QueryHandle queryHandle = (QueryHandle) qHelper.executeQuery(QueryInventory.JDBC_DIM_QUERY).getData();
    LensQuery lensQuery = qHelper.waitForCompletion(queryHandle);
    Assert.assertEquals(lensQuery.getStatus().getStatus(), QueryStatus.Status.SUCCESSFUL, "Query did not succeed");
    Response response = qHelper.exec("get", QueryURL.QUERY_URL + "/" + queryHandle.toString() + "/resultset", servLens, null, query);
    AssertUtil.assertSucceededResponse(response);
    Thread.sleep(20000);
    Response response1 = qHelper.exec("delete", QueryURL.QUERY_URL + "/" + queryHandle.toString() + "/resultset", servLens, null, query);
    AssertUtil.assertSucceededResponse(response1);
}

75. SessionTests#testServerConfExposureInSession()

Project: lens
Source File: SessionTests.java
View license
@Test(enabled = true)
public void testServerConfExposureInSession() throws Exception {
    // conf : lens-site.xml
    MapBuilder query1 = new MapBuilder("sessionid", sessionHandleString, "key", LensConfConstants.SERVER_DB_JDBC_PASS);
    Response response1 = lens.sendQuery("get", SessionURL.SESSION_PARAMS_URL, query1);
    Assert.assertEquals(response1.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
    //Driver conf : jdbc-driver.xml
    MapBuilder query2 = new MapBuilder("sessionid", sessionHandleString, "key", "lens.driver.jdbc.db.user");
    Response response2 = lens.sendQuery("get", SessionURL.SESSION_PARAMS_URL, query2);
    Assert.assertEquals(response2.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
}

76. SignedServiceTest#testVerification()

View license
@Test
public void testVerification() {
    // Keys repository
    DosetaKeyRepository repository = new DosetaKeyRepository();
    repository.setKeyStorePath("demo.jks");
    repository.setKeyStorePassword("changeit");
    repository.start();
    // Building the client
    ResteasyClient client = new ResteasyClientBuilder().build();
    Verifier verifier = new Verifier();
    Verification verification = verifier.addNew();
    verification.setRepository(repository);
    WebTarget target = client.target("http://localhost:8080/signatures-1.0/signed");
    Invocation.Builder request = target.request();
    request.property(Verifier.class.getName(), verifier);
    // Invocation to Restful web service
    Response response = request.post(Entity.text("Rene"));
    // Status 200 OK
    Assert.assertEquals(200, response.getStatus());
    System.out.println(response.readEntity(String.class));
    response.close();
    client.close();
}

77. ModelResourceTest#deploy()

Project: openscoring
Source File: ModelResourceTest.java
View license
private ModelResponse deploy(String id) throws IOException {
    Response response;
    try (InputStream is = openPMML(id)) {
        Entity<InputStream> entity = Entity.entity(is, MediaType.APPLICATION_XML);
        response = target("model/" + id).request(MediaType.APPLICATION_JSON).put(entity);
    }
    assertEquals(201, response.getStatus());
    return response.readEntity(ModelResponse.class);
}

78. ModelResourceTest#deployForm()

Project: openscoring
Source File: ModelResourceTest.java
View license
private ModelResponse deployForm(String id) throws IOException {
    Response response;
    try (InputStream is = openPMML(id)) {
        FormDataMultiPart formData = new FormDataMultiPart();
        formData.field("id", id);
        formData.bodyPart(new FormDataBodyPart("pmml", is, MediaType.APPLICATION_XML_TYPE));
        Entity<FormDataMultiPart> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);
        response = target("model").request(MediaType.APPLICATION_JSON).post(entity);
        formData.close();
    }
    assertEquals(201, response.getStatus());
    URI location = response.getLocation();
    assertEquals("/model/" + id, location.getPath());
    return response.readEntity(ModelResponse.class);
}

79. TestResteasy1141#test1()

Project: Resteasy
Source File: TestResteasy1141.java
View license
@Test
public void test1() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget put = client.target("http://127.0.0.1:9090/resteasy1141/test/42?foo=xyz");
    Form form = new Form().param("formParam", "Weinan Li");
    Response response = put.request().put(Entity.form(form));
    response.close();
    WebTarget get = client.target("http://127.0.0.1:9090/resteasy1141/test");
    assertEquals("Weinan Li", get.request().get().readEntity(String.class));
}

80. HeadContentLengthTest#testHeadContentLength()

Project: Resteasy
Source File: HeadContentLengthTest.java
View license
@Test
public void testHeadContentLength() {
    Client client = ClientBuilder.newClient();
    Builder builder = client.target("http://localhost:8080:/HeadContentLengthTest/headcontentlength/simpleresource").request();
    builder.accept(MediaType.TEXT_PLAIN_TYPE);
    Response getResponse = builder.get();
    String responseBody = getResponse.readEntity(String.class);
    Assert.assertEquals("hello", responseBody);
    int getResponseLength = getResponse.getLength();
    Assert.assertEquals(5, getResponseLength);
    Response headResponse = builder.head();
    int headResponseLength = headResponse.getLength();
    Assert.assertEquals(getResponseLength, headResponseLength);
}

81. TestResteasy1141#test1()

Project: Resteasy
Source File: TestResteasy1141.java
View license
@Test
public void test1() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget put = client.target("http://127.0.0.1:8080/resteasy1141/test/42?foo=xyz");
    Form form = new Form().param("formParam", "Weinan Li");
    Response response = put.request().put(Entity.form(form));
    response.close();
    WebTarget get = client.target("http://127.0.0.1:8080/resteasy1141/test");
    assertEquals("Weinan Li", get.request().get().readEntity(String.class));
}

82. TestResteasy1223#testGet()

Project: Resteasy
Source File: TestResteasy1223.java
View license
@Test
public void testGet() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget get = client.target(TEST_URI);
    Response response = get.request().get();
    assertEquals(200, response.getStatus());
    assertEquals("text/x-yaml", response.getHeaders().getFirst("Content-Type"));
    String s = response.readEntity(String.class);
    MyObject o1 = YamlResource.createMyObject();
    String s1 = new Yaml().dump(o1);
    Assert.assertEquals(s1, s);
    response.close();
}

83. TestResteasy1223#testPost()

Project: Resteasy
Source File: TestResteasy1223.java
View license
@Test
public void testPost() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget post = client.target(TEST_URI);
    MyObject o1 = YamlResource.createMyObject();
    String s1 = new Yaml().dump(o1);
    Response response = post.request().post(Entity.entity(s1, "text/x-yaml"));
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("text/x-yaml", response.getHeaders().getFirst("Content-Type"));
    Assert.assertEquals(s1, response.readEntity(String.class));
    response.close();
}

84. CustomerResourceTest#testCustomerResource()

Project: Resteasy
Source File: CustomerResourceTest.java
View license
@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 Created Customer **");
    response = client.target(location).request().get();
    CacheControl cc = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL));
    System.out.println("Max age: " + cc.getMaxAge());
}

85. CustomerResourceTest#testCustomerResource()

Project: Resteasy
Source File: CustomerResourceTest.java
View license
@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 Created Customer **");
    response = client.target(location).request().get();
    String md5 = response.getHeaderString("Content-MD5");
    System.out.println("Content-MD5: " + md5);
}

86. JaxrsAsyncTest#testInjectionFailure()

Project: Resteasy
Source File: JaxrsAsyncTest.java
View license
@Test
public void testInjectionFailure() throws Exception {
    System.out.println("***INJECTION FAILURE***");
    long start = System.currentTimeMillis();
    Client client = ClientBuilder.newClient();
    Response response = client.target("http://localhost:8080/jaxrs/injection-failure/abcd").request().get();
    // exception mapper from another test overrides 503
    Assert.assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
    Assert.assertTrue(response.readEntity(String.class).contains(NotFoundException.class.getName()));
    long end = System.currentTimeMillis() - start;
    // should take less than 1 second
    Assert.assertTrue(end < 1000);
    response.close();
    client.close();
}

87. JaxrsAsyncTest#testMethodFailure()

Project: Resteasy
Source File: JaxrsAsyncTest.java
View license
@Test
public void testMethodFailure() throws Exception {
    System.out.println("***method FAILURE***");
    long start = System.currentTimeMillis();
    Client client = ClientBuilder.newClient();
    Response response = client.target("http://localhost:8080/jaxrs/method-failure").request().get();
    // exception mapper from another test overrides 503
    Assert.assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
    Assert.assertTrue(response.readEntity(String.class).contains(ForbiddenException.class.getName()));
    long end = System.currentTimeMillis() - start;
    // should take less than 1 second
    Assert.assertTrue(end < 1000);
    response.close();
    client.close();
}

88. JaxrsAsyncTest#testAsync()

Project: Resteasy
Source File: JaxrsAsyncTest.java
View license
@Test
public void testAsync() throws Exception {
    Client client = ClientBuilder.newClient();
    long start = System.currentTimeMillis();
    Response response = client.target("http://localhost:8080/jaxrs").request().get();
    long end = System.currentTimeMillis() - start;
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("hello", response.readEntity(String.class));
    // should take less than 1 second
    Assert.assertTrue(end < 1000);
    response.close();
    client.close();
}

89. JaxrsAsyncTest#testResumeObject()

Project: Resteasy
Source File: JaxrsAsyncTest.java
View license
@Test
public void testResumeObject() throws Exception {
    Client client = ClientBuilder.newClient();
    client.register(JAXBXmlRootElementProvider.class);
    long start = System.currentTimeMillis();
    Response response = client.target("http://localhost:8080/jaxrs/resume/object").request().get();
    long end = System.currentTimeMillis() - start;
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bill", response.readEntity(XmlData.class).getName());
    // should take less than 1 second
    Assert.assertTrue(end < 1000);
    response.close();
    client.close();
}

90. JaxrsAsyncTest#testResumeObjectThread()

Project: Resteasy
Source File: JaxrsAsyncTest.java
View license
@Test
public void testResumeObjectThread() throws Exception {
    Client client = ClientBuilder.newClient();
    client.register(JAXBXmlRootElementProvider.class);
    long start = System.currentTimeMillis();
    Response response = client.target("http://localhost:8080/jaxrs/resume/object/thread").request().get();
    long end = System.currentTimeMillis() - start;
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bill", response.readEntity(XmlData.class).getName());
    // should take less than 1 second
    Assert.assertTrue(end < 1000);
    response.close();
    client.close();
}

91. JacksonTest#testJacksonJsonp()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testJacksonJsonp() throws Exception {
    jsonpInterceptor.setWrapInTryCatch(false);
    WebTarget target = client.target(generateURL("/products/333?callback=foo"));
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println(entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("foo({\"name\":\"Iphone\",\"id\":333})", entity);
    response.close();
}

92. JacksonTest#testJacksonJsonpWrapInTryCatch()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testJacksonJsonpWrapInTryCatch() throws Exception {
    jsonpInterceptor.setWrapInTryCatch(true);
    WebTarget target = client.target(generateURL("/products/333?callback=foo"));
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println(entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("try{foo({\"name\":\"Iphone\",\"id\":333})}catch(e){}", entity);
    response.close();
}

93. JacksonTest#testFormattedJacksonString()

Project: Resteasy
Source File: JacksonTest.java
View license
@Test
public void testFormattedJacksonString() throws Exception {
    WebTarget target = client.target(generateURL("/products/formatted/333"));
    Response response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println(entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(entity.contains("\n"));
    /* Formatting is dependent on OS \r\n vs. \n so don't test it this way
        Assert.assertEquals(("{\r\n" +
                "  \"name\" : \"Iphone\",\r\n" +
                "  \"id\" : 333\r\n" +
                "}"), entity);
                */
    response.close();
}

94. CharSetTest#testCase()

Project: Resteasy
Source File: CharSetTest.java
View license
@Test
public void testCase() throws Exception {
    ResteasyWebTarget target = client.target(TestPortProvider.generateURL("/test"));
    Customer cust = new Customer();
    String name = "billé";
    System.out.println("client name: " + name);
    System.out.println("bytes string: " + new String(name.getBytes("UTF-8"), "UTF-8"));
    cust.setName(name);
    Response response = target.request().post(Entity.xml(cust));
    response.close();
}

95. CollectionTest2Test#testNakedArray()

Project: Resteasy
Source File: CollectionTest2Test.java
View license
@Test
public void testNakedArray() throws Exception {
    String xml = "<resteasy:collection xmlns:resteasy=\"http://jboss.org/resteasy\">" + "<foo test=\"hello\"/></resteasy:collection>";
    ResteasyWebTarget target = client.target(generateURL("/array"));
    Response response = target.request().post(Entity.xml(xml));
    List<Foo> list = response.readEntity(new GenericType<List<Foo>>() {
    });
    Assert.assertEquals(1, list.size());
    Assert.assertEquals(list.get(0).getTest(), "hello");
    response.close();
}

96. CollectionTest2Test#testList()

Project: Resteasy
Source File: CollectionTest2Test.java
View license
@Test
public void testList() throws Exception {
    String xml = "<list>" + "<foo test=\"hello\"/></list>";
    ResteasyWebTarget target = client.target(generateURL("/list"));
    Response response = target.request().post(Entity.xml(xml));
    Foo[] list = response.readEntity(new GenericType<Foo[]>() {
    });
    Assert.assertEquals(1, list.length);
    Assert.assertEquals(list[0].getTest(), "hello");
    response.close();
}

97. CollectionTest2Test#testNamespacedNakedArray()

Project: Resteasy
Source File: CollectionTest2Test.java
View license
@Test
public void testNamespacedNakedArray() throws Exception {
    String xml = "<collection xmlns:foo=\"http://foo.com\">" + "<foo:foo test=\"hello\"/></collection>";
    ResteasyWebTarget target = client.target(generateURL("/namespaced/array"));
    Response response = target.request().post(Entity.xml(xml));
    List<NamespacedFoo> list = response.readEntity(new GenericType<List<NamespacedFoo>>() {
    });
    Assert.assertEquals(1, list.size());
    Assert.assertEquals(list.get(0).getTest(), "hello");
    response.close();
}

98. CollectionTest2Test#testNamespacedList()

Project: Resteasy
Source File: CollectionTest2Test.java
View license
@Test
public void testNamespacedList() throws Exception {
    String xml = "<list xmlns:foo=\"http://foo.com\">" + "<foo:foo test=\"hello\"/></list>";
    ResteasyWebTarget target = client.target(generateURL("/namespaced/list"));
    Response response = target.request().post(Entity.xml(xml));
    NamespacedFoo[] list = response.readEntity(new GenericType<NamespacedFoo[]>() {
    });
    Assert.assertEquals(1, list.length);
    Assert.assertEquals(list[0].getTest(), "hello");
    response.close();
}

99. CollectionTest2Test#testBadList()

Project: Resteasy
Source File: CollectionTest2Test.java
View license
@Test
public void testBadList() throws Exception {
    String xml = "<bad-list>" + "<foo test=\"hello\"/></bad-list>";
    ResteasyWebTarget target = client.target(generateURL("/list"));
    Response response = target.request().post(Entity.xml(xml));
    Assert.assertEquals(400, response.getStatus());
    response.close();
}

100. StreamResetTest#testJBEAP2138WithoutBufferedEntity()

Project: Resteasy
Source File: StreamResetTest.java
View license
@Test(expected = IllegalStateException.class)
public void testJBEAP2138WithoutBufferedEntity() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(TestPortProvider.generateURL("/test"));
    Response response = target.request().get();
    try {
        response.readEntity(Place.class);
    } catch (Exception e) {
    }
    response.readEntity(Person.class);
}