Java Code Examples for com.sun.jersey.api.client.ClientResponse#close()

The following examples show how to use com.sun.jersey.api.client.ClientResponse#close() . 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
Source File: NeoGraphDatabase.java    From navex with GNU General Public License v3.0 6 votes vote down vote up
private static void addLable(URI nodeUri) throws URISyntaxException {

		// START SNIPPET: addlable
		URI Uri = new URI( nodeUri.toString() + "/labels");
		// e.g : http://localhost:7474/db/data/node/59/labels

		WebResource resource = Client.create()
				.resource( Uri );
		ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
				.type( MediaType.APPLICATION_JSON )
				.entity( "\"Dynamic\"" )
				.post( ClientResponse.class );

		System.out.println( String.format( "PUT to [%s], status code [%d]",
				Uri, response.getStatus() ) );
		response.close();
		// END SNIPPET: addlable

	}
 
Example 2
Source File: RestIT.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testComplexObjectJacksonSerialization() throws JSONException {
  WebResource resource = client.resource(APP_BASE_PATH + PROCESS_DEFINITION_PATH + "/statistics");
  ClientResponse response = resource.queryParam("incidents", "true").accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

  JSONArray definitionStatistics = response.getEntity(JSONArray.class);
  response.close();

  assertEquals(200, response.getStatus());
  // invoice example instance
  assertEquals(3, definitionStatistics.length());

  // check that definition is also serialized
  for (int i = 0; i < definitionStatistics.length(); i++) {
    JSONObject definitionStatistic = definitionStatistics.getJSONObject(i);
    assertEquals("org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionStatisticsResultDto", definitionStatistic.getString("@class"));
    assertEquals(0, definitionStatistic.getJSONArray("incidents").length());
    JSONObject definition = definitionStatistic.getJSONObject("definition");
    assertTrue(definition.getString("name").toLowerCase().contains("invoice"));
    assertFalse(definition.getBoolean("suspended"));
  }
}
 
Example 3
Source File: ErrorPageIT.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCheckNonFoundResponse() {
  // when
  ClientResponse response = client.resource(APP_BASE_PATH + "nonexisting")
      .get(ClientResponse.class);

  // then
  assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
  assertTrue(response.getType().toString().startsWith(MediaType.TEXT_HTML));
  String responseEntity = response.getEntity(String.class);
  assertTrue(responseEntity.contains("Camunda"));
  assertTrue(responseEntity.contains("Not Found"));

  // cleanup
  response.close();
}
 
Example 4
Source File: NeoGraphDatabase.java    From navex with GNU General Public License v3.0 6 votes vote down vote up
private static URI createNode()
{
	// START SNIPPET: createNode
	final String nodeEntryPointUri = SERVER_ROOT_URI + "node";
	// http://localhost:7474/db/data/node

	WebResource resource = Client.create()
			.resource( nodeEntryPointUri );
	// POST {} to the node entry point URI
	ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
			.type( MediaType.APPLICATION_JSON )
			.entity( "{}" )
			.post( ClientResponse.class );

	final URI location = response.getLocation();
	System.out.println( String.format(
			"POST to [%s], status code [%d], location header [%s]",
			nodeEntryPointUri, response.getStatus(), location.toString() ) );
	response.close();

	return location;
	// END SNIPPET: createNode
}
 
Example 5
Source File: ElasticSearchDBHandler.java    From Insights with Apache License 2.0 6 votes vote down vote up
public JsonObject queryES(String sourceESUrl, String query) throws Exception {

		ClientResponse response = null;
		JsonObject data = null;
		try {
			WebResource resource = Client.create().resource(sourceESUrl);
			response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
					.post(ClientResponse.class, query);
			if (!((response.getStatus() == 200) || (response.getStatus() == 201) || (response.getStatus() == 404))) {
				throw new Exception("Failed to get response from ElasticSeach for query - " + query
						+ "-- HTTP response code -" + response.getStatus());
			}

			data = new JsonParser().parse(response.getEntity(String.class)).getAsJsonObject();
		} catch (Exception e) {
			log.error("Exception while getting data from ES for query - " + query, e);
			throw new Exception(e.getMessage());
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return data;
	}
 
Example 6
Source File: RestServerTest.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDelete() throws Exception {
    SyncConfig syncConfig = new SyncConfig();
    syncConfig.setSource(new TestConfig().withObjectCount(10).withMaxSize(10240).withDiscardData(false));
    syncConfig.setTarget(new TestConfig().withReadData(true).withDiscardData(false));

    // create sync job
    ClientResponse response = client.resource(endpoint).path("/job").type(XML).put(ClientResponse.class, syncConfig);
    String jobIdStr = response.getHeaders().getFirst("x-emc-job-id");
    try {
        Assert.assertEquals(response.getEntity(String.class), 201, response.getStatus());
        response.close(); // must close all responses

        Assert.assertNotNull(jobIdStr);
        int jobId = Integer.parseInt(jobIdStr);

        // wait for job to complete
        while (!client.resource(endpoint).path("/job/" + jobId + "/control").get(JobControl.class).getStatus().isFinalState()) {
            Thread.sleep(1000);
        }

        // get status (should be complete)
        JobControl jobControl = client.resource(endpoint).path("/job/" + jobId + "/control").get(JobControl.class);
        Assert.assertNotNull(jobControl);
        Assert.assertEquals(JobControlStatus.Complete, jobControl.getStatus());
    } finally {
        // delete job
        response = client.resource(endpoint).path("/job/" + jobIdStr).delete(ClientResponse.class);
        if (response.getStatus() != 200)
            log.warn("could not delete job: {}", response.getEntity(String.class));
        response.close(); // must close all responses
    }
}
 
Example 7
Source File: ExceptionLoggerIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotFailForUndefinedUser() {
  // when
  ClientResponse response = client.resource(APP_BASE_PATH + "app/admin/default/#/users/undefined?tab=profile")
                                  .get(ClientResponse.class);

  // then
  assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

  // cleanup
  response.close();
}
 
Example 8
Source File: RestIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected JSONObject getFirstTask() throws JSONException {
  ClientResponse response = client.resource(APP_BASE_PATH + TASK_PATH).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  JSONArray tasks = response.getEntity(JSONArray.class);
  JSONObject firstTask = tasks.getJSONObject(0);
  response.close();
  return firstTask;
}
 
Example 9
Source File: KylinClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
private static ClientResponse getClientResponse(String kylinUrl, String userName, String password) {
	ClientResponse response = null;
	String[] kylinUrls = kylinUrl.trim().split("[,;]");
	if (ArrayUtils.isEmpty(kylinUrls)) {
		return null;
	}

	Client client = Client.create();
	String decryptedPwd = PasswordUtils.getDecryptPassword(password);
	client.addFilter(new HTTPBasicAuthFilter(userName, decryptedPwd));

	for (String currentUrl : kylinUrls) {
		if (StringUtils.isBlank(currentUrl)) {
			continue;
		}

		String url = currentUrl.trim() + KYLIN_LIST_API_ENDPOINT;
		try {
			response = getProjectResponse(url, client);

			if (response != null) {
				if (response.getStatus() == HttpStatus.SC_OK) {
					break;
				} else {
					response.close();
				}
			}
		} catch (Throwable t) {
			String msgDesc = "Exception while getting kylin response, kylinUrl: " + url;
			LOG.error(msgDesc, t);
		}
	}
	client.destroy();

	return response;
}
 
Example 10
Source File: ElasticsearchClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
private static ClientResponse getClientResponse(String elasticsearchUrl, String elasticsearchApi, String userName) {
	String[] elasticsearchUrls = elasticsearchUrl.trim().split("[,;]");
	if (ArrayUtils.isEmpty(elasticsearchUrls)) {
		return null;
	}

	ClientResponse response = null;
	Client client = Client.create();
	for (String currentUrl : elasticsearchUrls) {
		if (StringUtils.isBlank(currentUrl)) {
			continue;
		}

		String url = currentUrl.trim() + elasticsearchApi;
		try {
			response = getClientResponse(url, client, userName);

			if (response != null) {
				if (response.getStatus() == HttpStatus.SC_OK) {
					break;
				} else {
					response.close();
				}
			}
		} catch (Throwable t) {
			String msgDesc = "Exception while getting elasticsearch response, elasticsearchUrl: " + url;
			LOG.error(msgDesc, t);
		}
	}
	client.destroy();

	return response;
}
 
Example 11
Source File: SqoopClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
private static ClientResponse getClientResponse(String sqoopUrl, String sqoopApi, String userName) {
	ClientResponse response = null;
	String[] sqoopUrls = sqoopUrl.trim().split("[,;]");
	if (ArrayUtils.isEmpty(sqoopUrls)) {
		return null;
	}

	Client client = Client.create();

	for (String currentUrl : sqoopUrls) {
		if (StringUtils.isBlank(currentUrl)) {
			continue;
		}

		String url = currentUrl.trim() + sqoopApi + "?" + PseudoAuthenticator.USER_NAME + "=" + userName;
		try {
			response = getClientResponse(url, client);

			if (response != null) {
				if (response.getStatus() == HttpStatus.SC_OK) {
					break;
				} else {
					response.close();
				}
			}
		} catch (Throwable t) {
			String msgDesc = "Exception while getting sqoop response, sqoopUrl: " + url;
			LOG.error(msgDesc, t);
		}
	}
	client.destroy();

	return response;
}
 
Example 12
Source File: RestIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void assertJodaTimePresent() {
  log.info("Checking " + APP_BASE_PATH + TASK_PATH);

  WebResource resource = client.resource(APP_BASE_PATH + TASK_PATH);
  resource.queryParam("dueAfter", "2000-01-01T00-00-00");
  ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

  assertEquals(200, response.getStatus());

  JSONArray definitionsJson = response.getEntity(JSONArray.class);
  assertEquals(6, definitionsJson.length());

  response.close();
}
 
Example 13
Source File: BaseIndexer.java    From q with Apache License 2.0 5 votes vote down vote up
void commit()
{
	WebResource webResource = client.resource(getUrlForCommitting());
	ClientResponse response = webResource.get(ClientResponse.class);
	if (response == null || (response.getStatus() != 201 && response.getStatus() != 200))
	{
		throw new RuntimeException("Failed : HTTP error code on commit: " + response.getStatus());
	}
	response.close();
}
 
Example 14
Source File: BaseIndexer.java    From q with Apache License 2.0 5 votes vote down vote up
void addDoc(Map<String, Object> doc)
{
	JsonNode node = new ObjectMapper().valueToTree(doc);
	StringBuilder jsonString = getJsonStringOfDoc(node);

	WebResource webResource = client.resource(getUrlForAddingDoc(doc));
	ClientResponse response = webResource.type("application/json").post(ClientResponse.class, jsonString.toString());
	if (response == null || (response.getStatus() != 201 && response.getStatus() != 200))
	{
		throw new RuntimeException("Failed : HTTP error code on adding a doc: " + response.getStatus());
	}
	response.close();
}
 
Example 15
Source File: SystemStatus.java    From Insights with Apache License 2.0 5 votes vote down vote up
public static String jerseyGetClientWithAuthentication(String url, String name, String password,String authtoken) {
	String output;
	String authStringEnc;
	ClientResponse response = null;
       try {
       	if(authtoken==null) {
       		String authString = name + ":" + password;
   			authStringEnc= new BASE64Encoder().encode(authString.getBytes());
   		}else {
   			authStringEnc=authtoken;
   		}
		Client restClient = Client.create();
		restClient.setConnectTimeout(5001);
		WebResource webResource = restClient.resource(url);
		response= webResource.accept("application/json")
		                                 .header("Authorization", "Basic " + authStringEnc)
		                                 .get(ClientResponse.class);
		if(response.getStatus() != 200){
			throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
		}else {
			output= response.getEntity(String.class);
		}
	} catch (Exception e) {
		log.error(" error while getting jerseyGetClientWithAuthentication "+e.getMessage());
		throw new RuntimeException("Failed : error while getting jerseyGetClientWithAuthentication : "+ e.getMessage());
	}finally {
		if(response!=null) {
			response.close();
		}
	}
       return output;
}
 
Example 16
Source File: RestJaxRs2IT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test(timeout=10000)
public void shouldUseJaxRs2Artifact() throws JSONException {
  Map<String, Object> payload = new HashMap<String, Object>();
  payload.put("workerId", "aWorkerId");
  payload.put("asyncResponseTimeout", 1000 * 60 * 30 + 1);

  ClientResponse response = client.resource(APP_BASE_PATH + FETCH_AND_LOCK_PATH).accept(MediaType.APPLICATION_JSON)
    .entity(payload, MediaType.APPLICATION_JSON_TYPE)
    .post(ClientResponse.class);

  assertEquals(400, response.getStatus());
  String responseMessage = response.getEntity(JSONObject.class).get("message").toString();
  assertTrue(responseMessage.equals("The asynchronous response timeout cannot be set to a value greater than 1800000 milliseconds"));
  response.close();
}
 
Example 17
Source File: NeoGraphDatabase.java    From navex with GNU General Public License v3.0 5 votes vote down vote up
private static void checkDatabaseIsRunning()
{
	// START SNIPPET: checkServer
	WebResource resource = Client.create()
			.resource( SERVER_ROOT_URI );
	ClientResponse response = resource.get( ClientResponse.class );

	System.out.println( String.format( "GET on [%s], status code [%d]",
			SERVER_ROOT_URI, response.getStatus() ) );
	response.close();
	// END SNIPPET: checkServer
}
 
Example 18
Source File: RestServerTest.java    From ecs-sync with Apache License 2.0 4 votes vote down vote up
@Test
public void testProgress() throws Exception {
    try {
        int threads = 16;

        SyncConfig syncConfig = new SyncConfig();
        syncConfig.setSource(new TestConfig().withObjectCount(80).withMaxSize(10240).withMaxDepth(4).withDiscardData(false));
        syncConfig.setTarget(new TestConfig().withReadData(true).withDiscardData(false));
        syncConfig.setFilters(Collections.singletonList(new DelayFilter.DelayConfig().withDelayMs(100)));
        syncConfig.withOptions(new SyncOptions().withThreadCount(threads));

        // create sync job
        ClientResponse response = client.resource(endpoint).path("/job").type(XML).put(ClientResponse.class, syncConfig);
        String jobId = response.getHeaders().getFirst("x-emc-job-id");

        Assert.assertEquals(response.getEntity(String.class), 201, response.getStatus());
        response.close(); // must close all responses

        // wait for sync to start
        while (client.resource(endpoint).path("/job/" + jobId + "/control").get(JobControl.class).getStatus() == JobControlStatus.Initializing) {
            Thread.sleep(500);
        }
        Thread.sleep(500);

        SyncProgress progress = client.resource(endpoint).path("/job/" + jobId + "/progress").get(SyncProgress.class);
        Assert.assertEquals(JobControlStatus.Running, progress.getStatus());
        Assert.assertTrue(progress.getTotalObjectsExpected() > 100);
        Assert.assertTrue(progress.getTotalBytesExpected() > 100 * 5120);
        Assert.assertTrue(progress.getObjectsComplete() > 0);
        Assert.assertTrue(progress.getBytesComplete() > 0);
        Assert.assertEquals(0, progress.getObjectsFailed());
        Assert.assertEquals(progress.getActiveQueryTasks(), 0);
        Assert.assertTrue(Math.abs(progress.getActiveSyncTasks() - threads) < 2);
        Assert.assertTrue(progress.getRuntimeMs() > 500);

        // bump threads to speed up completion
        client.resource(endpoint).path("/job/" + jobId + "/control").type(XML).post(new JobControl(JobControlStatus.Running, 32));
        // wait for job to complete
        while (!client.resource(endpoint).path("/job/" + jobId + "/control").get(JobControl.class).getStatus().isFinalState()) {
            Thread.sleep(1000);
        }

        JobControl jobControl = client.resource(endpoint).path("/job/" + jobId + "/control").get(JobControl.class);
        Assert.assertEquals(JobControlStatus.Complete, jobControl.getStatus());

        // delete job
        response = client.resource(endpoint).path("/job/" + jobId).delete(ClientResponse.class);
        Assert.assertEquals(response.getEntity(String.class), 200, response.getStatus());
        response.close(); // must close all responses
    } catch (UniformInterfaceException e) {
        log.error(e.getResponse().getEntity(String.class));
        throw e;
    }
}
 
Example 19
Source File: main.java    From graphify with Apache License 2.0 4 votes vote down vote up
private static List<Map<String, Object>> getWikipediaArticles() throws IOException {
    final String txUri = "http://localhost:7474/db/data/" + "transaction/commit";
    WebResource resource = Client.create().resource( txUri );

    String query = "MATCH (n:Page) WITH n, rand() as sortOrder " +
            "ORDER BY sortOrder " +
            "LIMIT 1000 " +
            "RETURN n.title as title";

    String payload = "{\"statements\" : [ {\"statement\" : \"" +query + "\"} ]}";
    ClientResponse response = resource
            .accept( MediaType.APPLICATION_JSON )
            .type( MediaType.APPLICATION_JSON )
            .entity( payload )
            .post( ClientResponse.class );

    ObjectMapper objectMapper = new ObjectMapper();
    HashMap<String, Object> result;
    try {
        result = objectMapper.readValue(response.getEntity( String.class ), HashMap.class);
    } catch (Exception e) {
        throw e;
    }
    response.close();

    List<Map<String, Object>> results = new ArrayList<>();

    ArrayList resultSet = ((ArrayList)result.get("results"));
    List<LinkedHashMap<String, Object>> dataSet = (List<LinkedHashMap<String, Object>>)resultSet.stream().map(a -> (LinkedHashMap<String, Object>)a).collect(Collectors.toList());

    List<LinkedHashMap> rows = (List<LinkedHashMap>)((ArrayList)(dataSet.get(0).get("data"))).stream().map(m -> (LinkedHashMap)m).collect(Collectors.toList());
    ArrayList cols = (ArrayList)(dataSet.get(0).get("columns"));

    for(LinkedHashMap row : rows) {
        ArrayList values = (ArrayList)row.get("row");
        Map<String, Object> resultRecord = new HashMap<>();
        for (int i = 0; i < values.size(); i++) {
            resultRecord.put(cols.get(i).toString(), values.get(i));
        }
        results.add(resultRecord);
    }
    return results;
}
 
Example 20
Source File: RestServerTest.java    From ecs-sync with Apache License 2.0 4 votes vote down vote up
@Test
public void testListJobs() throws Exception {
    SyncConfig syncConfig = new SyncConfig();
    syncConfig.setSource(new TestConfig().withObjectCount(10).withMaxSize(10240).withDiscardData(false));
    syncConfig.setTarget(new TestConfig().withReadData(true).withDiscardData(false));

    // create 3 sync jobs
    ClientResponse response = client.resource(endpoint).path("/job").type(XML).put(ClientResponse.class, syncConfig);
    Assert.assertEquals(response.getEntity(String.class), 201, response.getStatus());
    String jobId1 = response.getHeaders().getFirst("x-emc-job-id");
    response.close(); // must close all responses

    response = client.resource(endpoint).path("/job").type(XML).put(ClientResponse.class, syncConfig);
    Assert.assertEquals(response.getEntity(String.class), 201, response.getStatus());
    String jobId2 = response.getHeaders().getFirst("x-emc-job-id");
    response.close(); // must close all responses

    response = client.resource(endpoint).path("/job").type(XML).put(ClientResponse.class, syncConfig);
    Assert.assertEquals(response.getEntity(String.class), 201, response.getStatus());
    String jobId3 = response.getHeaders().getFirst("x-emc-job-id");
    response.close(); // must close all responses

    // get job list
    JobList jobList = client.resource(endpoint).path("/job").get(JobList.class);

    Assert.assertNotNull(jobList);
    Assert.assertEquals(3, jobList.getJobs().size());
    Assert.assertEquals(new Integer(jobId1), jobList.getJobs().get(0).getJobId());
    Assert.assertEquals(new Integer(jobId2), jobList.getJobs().get(1).getJobId());
    Assert.assertEquals(new Integer(jobId3), jobList.getJobs().get(2).getJobId());

    // wait for jobs to complete
    while (!client.resource(endpoint).path("/job/" + jobId1 + "/control").get(JobControl.class).getStatus().isFinalState()
            && !client.resource(endpoint).path("/job/" + jobId2 + "/control").get(JobControl.class).getStatus().isFinalState()
            && !client.resource(endpoint).path("/job/" + jobId3 + "/control").get(JobControl.class).getStatus().isFinalState()) {
        Thread.sleep(1000);
    }

    // delete jobs
    response = client.resource(endpoint).path("/job/" + jobId1).delete(ClientResponse.class);
    Assert.assertEquals(response.getEntity(String.class), 200, response.getStatus());
    response.close(); // must close all responses

    response = client.resource(endpoint).path("/job/" + jobId2).delete(ClientResponse.class);
    Assert.assertEquals(response.getEntity(String.class), 200, response.getStatus());
    response.close(); // must close all responses

    response = client.resource(endpoint).path("/job/" + jobId3).delete(ClientResponse.class);
    Assert.assertEquals(response.getEntity(String.class), 200, response.getStatus());
    response.close(); // must close all responses
}