Java Code Examples for com.sun.jersey.api.client.ClientResponse

The following examples show how to use com.sun.jersey.api.client.ClientResponse. 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 ResultSet getProcedures(String id, String catalog, String schemaPattern, String procedureNamePattern) 
		throws WebServiceException {
	ProcedureDTO procedureDTO = new ProcedureDTO();
	procedureDTO.id = id;
	procedureDTO.catalog = catalog;
	procedureDTO.schemaPattern = schemaPattern;
	procedureDTO.procedureNamePattern = procedureNamePattern;
	
	ClientResponse response = createRootResource().path("jdbc/databaseMetaData/getProcedures")
		.post(ClientResponse.class, procedureDTO);

	checkForException(response);

	ResultSetDTO theData = response.getEntity(ResultSetDTO.class);
	return new ResultSet(theData);
}
 
Example 2
Source Project: ranger   Source File: TagAdminRESTSink.java    License: Apache License 2.0 6 votes vote down vote up
private ClientResponse tryWithCred(ServiceTags serviceTags) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> tryWithCred");
	}
	ClientResponse clientResponsebyCred = uploadTagsWithCred(serviceTags);
	if (clientResponsebyCred != null && clientResponsebyCred.getStatus() != HttpServletResponse.SC_NO_CONTENT
			&& clientResponsebyCred.getStatus() != HttpServletResponse.SC_BAD_REQUEST
			&& clientResponsebyCred.getStatus() != HttpServletResponse.SC_OK) {
		sessionId = null;
		clientResponsebyCred = null;
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("<== tryWithCred");
	}
	return clientResponsebyCred;
}
 
Example 3
public List<Artifact> getArtefactList(String groupId, String artifactId) {
    LOGGER.info("Get artifact list for " + groupId + " " + artifactId);
    List<Artifact> list = new ArrayList<Artifact>();

    final Client client = buildClient();
    final WebResource restResource = client.resource(repositoryURI);
    WebResource path = restResource.path("service").path("local").path("lucene").path("search");
    WebResource queryParam = path.queryParam("g", groupId).queryParam("a", artifactId);
    final ClientResponse clientResponse = queryParam.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);

    final SearchResponse response = clientResponse.getEntity(SearchResponse.class);
    List<NexusArtifact> data = response.getData();
    for (NexusArtifact nexusArtifact : data) {
        Artifact a = new Artifact(nexusArtifact.getArtifactId(), nexusArtifact.getVersion(), "");
        list.add(a);
    }

    return list;
}
 
Example 4
Source Project: big-c   Source File: TestRMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAppsQueryQueue() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  rm.submitApp(CONTAINER_MB);
  rm.submitApp(CONTAINER_MB);

  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps").queryParam("queue", "default")
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  assertEquals("incorrect number of elements", 1, json.length());
  JSONObject apps = json.getJSONObject("apps");
  assertEquals("incorrect number of elements", 1, apps.length());
  JSONArray array = apps.getJSONArray("app");
  assertEquals("incorrect number of elements", 2, array.length());
  rm.stop();
}
 
Example 5
Source Project: big-c   Source File: TestHsWebServicesTasks.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTasksSlash() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("tasks/")
        .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject tasks = json.getJSONObject("tasks");
    JSONArray arr = tasks.getJSONArray("task");
    assertEquals("incorrect number of elements", 2, arr.length());

    verifyHsTask(arr, jobsMap.get(id), null);
  }
}
 
Example 6
Source Project: emodb   Source File: ReplicationJerseyTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Test delete w/a valid API key but not one that has permission to delete. */
@Test
public void testDeleteForbidden() {
    List<String> ids = ImmutableList.of("first", "second");

    try {
        replicationClient("completely-unknown-key").delete("channel", ids);
        fail();
    } catch (UniformInterfaceException e) {
        if (e.getResponse().getClientResponseStatus() != ClientResponse.Status.FORBIDDEN) {
            throw e;
        }
    }

    verifyNoMoreInteractions(_server);
}
 
Example 7
Source Project: product-ei   Source File: FilterFromJSONPathTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = {"wso2.esb"}, description = "Tests with filter mediator - JSON path Scenario - Filter condition true")
public void testJSONFilterFromJSONPathConditionTrueTestScenario() throws Exception {

    String JSON_PAYLOAD = "{\"album\":\"Hello\",\"singer\":\"Peter\"}";

    WebResource webResource = client
            .resource(getProxyServiceURLHttp("JSONPathFilterWithJSONProxy"));

    // sending post request
    ClientResponse postResponse = webResource.type("application/json")
            .post(ClientResponse.class, JSON_PAYLOAD);

    assertEquals(postResponse.getType().toString(), "application/json", "Content-Type Should be application/json");
    assertEquals(postResponse.getStatus(), 201, "Response status should be 201");

    // Calling the GET request to verify Added album details
    ClientResponse getResponse = webResource.type("application/json")
            .get(ClientResponse.class);

    assertNotNull(getResponse, "Received Null response for while getting Music album details");
    assertEquals(getResponse.getEntity(String.class), JSON_PAYLOAD, "Response mismatch for HTTP Get call");
}
 
Example 8
Source Project: big-c   Source File: TestHsWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobIdInvalid() throws JSONException, Exception {
  WebResource r = resource();

  try {
    r.path("ws").path("v1").path("history").path("mapreduce").path("jobs")
        .path("job_foo").accept(MediaType.APPLICATION_JSON)
        .get(JSONObject.class);
    fail("should have thrown exception on invalid uri");
  } catch (UniformInterfaceException ue) {
    ClientResponse response = ue.getResponse();
    assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject msg = response.getEntity(JSONObject.class);
    JSONObject exception = msg.getJSONObject("RemoteException");
    assertEquals("incorrect number of elements", 3, exception.length());
    String message = exception.getString("message");
    String type = exception.getString("exception");
    String classname = exception.getString("javaClassName");
    verifyJobIdInvalid(message, type, classname);

  }
}
 
Example 9
Source Project: big-c   Source File: TestAMWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobIdInvalidDefault() throws JSONException, Exception {
  WebResource r = resource();

  try {
    r.path("ws").path("v1").path("mapreduce").path("jobs").path("job_foo")
        .get(JSONObject.class);
    fail("should have thrown exception on invalid uri");
  } catch (UniformInterfaceException ue) {
    ClientResponse response = ue.getResponse();
    assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject msg = response.getEntity(JSONObject.class);
    JSONObject exception = msg.getJSONObject("RemoteException");
    assertEquals("incorrect number of elements", 3, exception.length());
    String message = exception.getString("message");
    String type = exception.getString("exception");
    String classname = exception.getString("javaClassName");
    verifyJobIdInvalid(message, type, classname);
  }
}
 
Example 10
Source Project: big-c   Source File: TestHsWebServicesTasks.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTasksXML() throws JSONException, Exception {

  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("tasks")
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList tasks = dom.getElementsByTagName("tasks");
    assertEquals("incorrect number of elements", 1, tasks.getLength());
    NodeList task = dom.getElementsByTagName("task");
    verifyHsTaskXML(task, jobsMap.get(id));
  }
}
 
Example 11
Source Project: localization_nifi   Source File: ITAccessTokenEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Obtains a token and creates a processor using it.
 *
 * @throws Exception ex
 */
@Test
public void testCreateProcessorUsingToken() throws Exception {
    String url = BASE_URL + "/access/token";

    ClientResponse response = TOKEN_USER.testCreateToken(url, "[email protected]", "whatever");

    // ensure the request is successful
    Assert.assertEquals(201, response.getStatus());

    // get the token
    String token = response.getEntity(String.class);

    // attempt to create a processor with it
    createProcessor(token);
}
 
Example 12
Source Project: atlas   Source File: AtlasClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEntity() throws Exception {
    setupRetryParams();
    AtlasClient atlasClient = new AtlasClient(service, configuration);

    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.CREATE_ENTITY, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.CREATED.getStatusCode());

    String jsonResponse = AtlasType.toV1Json(new EntityResult(Arrays.asList("id"), null, null));
    when(response.getEntity(String.class)).thenReturn(jsonResponse.toString());
    when(response.getLength()).thenReturn(jsonResponse.length());

    String entityJson = AtlasType.toV1Json(new Referenceable("type"));
    when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response);

    List<String> ids = atlasClient.createEntity(entityJson);
    assertEquals(ids.size(), 1);
    assertEquals(ids.get(0), "id");
}
 
Example 13
Source Project: ingestion   Source File: RestSourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws SchedulerException {
    when(builder.header(anyString(), anyObject())).thenReturn(builder);
    when(builder.header(anyString(), anyObject())).thenReturn(builder);
    when(builder.get(ClientResponse.class)).thenReturn(response);
    when(webResource.accept(any(MediaType.class))).thenReturn(builder);
    queue = new LinkedBlockingQueue<Event>(10);
    when(schedulerContext.get("queue")).thenReturn(queue);
    when(schedulerContext.get("client")).thenReturn(client);
    when(contextJob.getScheduler()).thenReturn(scheduler);
    when(scheduler.getContext()).thenReturn(schedulerContext);
    when(contextSource.getInteger("frequency", 10)).thenReturn(10);
    when(contextSource.getString(CONF_URL)).thenReturn(CONF_URL);
    when(contextSource.getString(CONF_METHOD, DEFAULT_METHOD)).thenReturn(DEFAULT_METHOD);
    when(contextSource.getString(CONF_APPLICATION_TYPE, DEFAULT_APPLICATION_TYPE)).thenReturn
            (DEFAULT_APPLICATION_TYPE);
    when(contextSource.getString(CONF_HEADERS, DEFAULT_HEADERS)).thenReturn(DEFAULT_HEADERS);
    when(contextSource.getString(CONF_BODY, DEFAULT_BODY)).thenReturn(DEFAULT_BODY);
    when(contextSource.getString(CONF_HANDLER, DEFAULT_REST_HANDLER)).thenReturn(DEFAULT_REST_HANDLER);
    when(contextSource.getString(URL_CONF)).thenReturn(URL_CONF);
    when(contextSource.getString(URL_HANDLER, DEFAULT_URL_HANDLER)).thenReturn(DEFAULT_URL_HANDLER);
    when(contextSource.getBoolean(CONF_SKIP_SSL, Boolean.FALSE)).thenReturn(Boolean.TRUE);


}
 
Example 14
Source Project: camunda-bpm-platform   Source File: ErrorPageIT.java    License: 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 15
Source Project: jira-rest-client   Source File: ProjectService.java    License: Apache License 2.0 6 votes vote down vote up
public Project getProjectDetail(String idOrKey) throws IOException {
	if (client == null)
		throw new IllegalStateException("HTTP Client not Initailized");
	
	client.setResourceName(Constants.JIRA_RESOURCE_PROJECT + "/" + idOrKey);
	ClientResponse response = client.get();
				
	String content = response.getEntity(String.class);	
	
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
	
	TypeReference<Project> ref = new TypeReference<Project>(){};
	Project prj = mapper.readValue(content, ref);
	
	return prj;
}
 
Example 16
Source Project: hadoop   Source File: TestAMWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobCountersDefault() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).path("counters/").get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("jobCounters");
    verifyAMJobCounters(info, jobsMap.get(id));
  }
}
 
Example 17
Source Project: big-c   Source File: TestAMWebServices.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidAccept() throws JSONException, Exception {
  WebResource r = resource();
  String responseStr = "";
  try {
    responseStr = r.path("ws").path("v1").path("mapreduce")
        .accept(MediaType.TEXT_PLAIN).get(String.class);
    fail("should have thrown exception on invalid uri");
  } catch (UniformInterfaceException ue) {
    ClientResponse response = ue.getResponse();
    assertEquals(Status.INTERNAL_SERVER_ERROR,
        response.getClientResponseStatus());
    WebServicesTestUtils.checkStringMatch(
        "error string exists and shouldn't", "", responseStr);
  }
}
 
Example 18
Source Project: big-c   Source File: TestAMWebServicesJobConf.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobConfDefault() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).path("conf").get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("conf");
    verifyAMJobConf(info, jobsMap.get(id));
  }
}
 
Example 19
Source Project: product-ei   Source File: HTTPPUTOnJsonPayloadsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = {"wso2.esb"}, description = "Tests PUT method with application/json content type",
        dependsOnMethods = "testHTTPGetRequestByDefaultAlbumJSONScenario")
public void testHTTPPutRequestUpdatedAlbumJSONScenario() throws Exception {

    String JSON_PAYLOAD = "{\"album\":\"THE ENDLESS RIVER\",\"singer\":\"MichaelJ\"}";

    WebResource webResource = client
            .resource(getProxyServiceURLHttp("JsonHTTPPutProxy"));

    // sending put request
    ClientResponse putResponse = webResource.type("application/json")
            .put(ClientResponse.class, JSON_PAYLOAD);

    assertEquals(putResponse.getType().toString(), "application/json", "Content-Type Should be application/json");
    assertEquals(putResponse.getStatus(), 201, "Response status should be 201");

    // Calling the GET request to verify Added album details
    ClientResponse getResponse = webResource.type("application/json")
            .get(ClientResponse.class);

    assertNotNull(getResponse, "Received Null response for while getting Music album details");
    assertEquals(getResponse.getEntity(String.class), JSON_PAYLOAD, "Response mismatch for HTTP Get call");

}
 
Example 20
Source Project: hadoop   Source File: TestNMWebServicesContainers.java    License: Apache License 2.0 6 votes vote down vote up
public void testNodeSingleContainersHelper(String media)
    throws JSONException, Exception {
  WebResource r = resource();
  Application app = new MockApp(1);
  nmContext.getApplications().put(app.getAppId(), app);
  HashMap<String, String> hash = addAppContainers(app);
  Application app2 = new MockApp(2);
  nmContext.getApplications().put(app2.getAppId(), app2);
  addAppContainers(app2);

  for (String id : hash.keySet()) {
    ClientResponse response = r.path("ws").path("v1").path("node")
        .path("containers").path(id).accept(media).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    verifyNodeContainerInfo(json.getJSONObject("container"), nmContext
        .getContainers().get(ConverterUtils.toContainerId(id)));
  }
}
 
Example 21
Source Project: big-c   Source File: TestHsWebServicesTasks.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTaskIdCountersDefault() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    for (Task task : jobsMap.get(id).getTasks().values()) {

      String tid = MRApps.toString(task.getID());
      ClientResponse response = r.path("ws").path("v1").path("history")
          .path("mapreduce").path("jobs").path(jobId).path("tasks").path(tid)
          .path("counters").get(ClientResponse.class);
      assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
      JSONObject json = response.getEntity(JSONObject.class);
      assertEquals("incorrect number of elements", 1, json.length());
      JSONObject info = json.getJSONObject("jobTaskCounters");
      verifyHsJobTaskCounters(info, task);
    }
  }
}
 
Example 22
Source Project: big-c   Source File: TestHsWebServicesTasks.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobTaskCountersXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    for (Task task : jobsMap.get(id).getTasks().values()) {

      String tid = MRApps.toString(task.getID());
      ClientResponse response = r.path("ws").path("v1").path("history")
          .path("mapreduce").path("jobs").path(jobId).path("tasks").path(tid)
          .path("counters").accept(MediaType.APPLICATION_XML)
          .get(ClientResponse.class);
      assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
      String xml = response.getEntity(String.class);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(xml));
      Document dom = db.parse(is);
      NodeList info = dom.getElementsByTagName("jobTaskCounters");
      verifyHsTaskCountersXML(info, task);
    }
  }
}
 
Example 23
Source Project: roboconf-platform   Source File: DebugWsDelegate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Runs a diagnostic for a given instance.
 * @return the instance
 * @throws DebugWsException
 */
public Diagnostic diagnoseInstance( String applicationName, String instancePath )
throws DebugWsException {

	this.logger.finer( "Diagnosing instance " + instancePath + " in application " + applicationName );

	WebResource path = this.resource.path( UrlConstants.DEBUG ).path( "diagnose-instance" );
	path = path.queryParam( "application-name", applicationName );
	path = path.queryParam( "instance-path", instancePath );

	ClientResponse response = this.wsClient.createBuilder( path )
					.accept( MediaType.APPLICATION_JSON )
					.get( ClientResponse.class );

	if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
		String value = response.getEntity( String.class );
		this.logger.finer( response.getStatusInfo() + ": " + value );
		throw new DebugWsException( response.getStatusInfo().getStatusCode(), value );
	}

	this.logger.finer( String.valueOf( response.getStatusInfo()));
	return response.getEntity( Diagnostic.class );
}
 
Example 24
Source Project: usergrid   Source File: ChopUiTestUtils.java    License: Apache License 2.0 6 votes vote down vote up
static void testStoreResults( TestParams testParams ) throws Exception {
    FormDataMultiPart part = new FormDataMultiPart();
    File tmpFile = File.createTempFile("results", "tmp");
    FileInputStream in = new FileInputStream( tmpFile );
    FormDataBodyPart body = new FormDataBodyPart( RestParams.CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
    part.bodyPart( body );

    ClientResponse response = testParams.addQueryParameters( QUERY_PARAMS )
            .setEndpoint( RunManagerResource.ENDPOINT )
            .newWebResource()
            .queryParam( RestParams.RUNNER_HOSTNAME, "localhost" )
            .queryParam( RestParams.RUN_ID, "112316437" )
            .queryParam( RestParams.RUN_NUMBER, "3" )
            .path( "/store" )
            .type( MediaType.MULTIPART_FORM_DATA_TYPE )
            .accept( MediaType.APPLICATION_JSON )
            .post( ClientResponse.class, part );

    tmpFile.delete();

    assertEquals( Response.Status.CREATED.getStatusCode(), response.getStatus() );

    assertEquals( UploadResource.SUCCESSFUL_TEST_MESSAGE, response.getEntity( String.class ) );
}
 
Example 25
Source Project: hadoop   Source File: TestHsWebServicesJobsQuery.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryFinishTimeBeginNegative() throws JSONException,
    Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("finishedTimeBegin", String.valueOf(-1000))
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject msg = response.getEntity(JSONObject.class);
  JSONObject exception = msg.getJSONObject("RemoteException");
  assertEquals("incorrect number of elements", 3, exception.length());
  String message = exception.getString("message");
  String type = exception.getString("exception");
  String classname = exception.getString("javaClassName");
  WebServicesTestUtils.checkStringMatch("exception message",
      "java.lang.Exception: finishedTimeBegin must be greater than 0",
      message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example 26
Source Project: big-c   Source File: TestHsWebServicesJobsQuery.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryStartTimeNegative() throws JSONException, Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("startedTimeBegin", String.valueOf(-1000))
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject msg = response.getEntity(JSONObject.class);
  JSONObject exception = msg.getJSONObject("RemoteException");
  assertEquals("incorrect number of elements", 3, exception.length());
  String message = exception.getString("message");
  String type = exception.getString("exception");
  String classname = exception.getString("javaClassName");
  WebServicesTestUtils
      .checkStringMatch("exception message",
          "java.lang.Exception: startedTimeBegin must be greater than 0",
          message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example 27
Source Project: hadoop   Source File: TestHsWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobCounters() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("counters")
        .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("jobCounters");
    verifyHsJobCounters(info, appContext.getJob(id));
  }
}
 
Example 28
Source Project: big-c   Source File: TestTimelineWebServices.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDomains() throws Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("timeline")
      .path("domain")
      .queryParam("owner", "owner_1")
      .accept(MediaType.APPLICATION_JSON)
      .get(ClientResponse.class);
  Assert.assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  TimelineDomains domains = response.getEntity(TimelineDomains.class);
  Assert.assertEquals(2, domains.getDomains().size());
  for (int i = 0; i < domains.getDomains().size(); ++i) {
    verifyDomain(domains.getDomains().get(i),
        i == 0 ? "domain_id_4" : "domain_id_1");
  }
}
 
Example 29
Source Project: emodb   Source File: ReportResource1.java    License: Apache License 2.0 6 votes vote down vote up
private RuntimeException handleException(String reportId, Exception e) throws WebApplicationException {
    if (e instanceof ReportNotFoundException) {
        throw new WebApplicationException(
                Response.status(ClientResponse.Status.NOT_FOUND)
                        .type(MediaType.APPLICATION_JSON_TYPE)
                        .entity(ImmutableMap.of("notFound", reportId))
                        .build());
    }

    _log.warn("Report request failed: [reportId={}]", reportId, e);

    throw new WebApplicationException(
            Response.status(ClientResponse.Status.INTERNAL_SERVER_ERROR)
                    .type(MediaType.APPLICATION_JSON_TYPE)
                    .entity(ImmutableMap.of("exception", e.getClass().getName(), "message", e.getMessage()))
                    .build());
}
 
Example 30
Source Project: atlas   Source File: AtlasClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void shouldGetAdminStatus() throws AtlasServiceException {
        setupRetryParams();

        AtlasClient atlasClient = new AtlasClient(service, configuration);

        WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service);
        ClientResponse response = mock(ClientResponse.class);
        when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
        String activeStatus = "{\"Status\":\"Active\"}";
        when(response.getEntity(String.class)).thenReturn(activeStatus);
        when(response.getLength()).thenReturn(activeStatus.length());
        when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response);

//         Fix after AtlasBaseClient
//        atlasClient.setService();


        String status = atlasClient.getAdminStatus();
        assertEquals(status, "Active");
    }