Java Code Examples for javax.ws.rs.core.Response#close()

The following examples show how to use javax.ws.rs.core.Response#close() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void testSystemPropertiesMatch() {
    Response invResponse = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
    Response sysResponse = this.getResponse(baseUrl + SYSTEM_PROPERTIES);

    this.assertResponse(baseUrl, invResponse);
    this.assertResponse(baseUrl, sysResponse);

    JsonObject jsonFromInventory = (JsonObject) invResponse.readEntity(JsonObject.class).getJsonArray("systems")
            .getJsonObject(0).get("properties");

    JsonObject jsonFromSystem = sysResponse.readEntity(JsonObject.class);

    String osNameFromInventory = jsonFromInventory.getString("os.name");
    String osNameFromSystem = jsonFromSystem.getString("os.name");
    this.assertProperty("os.name", "localhost", osNameFromSystem, osNameFromInventory);

    String userNameFromInventory = jsonFromInventory.getString("user.name");
    String userNameFromSystem = jsonFromSystem.getString("user.name");
    this.assertProperty("user.name", "localhost", userNameFromSystem, userNameFromInventory);

    invResponse.close();
    sysResponse.close();
}
 
Example 2
Source Project: hibernate-demos   File: PersonsIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void createAndGetPerson(@ArquillianResteasyResource( "hike-manager/persons" ) ResteasyWebTarget webTarget) throws Exception {
	// Create a person
	Invocation createPerson = invocationBuilder( webTarget ).buildPost(
			jsonEntity( "{ 'firstName' : 'Saundra', 'lastName' : 'Smith' } " )
	);

	Response response = createPerson.invoke();
	assertEquals( HttpStatus.SC_CREATED, response.getStatus() );

	String location = response.getHeaderString( "Location");
	assertNotNull( location );
	response.close();

	// Get the person
	Invocation getPerson = invocationBuilder( webTarget, "/" + getId( location ) ).buildGet();
	response = getPerson.invoke();
	assertEquals( HttpStatus.SC_OK, response.getStatus() );

	JSONAssert.assertEquals(
			"{ 'firstName' : 'Saundra', 'lastName' : 'Smith' }",
			response.readEntity( String.class ),
			false
	);
	response.close();
}
 
Example 3
@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());
}
 
Example 4
Source Project: mrgeo   File: GetMapTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Category(IntegrationTest.class)
public void testGetMapTifRectangularTileSize() throws Exception
{
  String contentType = "image/tiff";

  Response response = target("wms")
      .queryParam("SERVICE", "WMS")
      .queryParam("REQUEST", "getmap")
      .queryParam("LAYERS", "IslandsElevation-v2")
      .queryParam("FORMAT", contentType)
      .queryParam("BBOX", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("WIDTH", "700")
      .queryParam("HEIGHT", "300")
      .request().get();

  processImageResponse(response, contentType, "tif", true);
  response.close();
}
 
Example 5
Source Project: microprofile-lra   File: TckTests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Service A - Timeout 500 ms
 * Service B - Type.MANDATORY
 *
 * Service A calls Service B after it has waited 1 sec.
 * Service A returns http Status from the call to Service B.
 *
 * test calls A and verifies if return is status 412 (precondition failed)
 * or 410 (gone) since LRA is not active when Service B endpoint is called.
 */
@Test
public void timeLimitWithPreConditionFailed() {
    WebTarget resourcePath = tckSuiteTarget.path(LRA_RESOURCE_PATH).path(TIME_LIMIT_HALF_SEC);
    Response response = resourcePath
            .request()
            .get();

    // verify that a 412 response code was generated
    assertTrue("Expected 412 or 410 response",
            response.getStatus() == Response.Status.PRECONDITION_FAILED.getStatusCode() ||
                    response.getStatus() == Response.Status.GONE.getStatusCode()
            );

    response.close();
}
 
Example 6
Source Project: mrgeo   File: WcsGetCoverageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Category(IntegrationTest.class)
public void testGetMapLowerCaseParams() throws Exception
{
  String contentType = "image/tiff";
  Response response = target("wcs")
      .queryParam("service", "WCS")
      .queryParam("version", "1.1.0")
      .queryParam("request", "getcoverage")
      .queryParam("identifier", "IslandsElevation-v2")
      .queryParam("format", contentType)
      .queryParam("boundingbox", ISLANDS_ELEVATION_V2_IN_BOUNDS_SINGLE_SOURCE_TILE)
      .queryParam("width", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .queryParam("height", MrGeoConstants.MRGEO_MRS_TILESIZE_DEFAULT)
      .request().get();

  processImageResponse(response, contentType, "png");
  response.close();
}
 
Example 7
@Test
public void test08DeleteSamlMapper() {
    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, ResourceType.PROTOCOL_MAPPER);

    samlMappersRsc.delete(createdId);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), ResourceType.PROTOCOL_MAPPER);

    try {
        samlMappersRsc.getMapperById(createdId);
        Assert.fail("Not expected to find mapper");
    } catch (NotFoundException nfe) {
        // Expected
    }
}
 
Example 8
@SuppressWarnings("unchecked")
public <T> T testEndpoint(String endpoint, Class<?> entity) throws Exception {
       String url = getEndPoint(endpoint);
       System.out.println("Testing " + url);
       Response response = null;
       try {
        response = sendRequest(url, "GET");
        int responseCode = response.getStatus();
        assertTrue("Incorrect response code for " + url + ": " + responseCode,
                   responseCode == 200);
        String json = response.readEntity(String.class);
        ObjectMapper mapper = new ObjectMapper();
       return (T) mapper.readValue(json, entity);       	
       } finally {
       	if(response != null) {
       		response.close();
       	}
       }
   }
 
Example 9
public void killContainer(String id) {
    Response response = getServiceEndPoint()
            .path(id)
            .path("/kill")
            .request()
            .method(HttpMethod.POST);

    Response.StatusType statusInfo = response.getStatusInfo();
    response.close();

    checkContainerTargetingResponse(id, statusInfo);
}
 
Example 10
private String getUserAuthToken(String resolvedUrl) throws StageException {
  // 1. Login to DPM to get user auth token
  Response response = null;
  try {
    String baseUrl;
    URL url = new URL(resolvedUrl);
    if(url.getPort() == -1){ // port is not
      baseUrl = url.getProtocol() + "://" + url.getHost() + "/";
    } else {
      baseUrl =  url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + "/";
    }

    if (!resolveUrlToTokenMap.containsKey(baseUrl)) {
      Map<String, String> loginJson = new HashMap<>();
      loginJson.put("userName", conf.client.basicAuth.username.get());
      loginJson.put("password", conf.client.basicAuth.password.get());
      response = ClientBuilder.newClient()
          .target(baseUrl + "security/public-rest/v1/authentication/login")
          .register(new CsrfProtectionFilter("CSRF"))
          .request()
          .post(Entity.json(loginJson));
      if (response.getStatus() != Response.Status.OK.getStatusCode()) {
        String reason = response.getStatusInfo().getReasonPhrase();
        String respString = response.readEntity(String.class);
        final String errorMsg = reason + " : " + respString;
        LOG.warn(Errors.HTTP_01.getMessage(), response.getStatus(), errorMsg);
      } else {
        String userAuthToken = response.getHeaderString(X_USER_AUTH_TOKEN);
        resolveUrlToTokenMap.put(baseUrl, userAuthToken);
      }
    }
    return resolveUrlToTokenMap.get(baseUrl);
  } catch (Exception e) {
    throw new StageException(ControlHubApiErrors.CONTROL_HUB_API_01, e.getMessage(), e);
  } finally {
    if (response != null) {
      response.close();
    }
  }
}
 
Example 11
Source Project: keycloak   File: GroupTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void groupMembership() {
    RealmResource realm = adminClient.realms().realm("test");

    GroupRepresentation group = new GroupRepresentation();
    group.setName("group");
    String groupId = createGroup(realm, group).getId();

    Response response = realm.users().create(UserBuilder.create().username("user-a").build());
    String userAId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userResourcePath(userAId), ResourceType.USER);

    response = realm.users().create(UserBuilder.create().username("user-b").build());
    String userBId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userResourcePath(userBId), ResourceType.USER);

    realm.users().get(userAId).joinGroup(groupId);
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);

    List<UserRepresentation> members = realm.groups().group(groupId).members(0, 10);
    assertNames(members, "user-a");

    realm.users().get(userBId).joinGroup(groupId);
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userGroupPath(userBId, groupId), group, ResourceType.GROUP_MEMBERSHIP);

    members = realm.groups().group(groupId).members(0, 10);
    assertNames(members, "user-a", "user-b");

    realm.users().get(userAId).leaveGroup(groupId);
    assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);

    members = realm.groups().group(groupId).members(0, 10);
    assertNames(members, "user-b");
}
 
Example 12
private void processImageResponse(final Response response, final String extension, boolean hasgdal2)
    throws IOException
{
  try
  {
    Assert.assertEquals("Bad response code", Status.OK.getStatusCode(), response.getStatus());

    if (GEN_BASELINE_DATA_ONLY)
    {
      final String outputPath =
          baselineInput + testname.getMethodName() + "." +
              extension;
      log.info("Generating baseline image: " + outputPath);
      ImageTestUtils.writeBaselineImage(response, outputPath, hasgdal2);
    }
    else
    {
      final String baselineImageFile =
          baselineInput + testname.getMethodName() + "." +
              extension;
      log.info("Comparing result to baseline image " + baselineImageFile + " ...");
      ImageTestUtils.outputImageMatchesBaseline(response, baselineImageFile, hasgdal2);
    }
  }
  finally
  {
    if (response != null)
    {
      response.close();
    }
  }
}
 
Example 13
public void testEmptyInventory() {
    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
    this.assertResponse(baseUrl, response);

    JsonObject obj = response.readEntity(JsonObject.class);

    int expected = 0;
    int actual = obj.getInt("total");
    assertEquals("The inventory should be empty on application start but it wasn't", expected, actual);

    response.close();
}
 
Example 14
Source Project: dubbox-hystrix   File: RestClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void getUser(String url) {
    System.out.println("Getting user via " + url);
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().get();
    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 15
@Test
public void testTechSelectorInvalidTechType() throws Exception {
    String endpoint = "/start/api/v1/data?tech=ABC123&deploy=local";
    Response response = callEndpoint(endpoint);
    int status = response.getStatus();
    response.close();
    assertTrue("Response incorrect, response status was " + status, status == Response.Status.BAD_REQUEST.getStatusCode());
}
 
Example 16
Source Project: keycloak   File: ConcurrencyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(int threadIndex, Keycloak keycloak, RealmResource realm) throws Throwable {
    String name = "c-" + clientIndex.getAndIncrement();
    ClientRepresentation c = new ClientRepresentation();
    c.setClientId(name);
    final ClientsResource clients = realm.clients();

    Response response = clients.create(c);
    String id = ApiUtil.getCreatedId(response);
    response.close();
    final ClientResource client = clients.get(id);

    c = client.toRepresentation();
    assertNotNull(c);
    assertTrue("Client " + name + " not found in client list",
      clients.findAll().stream()
        .map(ClientRepresentation::getClientId)
        .filter(Objects::nonNull)
        .anyMatch(name::equals));

    client.remove();
    try {
        client.toRepresentation();
        fail("Client " + name + " should not be found.  Should throw a 404");
    } catch (NotFoundException e) {

    }

    assertFalse("Client " + name + " should now not present in client list",
      clients.findAll().stream()
        .map(ClientRepresentation::getClientId)
        .filter(Objects::nonNull)
        .anyMatch(name::equals));
}
 
Example 17
Source Project: rapid   File: TestContainerList.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldListAllContainers() {
    final Response response = getResponse(target("containers").path("json").queryParam("all", true));
    assertEquals(OK.getStatusCode(), response.getStatus());
    final JsonArray responseContent = response.readEntity(JsonArray.class);
    int expected = 1;
    assertThat(expected, is(responseContent.size()));
    response.close();
}
 
Example 18
Source Project: datacollector   File: SchAdmin.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Enable Control Hub on this Data Collector.
 */
public static void enableDPM(DPMInfoJson dpmInfo, Context context) throws IOException {
  Utils.checkNotNull(dpmInfo, "DPMInfo");

  String dpmBaseURL = normalizeDpmBaseURL(dpmInfo.getBaseURL());

  // Since we support enabling/Disabling DPM, first check if token already exists for the given DPM URL.
  // If token exists skip first 3 steps
  String currentDPMBaseURL = context.configuration.get(RemoteSSOService.DPM_BASE_URL_CONFIG, "");
  String currentAppAuthToken = context.configuration.get(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, "").trim();
  String componentType = context.configuration.get(
      RuntimeInfo.DPM_COMPONENT_TYPE_CONFIG,
      RuntimeInfo.DC_COMPONENT_TYPE
  ).trim();
  if (!currentDPMBaseURL.equals(dpmBaseURL) ||  currentAppAuthToken.length() == 0) {
    // 1. Login to DPM to get user auth token
    String userAuthToken = retrieveUserToken(dpmBaseURL, dpmInfo.getUserID(), dpmInfo.getUserPassword());
    String appAuthToken;

    // If component type is not Data Collector, make sure Control Hub Instance supports the requested component type
    if (!componentType.equals(RuntimeInfo.DC_COMPONENT_TYPE) &&
        !isValidComponentType(dpmBaseURL, userAuthToken, componentType)) {
      throw new RuntimeException(Utils.format(
          "Control Hub Instance: {} doesn't support component type: {}.",
          dpmBaseURL,
          componentType
      ));
    }

    // 2. Create Data Collector application token
    Response response = null;
    try {
      Map<String, Object> newComponentJson = new HashMap<>();
      newComponentJson.put("organization", dpmInfo.getOrganization());
      newComponentJson.put("componentType", componentType);
      newComponentJson.put("numberOfComponents", 1);
      newComponentJson.put("active", true);
      response = ClientBuilder.newClient()
          .target(dpmBaseURL + "/security/rest/v1/organization/" + dpmInfo.getOrganization() + "/components")
          .register(new CsrfProtectionFilter("CSRF"))
          .request()
          .header(SSOConstants.X_USER_AUTH_TOKEN, userAuthToken)
          .put(Entity.json(newComponentJson));
      if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
        throw new RuntimeException(Utils.format("DPM Create Application Token failed, status code '{}': {}",
            response.getStatus(),
            response.readEntity(String.class)
        ));
      }

      List<Map<String, Object>> newComponent = response.readEntity(new GenericType<List<Map<String,Object>>>() {});
      if (newComponent.size() > 0) {
        appAuthToken = (String) newComponent.get(0).get("fullAuthToken");
      } else {
        throw new RuntimeException("DPM Create Application Token failed: No token data from DPM Server.");
      }

    } finally {
      if (response != null) {
        response.close();
      }
      // Logout from DPM
      logout(dpmBaseURL, userAuthToken);
    }

    // 3. Update App Token file
    updateTokenFile(context, appAuthToken);
  }

  // 4. Update dpm.properties file
  updateDpmProperties(context, dpmBaseURL, dpmInfo.getLabels(), true);
}
 
Example 19
Source Project: datacollector   File: HttpTarget.java    License: Apache License 2.0 4 votes vote down vote up
private void sendUpdate(List<SDCMetricsJson> sdcMetricsJsonList) throws StageException {
  int delaySecs = 1;
  int attempts = 0;
  while (attempts < retryAttempts || retryAttempts == -1) {
    if (attempts > 0) {
      delaySecs = delaySecs * 2;
      delaySecs = Math.min(delaySecs, 60);
      LOG.warn("Post attempt '{}', waiting for '{}' seconds before retrying ...",
        attempts, delaySecs);
      StatsUtil.sleep(delaySecs);
    }
    attempts++;
    Response response = null;
    try {
      response = target.request()
        .header(SSOConstants.X_REST_CALL, SSOConstants.SDC_COMPONENT_NAME)
        .header(SSOConstants.X_APP_AUTH_TOKEN, sdcAuthToken.replaceAll("(\\r|\\n)", ""))
        .header(SSOConstants.X_APP_COMPONENT_ID, sdcId)
        .post(
          Entity.json(
            sdcMetricsJsonList
          )
        );
      if (response.getStatus() == HttpURLConnection.HTTP_OK) {
        return;
      } else if (response.getStatus() == HttpURLConnection.HTTP_UNAVAILABLE) {
        LOG.warn("Error writing to time-series app: DPM unavailable");
        // retry
      } else if (response.getStatus() == HttpURLConnection.HTTP_FORBIDDEN) {
        // no retry in this case
        String errorResponseMessage = response.readEntity(String.class);
        LOG.error(Utils.format(Errors.HTTP_02.getMessage(), errorResponseMessage));
        throw new StageException(Errors.HTTP_02, errorResponseMessage);
      } else {
        String responseMessage = response.readEntity(String.class);
        LOG.error(Utils.format(Errors.HTTP_02.getMessage(), responseMessage));
        //retry
      }
    } catch (Exception ex) {
      LOG.error(Utils.format(Errors.HTTP_02.getMessage(), ex.toString(), ex));
      // retry
    } finally {
      if (response != null) {
        response.close();
      }
    }
  }
  // no success after retry
  throw new StageException(Errors.HTTP_03, retryAttempts);
}
 
Example 20
Source Project: keycloak   File: FlowOverrideTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testDirectGrantHttpChallengeOTP() {
    UserRepresentation user = adminClient.realm("test").users().search("[email protected]").get(0);
    UserRepresentation userUpdate = UserBuilder.edit(user).totpSecret("totpSecret").otpEnabled().build();
    adminClient.realm("test").users().get(user.getId()).update(userUpdate);

    CredentialRepresentation totpCredential = adminClient.realm("test").users()
            .get(user.getId()).credentials().stream().filter(c -> OTPCredentialModel.TYPE.equals(c.getType())).findFirst().get();

    setupBruteForce();

    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
    form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE_OTP);

    // correct password + totp
    String totpCode = totp.generateTOTP("totpSecret");
    Response response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password" + totpCode))
            .post(Entity.form(form));
    assertEquals(200, response.getStatus());
    response.close();

    // correct password + wrong totp 2x
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password123456"))
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password123456"))
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());

    // correct password + totp but user is temporarily locked
    totpCode = totp.generateTOTP("totpSecret");
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password" + totpCode))
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());
    response.close();

    clearBruteForce();
    adminClient.realm("test").users().get(user.getId()).removeCredential(totpCredential.getId());
}