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

The following examples show how to use org.codehaus.jettison.json.JSONObject. 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: 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 2
Source Project: batfish   Source File: MainTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReadQuestionTemplateDuplicate() throws Exception {
  Map<String, String> questionTemplates = Maps.newHashMap();
  // already existing question template with key duplicate_template
  questionTemplates.put(DUPLICATE_TEMPLATE_NAME, "template_body");

  JSONObject testQuestion = new JSONObject();
  testQuestion.put(
      "instance",
      new JSONObject()
          .put("instanceName", DUPLICATE_TEMPLATE_NAME)
          .put("description", "test question description"));
  Path questionJsonPath = _folder.newFile("testquestion.json").toPath();
  CommonUtil.writeFile(questionJsonPath, testQuestion.toString());

  readQuestionTemplate(questionJsonPath, questionTemplates);

  assertThat(questionTemplates.keySet(), hasSize(1));
  // the value of the question template with key duplicate_template should be replaced now
  assertThat(
      questionTemplates,
      IsMapContaining.hasEntry(
          DUPLICATE_TEMPLATE_NAME,
          "{\"instance\":{\"instanceName\":\"duplicate_template\",\"description\":\"test question description\"}}"));
}
 
Example 3
Source Project: attic-apex-core   Source File: StramWebServices.java    License: Apache License 2.0 6 votes vote down vote up
@POST
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId:\\d+}/" + PATH_RECORDINGS_START)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject startRecording(@PathParam("opId") int opId, String content) throws JSONException
{
  init();
  LOG.debug("Start recording on {} requested", opId);
  JSONObject response = new JSONObject();
  long numWindows = 0;
  if (StringUtils.isNotBlank(content)) {
    JSONObject r = new JSONObject(content);
    numWindows = r.optLong("numWindows", 0);
  }
  String id = getTupleRecordingId();
  dagManager.startRecording(id, opId, null, numWindows);
  response.put("id", id);
  return response;
}
 
Example 4
Source Project: Crawer   Source File: AllPriceMapper.java    License: MIT License 6 votes vote down vote up
/**
 * 对象转成json字符串
 * @param mapper
 * @return
 * @throws JSONException
 */
private static String bean2Json(AllPriceMapper mapper) throws JSONException{
	
	JSONArray ja = new JSONArray();
	JSONObject jo = new JSONObject(); 
	
	jo.put(DD_NET, mapper.getDD()==null?"":mapper.getDD());
	jo.put(DB_NET, mapper.getDB()==null?"":mapper.getDB());
	jo.put(AM_NET, mapper.getAM()==null?"":mapper.getAM());
	jo.put(JD_NET, mapper.getJD()==null?"":mapper.getJD());
	jo.put(PUB_NET, mapper.getPUB()==null?"":mapper.getPUB());
	
	ja.put(jo);
	ja.put(new JSONObject());
	return jo.toString();
}
 
Example 5
Source Project: big-c   Source File: TestRMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAppsQueryFinalStatus() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  RMApp app1 = rm.submitApp(CONTAINER_MB);
  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps").queryParam("finalStatus", FinalApplicationStatus.UNDEFINED.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());
  System.out.println(json.toString());
  JSONObject apps = json.getJSONObject("apps");
  assertEquals("incorrect number of elements", 1, apps.length());
  JSONArray array = apps.getJSONArray("app");
  assertEquals("incorrect number of elements", 1, array.length());
  verifyAppInfo(array.getJSONObject(0), app1);
  rm.stop();
}
 
Example 6
@Test
public void testSearchByDSL() throws Exception {
    String dslQuery = "from "+ DATABASE_TYPE + " name=\"" + dbName + "\"";
    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("query", dslQuery);
    JSONObject response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH_DSL, queryParams);

    Assert.assertNotNull(response);
    Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

    assertEquals(response.getString("query"), dslQuery);
    assertEquals(response.getString("queryType"), "dsl");

    JSONArray results = response.getJSONArray(AtlasClient.RESULTS);
    assertNotNull(results);
    assertEquals(results.length(), 1);

    int numRows = response.getInt(AtlasClient.COUNT);
    assertEquals(numRows, 1);
}
 
Example 7
Source Project: hadoop   Source File: TestAMWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobId() 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 8
Source Project: hadoop   Source File: TestHsWebServicesTasks.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("history")
        .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());
    verifyHsTask(arr, jobsMap.get(id), type);
  }
}
 
Example 9
Source Project: big-c   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 10
Source Project: hadoop   Source File: TestRMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAppsQueryStateNone() 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("state", 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 11
Source Project: hadoop   Source File: TestNMWebServicesApps.java    License: Apache License 2.0 6 votes vote down vote up
public void testNodeSingleAppHelper(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);

  ClientResponse response = r.path("ws").path("v1").path("node").path("apps")
      .path(app.getAppId().toString()).accept(media)
      .get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  verifyNodeAppInfo(json.getJSONObject("app"), app, hash);
}
 
Example 12
Source Project: Bats   Source File: StramWebServices.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/attributes")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getOperatorAttributes(@PathParam("operatorName") String operatorName, @QueryParam("attributeName") String attributeName)
{
  init();
  OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName);
  if (logicalOperator == null) {
    throw new NotFoundException();
  }
  HashMap<String, String> map = new HashMap<>();
  for (Map.Entry<Attribute<?>, Object> entry : dagManager.getOperatorAttributes(operatorName).entrySet()) {
    if (attributeName == null || entry.getKey().getSimpleName().equals(attributeName)) {
      Map.Entry<Attribute<Object>, Object> entry1 = (Map.Entry<Attribute<Object>, Object>)(Map.Entry)entry;
      map.put(entry1.getKey().getSimpleName(), entry1.getKey().codec.toString(entry1.getValue()));
    }
  }
  return new JSONObject(map);
}
 
Example 13
Source Project: attic-apex-core   Source File: TypeDiscoveryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPortAttributes() throws JSONException, IllegalAccessException
{
  JSONArray portAttributes = TypeDiscoverer.getPortAttributes().getJSONArray("attributes");
  Map<String, JSONObject> attributesMap = Maps.newHashMap();
  for (int i = 0; i < portAttributes.length(); i++) {
    attributesMap.put(portAttributes.getJSONObject(i).getString("name"), portAttributes.getJSONObject(i));
  }
  JSONObject queueCapacityAttr = attributesMap.get("QUEUE_CAPACITY");
  Assert.assertNotNull("queue capacity", queueCapacityAttr);
  Assert.assertEquals("queue capacity type", "java.lang.Integer", queueCapacityAttr.getString("type"));
  Assert.assertEquals("default queue capacity", "1024", queueCapacityAttr.getString("default"));

  JSONObject streamCodecAttr = attributesMap.get("STREAM_CODEC");
  Assert.assertNotNull("stream codec", streamCodecAttr);
  Assert.assertEquals("stream codec type", "com.datatorrent.api.StreamCodec", streamCodecAttr.getString("type"));
  Assert.assertNotNull("type args", streamCodecAttr.getJSONArray("typeArgs"));
}
 
Example 14
Source Project: big-c   Source File: TestHsWebServicesAttempts.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("history")
          .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);
      verifyHsTaskAttempts(json, task);
    }
  }
}
 
Example 15
Source Project: big-c   Source File: TestHsWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobAttemptsSlash() 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("jobattempts/")
        .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("jobAttempts");
    verifyHsJobAttempts(info, appContext.getJob(id));
  }
}
 
Example 16
Source Project: hadoop   Source File: TestAMWebServicesJobs.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobAttemptsDefault() 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("jobattempts")
        .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("jobAttempts");
    verifyJobAttempts(info, jobsMap.get(id));
  }
}
 
Example 17
Source Project: jettison   Source File: MappedXMLStreamReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testStreamReaderNullTextAsNull() throws Exception {
    JSONObject obj = 
        new JSONObject("{ " +
                       "\"root\" : { " +
                       "\"child1\" : \"null\"" +
                       "} }");
    Configuration c = new Configuration();
    MappedNamespaceConvention con = new MappedNamespaceConvention(c);
    XMLStreamReader reader = new MappedXMLStreamReader(obj, con);
    
    assertEquals(XMLStreamReader.START_ELEMENT, reader.next());
    assertEquals("root", reader.getName().getLocalPart());
    assertEquals(XMLStreamReader.START_ELEMENT, reader.next());
    assertEquals("child1", reader.getName().getLocalPart());
    assertEquals(XMLStreamReader.CHARACTERS, reader.next());
    assertEquals(null, reader.getText());
    assertEquals(XMLStreamReader.END_ELEMENT, reader.next());
    assertEquals("child1", reader.getName().getLocalPart());
    assertEquals(XMLStreamReader.END_ELEMENT, reader.next());
    assertEquals("root", reader.getName().getLocalPart()); 
}
 
Example 18
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 19
/****
 * 更新story 至 Product Backlog
 * 
 * @param boolean success
 * @return updateStoryResponse
 */
public String updateStory(boolean success) {
	JSONObject updateStoryResponse = new JSONObject();

	try {
		if (success) {
			updateStoryResponse.put("status", "SUCCESS");
		} else {
			updateStoryResponse.put("status", "FAILED");
		}
	} catch (JSONException e) {
		return "{\"status\": \"FAILED\"}";
	}

	return updateStoryResponse.toString();
}
 
Example 20
Source Project: big-c   Source File: TestAHSWebServices.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleApp() throws Exception {
  ApplicationId appId = ApplicationId.newInstance(0, 1);
  WebResource r = resource();
  ClientResponse response =
      r.path("ws").path("v1").path("applicationhistory").path("apps")
        .path(appId.toString())
        .queryParam("user.name", USERS[round])
        .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 app = json.getJSONObject("app");
  assertEquals(appId.toString(), app.getString("appId"));
  assertEquals("test app", app.get("name"));
  assertEquals(round == 0 ? "test diagnostics info" : "",
      app.get("diagnosticsInfo"));
  assertEquals("test queue", app.get("queue"));
  assertEquals("user1", app.get("user"));
  assertEquals("test app type", app.get("type"));
  assertEquals(FinalApplicationStatus.UNDEFINED.toString(),
    app.get("finalAppStatus"));
  assertEquals(YarnApplicationState.FINISHED.toString(), app.get("appState"));
}
 
Example 21
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 22
Source Project: cloud-espm-v2   Source File: SalesOrderHeaderODataIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test Create Sales Order Header via URL.
 * 
 * @throws IOException
 * @throws JSONException
 */
@Test
public void testCreateSalesOrderHeaderViaREST() throws IOException,
		JSONException {
	String salesOrderHeaderXml = StreamHelper.readFromFile(SOH_FILENAME);
	String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME,
			salesOrderHeaderXml, false);
	HttpResponse resp = RequestExecutionHelper.executeGetRequest(
			ENTITY_NAME + "?$format=json&$filter=SalesOrderId%20eq%20'"
					+ id + "'", true);
	assertEquals("Sales Order not persisted", HttpURLConnection.HTTP_OK,
			resp.getResponseCode());
	JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp
			.getBody());
	assertNotNull("Unable to parse JSON response", ja);
	JSONObject jo = (JSONObject) ja.get(0);
	assertEquals("Added Sales Order Header via REST not persisted in db",
			id, jo.getString("SalesOrderId"));
	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 23
Source Project: big-c   Source File: TestNMWebServices.java    License: Apache License 2.0 6 votes vote down vote up
public void verifyNodeInfo(JSONObject json) throws JSONException, Exception {
  assertEquals("incorrect number of elements", 1, json.length());
  JSONObject info = json.getJSONObject("nodeInfo");
  assertEquals("incorrect number of elements", 16, info.length());
  verifyNodeInfoGeneric(info.getString("id"), info.getString("healthReport"),
      info.getLong("totalVmemAllocatedContainersMB"),
      info.getLong("totalPmemAllocatedContainersMB"),
      info.getLong("totalVCoresAllocatedContainers"),
      info.getBoolean("vmemCheckEnabled"),
      info.getBoolean("pmemCheckEnabled"),
      info.getLong("lastNodeUpdateTime"), info.getBoolean("nodeHealthy"),
      info.getString("nodeHostName"), info.getString("hadoopVersionBuiltOn"),
      info.getString("hadoopBuildVersion"), info.getString("hadoopVersion"),
      info.getString("nodeManagerVersionBuiltOn"),
      info.getString("nodeManagerBuildVersion"),
      info.getString("nodeManagerVersion"));

}
 
Example 24
Source Project: hadoop   Source File: TestAMWebServicesTasks.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("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());

    verifyAMTask(arr, jobsMap.get(id), null);
  }
}
 
Example 25
Source Project: attic-apex-core   Source File: StramWebServicesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoDefault() throws JSONException, Exception
{
  WebResource r = resource();
  ClientResponse response = r.path(StramWebServices.PATH)
      .path(StramWebServices.PATH_INFO + "/").get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  assertTrue("Too few elements", json.length() > 1);
  verifyAMInfo(json, appContext);
}
 
Example 26
Source Project: zeppelin   Source File: ZeppelinhubClient.java    License: Apache License 2.0 5 votes vote down vote up
boolean runAllParagraph(String noteId, String hubMsg) {
  LOG.info("Running paragraph with noteId {}", noteId);
  try {
    JSONObject data = new JSONObject(hubMsg);
    if (data.equals(JSONObject.NULL) || !(data.get("data") instanceof JSONArray)) {
      LOG.error("Wrong \"data\" format for RUN_NOTEBOOK");
      return false;
    }
    Client client = Client.getInstance();
    if (client == null) {
      LOG.warn("Base client isn't initialized, returning");
      return false;
    }
    Message zeppelinMsg = new Message(OP.RUN_PARAGRAPH);

    JSONArray paragraphs = data.getJSONArray("data");
    String principal = data.getJSONObject("meta").getString("owner");
    for (int i = 0; i < paragraphs.length(); i++) {
      if (!(paragraphs.get(i) instanceof JSONObject)) {
        LOG.warn("Wrong \"paragraph\" format for RUN_NOTEBOOK");
        continue;
      }
      zeppelinMsg.data = gson.fromJson(paragraphs.getString(i), 
          new TypeToken<Map<String, Object>>(){}.getType());
      zeppelinMsg.principal = principal;
      zeppelinMsg.ticket = TicketContainer.instance.getTicket(principal);
      client.relayToZeppelin(zeppelinMsg, noteId);
      LOG.info("\nSending RUN_PARAGRAPH message to Zeppelin ");
    }
  } catch (JSONException e) {
    LOG.error("Failed to parse RUN_NOTEBOOK message from ZeppelinHub ", e);
    return false;
  }
  return true;
}
 
Example 27
Source Project: hadoop   Source File: TestHsWebServicesJobsQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJobsQueryFinishTimeBeginEnd() throws JSONException, Exception {
  WebResource r = resource();

  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  int size = jobsMap.size();
  // figure out the mid end time - we expect atleast 3 jobs
  ArrayList<Long> finishTime = new ArrayList<Long>(size);
  for (Map.Entry<JobId, Job> entry : jobsMap.entrySet()) {
    finishTime.add(entry.getValue().getReport().getFinishTime());
  }
  Collections.sort(finishTime);

  assertTrue("Error we must have atleast 3 jobs", size >= 3);
  long midFinishTime = finishTime.get(size - 2);

  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("finishedTimeBegin", String.valueOf(40000))
      .queryParam("finishedTimeEnd", String.valueOf(midFinishTime))
      .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 jobs = json.getJSONObject("jobs");
  JSONArray arr = jobs.getJSONArray("job");
  assertEquals("incorrect number of elements", size - 1, arr.length());
}
 
Example 28
Source Project: hadoop   Source File: TestNMWebServicesApps.java    License: Apache License 2.0 5 votes vote down vote up
public void verifyNodeAppInfo(JSONObject info, Application app,
    HashMap<String, String> hash) throws JSONException, Exception {
  assertEquals("incorrect number of elements", 4, info.length());

  verifyNodeAppInfoGeneric(app, info.getString("id"),
      info.getString("state"), info.getString("user"));

  JSONArray containerids = info.getJSONArray("containerids");
  for (int i = 0; i < containerids.length(); i++) {
    String id = containerids.getString(i);
    assertEquals("extra containerid: " + id, id, hash.remove(id));
  }
  assertTrue("missing containerids", hash.isEmpty());
}
 
Example 29
Source Project: ezScrum   Source File: TaskWebService.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 編輯 task (TaskInfo 可能不完全,待檢查!!!)
 * @param taskJson
 * @return
 * @throws JSONException 
 */
public String updateTask(String taskJSonString) throws JSONException {
	JSONObject taskJSon = new JSONObject(taskJSonString);
	TaskInfo taskInfo = new TaskInfo();
	taskInfo.taskId = Long.parseLong(taskJSon.getString("id"));
	taskInfo.name = taskJSon.getString("name");
	taskInfo.estimate = Integer.parseInt(taskJSon.getString("estimate"));
	taskInfo.remains = Integer.parseInt(taskJSon.getString("remains"));
	taskInfo.notes = taskJSon.getString("notes");
	taskInfo.actual = Integer.parseInt(taskJSon.getString("actual"));
	
	mSprintBacklogHelper.updateTask(taskInfo, taskJSon.getString("handler"), taskJSon.getString("partner"));
	return "true";
}
 
Example 30
/**
 * Get executor by app name.
 * 
 * @param appName app name
 * @return executor state info
 * @throws JSONException parse json exception
 */
public Collection<ExecutorStateInfo> executors(final String appName) throws JSONException {
    return Collections2.transform(findExecutors(fetch(stateUrl).getJSONArray("frameworks"), appName), new Function<JSONObject, ExecutorStateInfo>() {
        @Override
        public ExecutorStateInfo apply(final JSONObject input) {
            try {
                return ExecutorStateInfo.builder().id(getExecutorId(input)).slaveId(input.getString("slave_id")).build();
            } catch (final JSONException ex) {
                throw new RuntimeException(ex);
            }
        }
    });
}