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

The following examples show how to use com.sun.jersey.api.client.ClientResponse. 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: TestAMWebServices.java    From big-c with 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 #2
Source File: IssueService.java    From jira-rest-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of all issue types visible to the user
 *
 * @return List list of IssueType
 *
 * @throws IOException json decoding failed
 */
public List<IssueType> getAllIssueTypes() throws IOException {

    client.setResourceName(Constants.JIRA_RESOURCE_ISSUETYPE);

    ClientResponse response = client.get();
    String content = response.getEntity(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    TypeReference<List<IssueType>> ref = new TypeReference<List<IssueType>>() {
    };
    List<IssueType> issueTypes = mapper.readValue(content, ref);

    return issueTypes;
}
 
Example #3
Source File: FilterFromJSONPathTestCase.java    From product-ei with 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 #4
Source File: TestHsWebServicesJobsQuery.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryStartTimeEndNegative() throws JSONException,
    Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("startedTimeEnd", 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: startedTimeEnd must be greater than 0", message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example #5
Source File: KandyRestClient.java    From karamel with Apache License 2.0 6 votes vote down vote up
public static String estimateCost(String clusterDef) throws KaramelException {
  try {
    checkResources();
    ClientResponse response = costService.type(MediaType.TEXT_PLAIN).post(ClientResponse.class, clusterDef);
    if (response.getStatus() >= 300) {
      logger.debug(String.format("Kandy server couldn't return the cluster cost because '%s'",
          response.getStatusInfo().getReasonPhrase()));
    } else {
      String cost = response.getEntity(String.class);
      return cost;
    }
  } catch (Exception e) {
    logger.error("exception during calling cost estimation to Kandy: " + e.getMessage());
    throw new KaramelException(e.getMessage());
  }
  return null;
}
 
Example #6
Source File: DatabaseMetaDataWebServiceClient.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: NexusConnector.java    From jenkins-deployment-dashboard-plugin with MIT License 6 votes vote down vote up
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 #8
Source File: TagAdminRESTSink.java    From ranger with 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 #9
Source File: TestHsWebServicesTasks.java    From big-c with 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 #10
Source File: ITAccessTokenEndpoint.java    From localization_nifi with 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, "user@nifi", "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 #11
Source File: AtlasClientTest.java    From atlas with 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 #12
Source File: RestSourceTest.java    From ingestion with 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 #13
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 #14
Source File: ProjectService.java    From jira-rest-client with 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 #15
Source File: TestAMWebServicesJobs.java    From hadoop with 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 #16
Source File: ProjectService.java    From jira-rest-client with Apache License 2.0 6 votes vote down vote up
public List<Project> getProjectList() throws IOException {
	if (client == null)
		throw new IllegalStateException("HTTP Client not Initailized");
	
	client.setResourceName(Constants.JIRA_RESOURCE_PROJECT);
	ClientResponse response = client.get();
				
	String content = response.getEntity(String.class);	
	
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
	
	TypeReference<List<Project>> ref = new TypeReference<List<Project>>(){};
	List<Project> prj = mapper.readValue(content, ref);
	
	return prj;
}
 
Example #17
Source File: TestAMWebServicesJobConf.java    From big-c with 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 #18
Source File: HTTPPUTOnJsonPayloadsTestCase.java    From product-ei with 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 #19
Source File: TestNMWebServicesContainers.java    From hadoop with 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 #20
Source File: TestHsWebServicesTasks.java    From big-c with 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 #21
Source File: TestHsWebServicesTasks.java    From big-c with 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 #22
Source File: DebugWsDelegate.java    From roboconf-platform with 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 #23
Source File: ChopUiTestUtils.java    From usergrid with 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 #24
Source File: TestHsWebServicesJobsQuery.java    From hadoop with 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 #25
Source File: TestHsWebServicesJobsQuery.java    From big-c with 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 #26
Source File: TestHsWebServicesJobs.java    From hadoop with 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 #27
Source File: TestTimelineWebServices.java    From big-c with 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 #28
Source File: ReportResource1.java    From emodb with 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 #29
Source File: AtlasClientTest.java    From atlas with 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");
    }
 
Example #30
Source File: TestHsWebServicesTasks.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testTaskId() 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)
          .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("task");
      verifyHsSingleTask(info, task);
    }
  }
}