Java Code Examples for org.codehaus.jettison.json.JSONException

The following examples show how to use org.codehaus.jettison.json.JSONException. 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
Source Project: big-c   Source File: TestRMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
public void verifyAppInfo(JSONObject info, RMApp app) throws JSONException,
    Exception {

  assertEquals("incorrect number of elements", 27, info.length());

  verifyAppInfoGeneric(app, info.getString("id"), info.getString("user"),
      info.getString("name"), info.getString("applicationType"),
      info.getString("queue"), info.getString("state"),
      info.getString("finalStatus"), (float) info.getDouble("progress"),
      info.getString("trackingUI"), info.getString("diagnostics"),
      info.getLong("clusterId"), info.getLong("startedTime"),
      info.getLong("finishedTime"), info.getLong("elapsedTime"),
      info.getString("amHostHttpAddress"), info.getString("amContainerLogs"),
      info.getInt("allocatedMB"), info.getInt("allocatedVCores"),
      info.getInt("runningContainers"), 
      info.getInt("preemptedResourceMB"),
      info.getInt("preemptedResourceVCores"),
      info.getInt("numNonAMContainerPreempted"),
      info.getInt("numAMContainerPreempted"));
}
 
Example 2
Source Project: big-c   Source File: TestRMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
public void verifyAppAttemptInfoGeneric(RMAppAttempt appAttempt, int id,
    long startTime, String containerId, String nodeHttpAddress, String nodeId,
    String logsLink, String user)
        throws JSONException, Exception {

  assertEquals("id doesn't match", appAttempt.getAppAttemptId()
      .getAttemptId(), id);
  assertEquals("startedTime doesn't match", appAttempt.getStartTime(),
      startTime);
  WebServicesTestUtils.checkStringMatch("containerId", appAttempt
      .getMasterContainer().getId().toString(), containerId);
  WebServicesTestUtils.checkStringMatch("nodeHttpAddress", appAttempt
      .getMasterContainer().getNodeHttpAddress(), nodeHttpAddress);
  WebServicesTestUtils.checkStringMatch("nodeId", appAttempt
      .getMasterContainer().getNodeId().toString(), nodeId);
  assertTrue("logsLink doesn't match", logsLink.startsWith("//"));
  assertTrue(
      "logsLink doesn't contain user info", logsLink.endsWith("/"
      + user));
}
 
Example 3
Source Project: hadoop   Source File: TestRMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
public void verifyAppInfo(JSONObject info, RMApp app) throws JSONException,
    Exception {

  assertEquals("incorrect number of elements", 30, info.length());

  verifyAppInfoGeneric(app, info.getString("id"), info.getString("user"),
      info.getString("name"), info.getString("applicationType"),
      info.getString("queue"), info.getString("state"),
      info.getString("finalStatus"), (float) info.getDouble("progress"),
      info.getString("trackingUI"), info.getString("diagnostics"),
      info.getLong("clusterId"), info.getLong("startedTime"),
      info.getLong("finishedTime"), info.getLong("elapsedTime"),
      info.getString("amHostHttpAddress"), info.getString("amContainerLogs"),
      info.getInt("allocatedMB"), info.getInt("allocatedVCores"), info.getInt("allocatedGCores"),
      info.getInt("runningContainers"), 
      info.getInt("preemptedResourceMB"),
      info.getInt("preemptedResourceVCores"), info.getInt("preemptedResourceGCores"),
      info.getInt("numNonAMContainerPreempted"),
      info.getInt("numAMContainerPreempted"));
}
 
Example 4
Source Project: hadoop   Source File: TestAMWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobIdSlash() 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 + "/").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("job");
    verifyAMJob(info, jobsMap.get(id));
  }
}
 
Example 5
Source Project: nifi   Source File: ExecuteSparkInteractive.java    License: Apache License 2.0 6 votes vote down vote up
private JSONObject readJSONObjectFromUrlPOST(String urlString, LivySessionService livySessionService, Map<String, String> headers, String payload)
    throws IOException, JSONException, SessionManagerException {
    HttpClient httpClient = livySessionService.getConnection();

    HttpPost request = new HttpPost(urlString);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        request.addHeader(entry.getKey(), entry.getValue());
    }
    HttpEntity httpEntity = new StringEntity(payload);
    request.setEntity(httpEntity);
    HttpResponse response = httpClient.execute(request);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase());
    }

    InputStream content = response.getEntity().getContent();
    return readAllIntoJSONObject(content);
}
 
Example 6
Source Project: incubator-atlas   Source File: AtlasClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get an entity given the entity id
 * @param entityType entity type name
 * @param attribute qualified name of the entity
 * @param value
 * @return result object
 * @throws AtlasServiceException
 */
public Referenceable getEntity(final String entityType, final String attribute, final String value)
        throws AtlasServiceException {
    JSONObject jsonResponse = callAPIWithRetries(API.GET_ENTITY, null, new ResourceCreator() {
        @Override
        public WebResource createResource() {
            WebResource resource = getResource(API.GET_ENTITY);
            resource = resource.queryParam(TYPE, entityType);
            resource = resource.queryParam(ATTRIBUTE_NAME, attribute);
            resource = resource.queryParam(ATTRIBUTE_VALUE, value);
            return resource;
        }
    });
    try {
        String entityInstanceDefinition = jsonResponse.getString(AtlasClient.DEFINITION);
        return InstanceSerialization.fromJsonReferenceable(entityInstanceDefinition, true);
    } catch (JSONException e) {
        throw new AtlasServiceException(API.GET_ENTITY, e);
    }
}
 
Example 7
Source Project: jettison   Source File: BadgerFishXMLStreamWriter.java    License: Apache License 2.0 6 votes vote down vote up
public void writeCharacters(String text) throws XMLStreamException {
	text = text.trim();
	if (text.length() == 0) {
	    return;
	}
    try {
        Object o = getCurrentNode().opt("$");
        if (o instanceof JSONArray) {
            ((JSONArray) o).put(text);
        } else if (o instanceof String) {
            JSONArray arr = new JSONArray();
            arr.put(o);
            arr.put(text);
            getCurrentNode().put("$", arr);
        } else {
            getCurrentNode().put("$", text);
        }
    } catch (JSONException e) {
        throw new XMLStreamException(e);
    }
}
 
Example 8
Source Project: tez   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse events from json
 *
 * @param eventNodes
 * @param eventList
 * @throws JSONException
 */
public static void parseEvents(JSONArray eventNodes, List<Event> eventList) throws
    JSONException {
  if (eventNodes == null) {
    return;
  }
  for (int i = 0; i < eventNodes.length(); i++) {
    JSONObject eventNode = eventNodes.optJSONObject(i);
    final String eventInfo = eventNode.optString(Constants.EVENT_INFO);
    final String eventType = eventNode.optString(Constants.EVENT_TYPE);
    final long time = eventNode.optLong(Constants.EVENT_TIME_STAMP);

    Event event = new Event(eventInfo, eventType, time);

    eventList.add(event);

  }
}
 
Example 9
Source Project: big-c   Source File: TestRMWebServices.java    License: Apache License 2.0 6 votes vote down vote up
public void verifyClusterSchedulerFifoGeneric(String type, String state,
    float capacity, float usedCapacity, int minQueueCapacity,
    int maxQueueCapacity, int numNodes, int usedNodeCapacity,
    int availNodeCapacity, int totalNodeCapacity, int numContainers)
    throws JSONException, Exception {

  assertEquals("type doesn't match", "fifoScheduler", type);
  assertEquals("qstate doesn't match", QueueState.RUNNING.toString(), state);
  assertEquals("capacity doesn't match", 1.0, capacity, 0.0);
  assertEquals("usedCapacity doesn't match", 0.0, usedCapacity, 0.0);
  assertEquals(
      "minQueueMemoryCapacity doesn't match",
      YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
      minQueueCapacity);
  assertEquals("maxQueueMemoryCapacity doesn't match",
      YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB,
      maxQueueCapacity);
  assertEquals("numNodes doesn't match", 0, numNodes);
  assertEquals("usedNodeCapacity doesn't match", 0, usedNodeCapacity);
  assertEquals("availNodeCapacity doesn't match", 0, availNodeCapacity);
  assertEquals("totalNodeCapacity doesn't match", 0, totalNodeCapacity);
  assertEquals("numContainers doesn't match", 0, numContainers);

}
 
Example 10
Source Project: cloud-espm-v2   Source File: CustomerODataIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test Delete Customer via URL.
 * 
 * @throws JSONException
 * @throws IOException
 */
@Test
public void testDeleteCustomerViaURL() throws IOException, JSONException {
	String email = rand.nextInt(200) + "@sap.com";
	String customerXml = StreamHelper.readFromFile(FILENAME);
	customerXml = customerXml.replace(
			"<d:EmailAddress>email</d:EmailAddress>", "<d:EmailAddress>"
					+ email + "</d:EmailAddress>");
	String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME,
			customerXml, false);
	HttpResponse resp = RequestExecutionHelper.executeGetRequest(
			ENTITY_NAME + "?$format=json&$filter=CustomerId%20eq%20'" + id
					+ "'", true);
	assertEquals("Customer not persisted", HttpURLConnection.HTTP_OK,
			resp.getResponseCode());
	resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('"
			+ id + "')", true);
	assertEquals(
			"Unable to delete Customer via REST or incorrect HTTP Response Code:"
					+ resp.getResponseMessage(),
			HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode());
}
 
Example 11
Source Project: jettison   Source File: MappedXMLStreamReader.java    License: Apache License 2.0 6 votes vote down vote up
public MappedXMLStreamReader(JSONObject obj, MappedNamespaceConvention con)
        throws JSONException, XMLStreamException {
    String rootName = (String) obj.keys().next();

    this.convention = con;
    this.nodes = new FastStack();
    this.ctx = con;
    Object top = obj.get(rootName);
    if (top instanceof JSONObject) {
        this.node = new Node(null, rootName, (JSONObject)top, convention);
    } else if (top instanceof JSONArray && !(((JSONArray)top).length() == 1 && ((JSONArray)top).get(0).equals(""))) {
        if (con.isRootElementArrayWrapper()) {
            this.node = new Node(null, rootName, obj, convention);
        } else {
            this.node = new Node(null, rootName, ((JSONArray)top).getJSONObject(0), convention);
        }
    } else {
        node = new Node(rootName, convention);
        convention.processAttributesAndNamespaces(node, obj);
        currentValue = JSONObject.NULL.equals(top) ? null : top.toString();
    }
    nodes.push(node);
    event = START_DOCUMENT;
}
 
Example 12
Source Project: hadoop   Source File: TestHsWebServicesJobsQuery.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryFinishTimeEndInvalidformat() throws JSONException,
    Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs").queryParam("finishedTimeEnd", "efsd")
      .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: Invalid number format: For input string: \"efsd\"",
          message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example 13
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 14
Source Project: big-c   Source File: TestAMWebServicesTasks.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTasksQueryReduce() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    String type = "r";
    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).path("tasks").queryParam("type", type)
        .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", 1, arr.length());
    verifyAMTask(arr, jobsMap.get(id), type);
  }
}
 
Example 15
Source Project: hadoop   Source File: TestNMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNodeAppsState() throws JSONException, Exception {
  WebResource r = resource();
  Application app = new MockApp(1);
  nmContext.getApplications().put(app.getAppId(), app);
  addAppContainers(app);
  MockApp app2 = new MockApp("foo", 1234, 2);
  nmContext.getApplications().put(app2.getAppId(), app2);
  HashMap<String, String> hash2 = addAppContainers(app2);
  app2.setState(ApplicationState.RUNNING);

  ClientResponse response = r.path("ws").path("v1").path("node").path("apps")
      .queryParam("state", ApplicationState.RUNNING.toString())
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);

  JSONObject info = json.getJSONObject("apps");
  assertEquals("incorrect number of elements", 1, info.length());
  JSONArray appInfo = info.getJSONArray("app");
  assertEquals("incorrect number of elements", 1, appInfo.length());
  verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);

}
 
Example 16
Source Project: big-c   Source File: TestRMWebServicesNodes.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleNodesXML() throws JSONException, Exception {
  rm.start();
  WebResource r = resource();
  MockNM nm1 = rm.registerNode("h1:1234", 5120);
  // MockNM nm2 = rm.registerNode("h2:1235", 5121);
  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("nodes").path("h1:1234").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 nodes = dom.getElementsByTagName("node");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyNodesXML(nodes, nm1);
  rm.stop();
}
 
Example 17
Source Project: big-c   Source File: TestNMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNodeSingleAppsXML() 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);

  ClientResponse response = r.path("ws").path("v1").path("node").path("apps")
      .path(app.getAppId().toString() + "/")
      .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 nodes = dom.getElementsByTagName("app");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyNodeAppInfoXML(nodes, app, hash);
}
 
Example 18
Source Project: hadoop   Source File: TestHsWebServicesTasks.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTaskIdCountersSlash() 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/").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("jobTaskCounters");
      verifyHsJobTaskCounters(info, task);
    }
  }
}
 
Example 19
Source Project: big-c   Source File: TestAMWebServicesAttempts.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTaskAttemptsDefault() 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("mapreduce")
          .path("jobs").path(jobId).path("tasks").path(tid).path("attempts")
          .get(ClientResponse.class);
      assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
      JSONObject json = response.getEntity(JSONObject.class);
      verifyAMTaskAttempts(json, task);
    }
  }
}
 
Example 20
Source Project: ezScrum   Source File: LoginApi.java    License: GNU General Public License v2.0 6 votes vote down vote up
@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public String login(String loginJson) throws JSONException {
	// get JSONObject
	JSONObject jsonEntity = new JSONObject(loginJson);
	// confirm User Account
	AccountObject account = AccountObject.confirmAccount(jsonEntity.getString(TokenEnum.USERNAME), jsonEntity.getString(TokenEnum.PASSWORD));
	
	if (account == null) {
		return "";
	}
	
	// create Token Object
	TokenObject token = new TokenObject(account.getId(), jsonEntity.getString(TokenEnum.PLATFORM_TYPE));
	token.save();
	
	// create Response JSONObject
	JSONObject respEntity = new JSONObject();
	respEntity.put(TokenEnum.PUBLIC_TOKEN, token.getPublicToken())
	          .put(TokenEnum.PRIVATE_TOKEN, token.getPrivateToken())
	          .put(TokenEnum.SERVER_TIME, System.currentTimeMillis());
	return respEntity.toString();
}
 
Example 21
Source Project: hadoop   Source File: TestRMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAppsQueryStatesNone() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  rm.submitApp(CONTAINER_MB);
  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps")
      .queryParam("states", YarnApplicationState.RUNNING.toString())
      .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());
  assertEquals("apps is not null", JSONObject.NULL, json.get("apps"));
  rm.stop();
}
 
Example 22
Source Project: big-c   Source File: TestHsWebServicesJobConf.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("history").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");
    verifyHsJobConf(info, jobsMap.get(id));
  }
}
 
Example 23
Source Project: big-c   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 24
Source Project: cloud-espm-v2   Source File: StockODataIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test Select Service Query Option via URL.
 * 
 * @throws IOException
 * @throws JSONException
 */
@Test
public void testStockUrlSelect() throws IOException, JSONException {
	HttpResponse resp = RequestExecutionHelper
			.executeGetRequest(
					ENTITY_NAME
							+ "?$format=json&$orderby=ProductId%20desc&$skip=1&$top=1&$select=MinStock,Quantity",
					true);
	JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp
			.getBody());
	assertNotNull("Unable to parse JSON response", ja);
	assertTrue(
			"Selected property Quantity does not exist in the odata service",
			resp.getBody().contains("Quantity"));
	assertTrue(
			"Non selected property LotSize still exists in the odata service",
			!resp.getBody().contains("LotSize"));
}
 
Example 25
Source Project: big-c   Source File: TestHsWebServicesJobsQuery.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryStartTimeInvalidformat() throws JSONException,
    Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs").queryParam("startedTimeBegin", "efsd")
      .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: Invalid number format: For input string: \"efsd\"",
          message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example 26
Source Project: hadoop   Source File: TestAMWebServicesAttempts.java    License: Apache License 2.0 6 votes vote down vote up
public void verifyAMJobTaskAttemptCounters(JSONObject info, TaskAttempt att)
    throws JSONException {

  assertEquals("incorrect number of elements", 2, info.length());

  WebServicesTestUtils.checkStringMatch("id", MRApps.toString(att.getID()),
      info.getString("id"));

  // just do simple verification of fields - not data is correct
  // in the fields
  JSONArray counterGroups = info.getJSONArray("taskAttemptCounterGroup");
  for (int i = 0; i < counterGroups.length(); i++) {
    JSONObject counterGroup = counterGroups.getJSONObject(i);
    String name = counterGroup.getString("counterGroupName");
    assertTrue("name not set", (name != null && !name.isEmpty()));
    JSONArray counters = counterGroup.getJSONArray("counter");
    for (int j = 0; j < counters.length(); j++) {
      JSONObject counter = counters.getJSONObject(j);
      String counterName = counter.getString("name");
      assertTrue("name not set",
          (counterName != null && !counterName.isEmpty()));
      long value = counter.getLong("value");
      assertTrue("value  >= 0", value >= 0);
    }
  }
}
 
Example 27
Source Project: cloud-espm-v2   Source File: SalesOrderHeaderODataIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test Get SalesOrderHeader Details by Anonymous user.
 * 
 * @throws IOException
 * @throws JSONException
 */
@Test
public void testGetSalesOrderHeaderByAnonymous() throws IOException,
		JSONException {
	String salesOrderXml = StreamHelper.readFromFile(SO_FILENAME);
	String id = RequestExecutionHelper.createSalesOrderViaREST(ENTITY_NAME,
			salesOrderXml, false);
	HttpResponse resp = RequestExecutionHelper.executeGetRequest(
			ENTITY_NAME + "?$format=json&$filter=SalesOrderId%20eq%20'"
					+ id + "'", false);
	assertEquals(
			"SalesOrderHeader OData service not secured for HTTP GET request",
			HttpURLConnection.HTTP_UNAUTHORIZED, resp.getResponseCode());
	resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('"
			+ id + "')", true);
	assertEquals(
			"Unable to delete Sales Order Header via REST or incorrect HTTP Response Code:"
					+ resp.getResponseMessage(),
			HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode());
}
 
Example 28
Source Project: big-c   Source File: TestRMWebServicesAppsModification.java    License: Apache License 2.0 6 votes vote down vote up
protected String validateGetNewApplicationResponse(ClientResponse resp)
    throws JSONException, ParserConfigurationException, IOException,
    SAXException {
  String ret = "";
  if (resp.getType().equals(MediaType.APPLICATION_JSON_TYPE)) {
    JSONObject json = resp.getEntity(JSONObject.class);
    ret = validateGetNewApplicationJsonResponse(json);
  } else if (resp.getType().equals(MediaType.APPLICATION_XML_TYPE)) {
    String xml = resp.getEntity(String.class);
    ret = validateGetNewApplicationXMLResponse(xml);
  } else {
    // we should not be here
    assertTrue(false);
  }
  return ret;
}
 
Example 29
Source Project: batfish   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads question from a JSON
 *
 * @param questionText Question JSON Text
 * @param questionSource JSON key of question or file path of JSON
 * @return question loaded as a {@link JSONObject}
 * @throws BatfishException if question does not have instanceName or question cannot be parsed
 */
static JSONObject loadQuestionFromText(String questionText, String questionSource) {
  try {
    JSONObject questionObj = new JSONObject(questionText);
    if (questionObj.has(BfConsts.PROP_INSTANCE) && !questionObj.isNull(BfConsts.PROP_INSTANCE)) {
      JSONObject instanceDataObj = questionObj.getJSONObject(BfConsts.PROP_INSTANCE);
      String instanceDataStr = instanceDataObj.toString();
      InstanceData instanceData =
          BatfishObjectMapper.mapper()
              .readValue(instanceDataStr, new TypeReference<InstanceData>() {});
      validateInstanceData(instanceData);
      return questionObj;
    } else {
      throw new BatfishException(
          String.format("Question in %s has no instance data", questionSource));
    }
  } catch (JSONException | IOException e) {
    throw new BatfishException("Failed to process question", e);
  }
}
 
Example 30
Source Project: hadoop   Source File: TestHsWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobCountersSlash() 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));
  }
}