org.codehaus.jettison.json.JSONArray Java Examples

The following examples show how to use org.codehaus.jettison.json.JSONArray. 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: TestHsWebServicesJobsQuery.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryStartTimeEnd() throws JSONException, Exception {
  WebResource r = resource();
  // the mockJobs start time is the current time - some random amount
  Long now = System.currentTimeMillis();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("startedTimeEnd", String.valueOf(now))
      .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", 3, arr.length());
}
 
Example #2
Source File: StockODataIT.java    From cloud-espm-v2 with 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 #3
Source File: Compiler.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
private void prepareCompTypes(Set<String> neededTypes) {
  try {
    JSONArray buildInfo = new JSONArray(Resources.toString(
        Compiler.class.getResource(COMP_BUILD_INFO), Charsets.UTF_8));

    Set<String> allSimpleTypes = Sets.newHashSet();
    for (int i = 0; i < buildInfo.length(); ++i) {
      JSONObject comp = buildInfo.getJSONObject(i);
      allSimpleTypes.add(comp.getString("type"));
    }

    simpleCompTypes = Sets.newHashSet(neededTypes);
    simpleCompTypes.retainAll(allSimpleTypes);

    extCompTypes = Sets.newHashSet(neededTypes);
    extCompTypes.removeAll(allSimpleTypes);

  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example #4
Source File: BadgerFishXMLStreamWriter.java    From jettison with 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 #5
Source File: HistoryEventJsonConversion.java    From incubator-tez with Apache License 2.0 6 votes vote down vote up
private static JSONObject convertDAGStartedEvent(DAGStartedEvent event) throws JSONException {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put(ATSConstants.ENTITY,
      event.getDagID().toString());
  jsonObject.put(ATSConstants.ENTITY_TYPE,
      EntityTypes.TEZ_DAG_ID.name());

  // Related Entities not needed as should have been done in
  // dag submission event

  // TODO decide whether this goes into different events,
  // event info or other info.
  JSONArray events = new JSONArray();
  JSONObject startEvent = new JSONObject();
  startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime());
  startEvent.put(ATSConstants.EVENT_TYPE,
      HistoryEventType.DAG_STARTED.name());
  events.put(startEvent);
  jsonObject.put(ATSConstants.EVENTS, events);

  return jsonObject;
}
 
Example #6
Source File: PermissionsInfo.java    From Bats with Apache License 2.0 6 votes vote down vote up
public JSONObject toJSONObject()
{
  JSONObject result = new JSONObject();
  JSONObject readOnly = new JSONObject();
  JSONObject readWrite = new JSONObject();
  try {
    readOnly.put("users", new JSONArray(readOnlyUsers));
    readOnly.put("roles", new JSONArray(readOnlyRoles));
    readOnly.put("everyone", readOnlyEveryone);
    readWrite.put("users", new JSONArray(readWriteUsers));
    readWrite.put("roles", new JSONArray(readWriteRoles));
    readWrite.put("everyone", readWriteEveryone);
    result.put("readOnly", readOnly);
    result.put("readWrite", readWrite);
  } catch (JSONException ex) {
    throw new RuntimeException(ex);
  }
  return result;
}
 
Example #7
Source File: TestAMWebServicesTasks.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testTasksQueryMap() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    String type = "m";
    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 #8
Source File: TestHsWebServicesJobs.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobs() throws JSONException, Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs").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", 1, arr.length());
  JSONObject info = arr.getJSONObject(0);
  Job job = appContext.getPartialJob(MRApps.toJobID(info.getString("id")));
  VerifyJobsUtils.verifyHsJobPartial(info, job);

}
 
Example #9
Source File: TestAMWebServicesJobs.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobs() throws JSONException, Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("mapreduce")
      .path("jobs").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");
  JSONObject info = arr.getJSONObject(0);
  Job job = appContext.getJob(MRApps.toJobID(info.getString("id")));
  verifyAMJob(info, job);

}
 
Example #10
Source File: WorkMgrService.java    From batfish with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public JSONArray getInfo() {
  _logger.info("WMS:getInfo\n");
  try {
    JSONObject map = new JSONObject();
    map.put("Service name", "Batfish coordinator");
    map.put(CoordConsts.SVC_KEY_VERSION, BatfishVersion.getVersionStatic());
    map.put("APIs", "Enter ../application.wadl (relative to your URL) to see supported methods");

    return successResponse(map);
  } catch (Exception e) {
    String stackTrace = Throwables.getStackTraceAsString(e);
    _logger.errorf("WMS:getInfo exception: %s", stackTrace);
    return failureResponse(e.getMessage());
  }
}
 
Example #11
Source File: AccumuloServiceTest.java    From OSTMap with Apache License 2.0 6 votes vote down vote up
@Test
public void testAccumuloServiceTokenSearchHashtag() throws Exception {
    //run Token Search
    System.out.println("settings file path: " + settings.getAbsolutePath());

    String fieldList = "user,text";
    String searchToken = "#katze";

    TokenSearchController tsc = new TokenSearchController();
    tsc.validateQueryParams(fieldList,searchToken);
    String result = tsc.getResultsFromAccumulo(fieldList,searchToken,settings.getAbsolutePath());

    JSONArray resultArray = new JSONArray(result);

    assertTrue(resultArray.length() == 1);
    assertEquals(tweet3Json.getString("id_str"),resultArray.getJSONObject(0).getString("id_str"));
}
 
Example #12
Source File: TestRMWebServicesApps.java    From big-c with 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 #13
Source File: AccumuloServiceTest.java    From OSTMap with Apache License 2.0 6 votes vote down vote up
@Test
public void testAccumuloServiceTokenSearch() throws Exception {
    //run Token Search
    System.out.println("settings file path: " + settings.getAbsolutePath());

    String fieldList = "user,text";
    String searchToken = "katze";

    TokenSearchController tsc = new TokenSearchController();
    tsc.validateQueryParams(fieldList,searchToken);
    String result = tsc.getResultsFromAccumulo(fieldList,searchToken,settings.getAbsolutePath());

    JSONArray resultArray = new JSONArray(result);

    assertTrue(resultArray.length() == 1);
    assertEquals(tweet3Json.getString("id_str"),resultArray.getJSONObject(0).getString("id_str"));
}
 
Example #14
Source File: TestRMWebServicesNodes.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryAll() throws Exception {
  WebResource r = resource();
  MockNM nm1 = rm.registerNode("h1:1234", 5120);
  MockNM nm2 = rm.registerNode("h2:1235", 5121);
  MockNM nm3 = rm.registerNode("h3:1236", 5122);
  rm.sendNodeStarted(nm1);
  rm.sendNodeStarted(nm3);
  rm.NMwaitForState(nm1.getNodeId(), NodeState.RUNNING);
  rm.NMwaitForState(nm2.getNodeId(), NodeState.NEW);
  rm.sendNodeLost(nm3);

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("nodes")
      .queryParam("states", Joiner.on(',').join(EnumSet.allOf(NodeState.class)))
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  JSONObject nodes = json.getJSONObject("nodes");
  assertEquals("incorrect number of elements", 1, nodes.length());
  JSONArray nodeArray = nodes.getJSONArray("node");
  assertEquals("incorrect number of elements", 3, nodeArray.length());
}
 
Example #15
Source File: SupplierODataIT.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test if Supplier URL Select Service Query Option.
 * 
 * @throws IOException
 * @throws JSONException
 */
@Test
public void testSupplierUrlSelect() throws IOException, JSONException {
	HttpResponse resp = RequestExecutionHelper
			.executeGetRequest(
					ENTITY_NAME
							+ "?$format=json&$orderby=SupplierId&$skip=1&$top=1&$select=SupplierId,Country",
					true);
	JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp
			.getBody());
	assertNotNull("Unable to parse JSON response", ja);
	ja.get(0);
	assertTrue(
			"Selected property Country does not exist in the odata service",
			resp.getBody().contains("Country"));
	assertTrue(
			"Non selected property City still exists in the odata service",
			!resp.getBody().contains("City"));
}
 
Example #16
Source File: TestHsWebServicesJobsQuery.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryState() throws JSONException, Exception {
  WebResource r = resource();
  // we only create 3 jobs and it cycles through states so we should have 3 unique states
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  String queryState = "BOGUS";
  JobId jid = null;
  for (Map.Entry<JobId, Job> entry : jobsMap.entrySet()) {
    jid = entry.getValue().getID();
    queryState = entry.getValue().getState().toString();
    break;
  }
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs").queryParam("state", queryState)
      .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", 1, arr.length());
  JSONObject info = arr.getJSONObject(0);
  Job job = appContext.getPartialJob(jid);
  VerifyJobsUtils.verifyHsJobPartial(info, job);
}
 
Example #17
Source File: WorkMgrService.java    From batfish with Apache License 2.0 6 votes vote down vote up
@GET
@Path("test")
@Produces(MediaType.TEXT_PLAIN)
public String test() {
  try {
    _logger.info("WMS:test\n");
    JSONArray id = successResponse(Main.getWorkMgr().getStatusJson());

    return id.toString();

    // return Response.ok()
    // .entity(id)
    // // .header("Access-Control-Allow-Origin","*")
    // .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
    // .allow("OPTIONS")
    // .build();
  } catch (Exception e) {
    String stackTrace = Throwables.getStackTraceAsString(e);
    _logger.errorf("WMS:test exception: %s", stackTrace);
    // return Response.serverError().build();
    return "got error";
  }
}
 
Example #18
Source File: TestAMWebServicesJobs.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobs() throws JSONException, Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("mapreduce")
      .path("jobs").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");
  JSONObject info = arr.getJSONObject(0);
  Job job = appContext.getJob(MRApps.toJobID(info.getString("id")));
  verifyAMJob(info, job);

}
 
Example #19
Source File: JMXResource.java    From karyon with Apache License 2.0 6 votes vote down vote up
/**
 * Generate JSON for the MBean operations
 *
 * @param objName
 * @return
 * @throws Exception
 */
private JSONArray emitOperations(ObjectName objName) throws Exception {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objName);
    JSONArray ar = new JSONArray();

    MBeanOperationInfo[] operations = mBeanInfo.getOperations();
    for (MBeanOperationInfo operation : operations) {
        JSONObject obj = new JSONObject();
        obj.put("name", operation.getName());
        obj.put("description", operation.getDescription());
        obj.put("returnType", operation.getReturnType());
        obj.put("impact", operation.getImpact());

        JSONArray params = new JSONArray();
        for (MBeanParameterInfo param : operation.getSignature()) {
            JSONObject p = new JSONObject();
            p.put("name", param.getName());
            p.put("type", param.getType());
            params.put(p);
        }
        obj.put("params", params);
        ar.put(obj);
    }
    return ar;
}
 
Example #20
Source File: JsonHelper.java    From OSTMap with Apache License 2.0 6 votes vote down vote up
public static String generateCoordinates(String json) {
    try {
        JSONObject obj = new JSONObject(json);
        Double[] longLat = Extractor.extractLocation(obj);

        if (obj.has(KEY_COORDINATES) && obj.isNull(KEY_COORDINATES)) {
            //coordinates is empty
            JSONArray longLatArr = new JSONArray();
            if (longLat != null && longLat[0] != null && longLat[1] != null) {
                longLatArr.put(longLat[0]);
                longLatArr.put(longLat[1]);
                JSONObject coordinates1 = new JSONObject().put(KEY_COORDINATES, longLatArr);
                obj.put(KEY_COORDINATES, coordinates1);
            }
        }
        if (obj.has(KEY_PLACE)) {
            //ccordinates is set, remove place
            obj.remove(KEY_PLACE);
        }
        return obj.toString();
    } catch (JSONException e) {
        log.error("no correct JSON string:" + json);

        return null;
    }
}
 
Example #21
Source File: DAGClientTimelineImpl.java    From tez with Apache License 2.0 6 votes vote down vote up
@Override
public VertexStatus getVertexStatus(String vertexName, Set<StatusGetOpts> statusOptions)
    throws IOException, TezException {
  final String url = String.format(
      "%s/%s?primaryFilter=%s:%s&secondaryFilter=vertexName:%s&fields=%s", baseUri,
      ATSConstants.TEZ_VERTEX_ID, ATSConstants.TEZ_DAG_ID, dagId, vertexName, FILTER_BY_FIELDS);

  try {
    VertexStatusProto.Builder statusBuilder;
    final JSONObject jsonRoot = getJsonRootEntity(url);
    JSONArray entitiesNode = jsonRoot.optJSONArray(ATSConstants.ENTITIES);
    if (entitiesNode == null || entitiesNode.length() != 1) {
      throw new TezException("Failed to get vertex status YARN Timeline");
    }
    JSONObject vertexNode = entitiesNode.getJSONObject(0);

    statusBuilder = parseVertexStatus(vertexNode, statusOptions);
    if (statusBuilder == null) {
      throw new TezException("Failed to parse vertex status from YARN Timeline");
    }

    return new VertexStatus(statusBuilder);
  } catch (JSONException je) {
    throw new TezException("Failed to parse VertexStatus json from YARN Timeline", je);
  }
}
 
Example #22
Source File: LivyRestExecutor.java    From kylin with Apache License 2.0 6 votes vote down vote up
private List<String> getLogs(JSONObject logInfo) {
    List<String> logs = Lists.newArrayList();
    if (logInfo.has("log")) {
        try {
            JSONArray logArray = logInfo.getJSONArray("log");

            for (int i=0; i<logArray.length(); i++) {
                logs.add(logArray.getString(i));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return logs;
}
 
Example #23
Source File: TestHsWebServicesTasks.java    From big-c with Apache License 2.0 6 votes vote down vote up
public void verifyHsJobTaskCounters(JSONObject info, Task task)
    throws JSONException {

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

  WebServicesTestUtils.checkStringMatch("id", MRApps.toString(task.getID()),
      info.getString("id"));
  // just do simple verification of fields - not data is correct
  // in the fields
  JSONArray counterGroups = info.getJSONArray("taskCounterGroup");
  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 #24
Source File: TestAMWebServicesAttempts.java    From big-c with Apache License 2.0 6 votes vote down vote up
public void verifyAMTaskAttempts(JSONObject json, Task task)
    throws JSONException {
  assertEquals("incorrect number of elements", 1, json.length());
  JSONObject attempts = json.getJSONObject("taskAttempts");
  assertEquals("incorrect number of elements", 1, json.length());
  JSONArray arr = attempts.getJSONArray("taskAttempt");
  for (TaskAttempt att : task.getAttempts().values()) {
    TaskAttemptId id = att.getID();
    String attid = MRApps.toString(id);
    Boolean found = false;

    for (int i = 0; i < arr.length(); i++) {
      JSONObject info = arr.getJSONObject(i);
      if (attid.matches(info.getString("id"))) {
        found = true;
        verifyAMTaskAttempt(info, att, task.getType());
      }
    }
    assertTrue("task attempt with id: " + attid
        + " not in web service output", found);
  }
}
 
Example #25
Source File: TestHsWebServicesJobsQuery.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryFinishTimeBegin() throws JSONException, Exception {
  WebResource r = resource();
  // the mockJobs finish time is the current time + some random amount
  Long now = System.currentTimeMillis();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("finishedTimeBegin", String.valueOf(now))
      .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", 3, arr.length());
}
 
Example #26
Source File: TypeGraph.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
/**
 * A utility method that tells whether a class is considered a bean.<br/>
 * For simplicity we exclude classes that have any type-args.
 *
 * @param className name of the class
 * @return true if it is a bean false otherwise.
 */
public boolean isInstantiableBean(String className) throws JSONException
{
  JSONObject classDesc = describeClass(className);
  if (classDesc.has("typeArgs")) {
    //any type with generics is not considered a bean
    return false;
  }
  JSONArray classProps = classDesc.optJSONArray("properties");
  if (classProps == null || classProps.length() == 0) {
    //no properties then cannot be a bean
    return false;
  }
  for (int p = 0; p < classProps.length(); p++) {
    JSONObject propDesc = classProps.getJSONObject(p);
    if (propDesc.optBoolean("canGet", false)) {
      return true;
    }
  }
  return false;
}
 
Example #27
Source File: TestRMWebServicesApps.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppsQueryQueue() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  rm.submitApp(CONTAINER_MB);
  rm.submitApp(CONTAINER_MB);

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

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps").queryParam("queue", "default")
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  assertEquals("incorrect number of elements", 1, json.length());
  JSONObject apps = json.getJSONObject("apps");
  assertEquals("incorrect number of elements", 1, apps.length());
  JSONArray array = apps.getJSONArray("app");
  assertEquals("incorrect number of elements", 2, array.length());
  rm.stop();
}
 
Example #28
Source File: NotificationHookConsumerIT.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageHandleFailureConsumerContinues() throws Exception {
    //send invalid message - update with invalid type
    sendHookMessage(new HookNotification.EntityPartialUpdateRequest(TEST_USER, randomString(), null, null,
            new Referenceable(randomString())));

    //send valid message
    final Referenceable entity = new Referenceable(DATABASE_TYPE_BUILTIN);
    String dbName = "db" + randomString();
    entity.set(NAME, dbName);
    entity.set(DESCRIPTION, randomString());
    entity.set(QUALIFIED_NAME, dbName);
    entity.set(CLUSTER_NAME, randomString());
    sendHookMessage(new HookNotification.EntityCreateRequest(TEST_USER, entity));

    waitFor(MAX_WAIT_TIME, new Predicate() {
        @Override
        public boolean evaluate() throws Exception {
            JSONArray results = searchByDSL(String.format("%s where name='%s'", DATABASE_TYPE_BUILTIN, entity.get(NAME)));
            return results.length() == 1;
        }
    });
}
 
Example #29
Source File: TestRMWebServicesNodes.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryAll() throws Exception {
  WebResource r = resource();
  MockNM nm1 = rm.registerNode("h1:1234", 5120);
  MockNM nm2 = rm.registerNode("h2:1235", 5121);
  MockNM nm3 = rm.registerNode("h3:1236", 5122);
  rm.sendNodeStarted(nm1);
  rm.sendNodeStarted(nm3);
  rm.NMwaitForState(nm1.getNodeId(), NodeState.RUNNING);
  rm.NMwaitForState(nm2.getNodeId(), NodeState.NEW);
  rm.sendNodeLost(nm3);

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("nodes")
      .queryParam("states", Joiner.on(',').join(EnumSet.allOf(NodeState.class)))
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  JSONObject nodes = json.getJSONObject("nodes");
  assertEquals("incorrect number of elements", 1, nodes.length());
  JSONArray nodeArray = nodes.getJSONArray("node");
  assertEquals("incorrect number of elements", 3, nodeArray.length());
}
 
Example #30
Source File: TestAMWebServicesAttempts.java    From big-c with 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);
    }
  }
}