Java Code Examples for org.codehaus.jettison.json.JSONObject#getInt()

The following examples show how to use org.codehaus.jettison.json.JSONObject#getInt() . 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: MetadataDiscoveryJerseyResourceIT.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: GraphBackedDiscoveryServiceTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
public boolean matches(JSONObject object) throws JSONException {
    for (Map.Entry<String, Object> requiredFieldsEntry : fieldValues_.entrySet()) {
        String fieldName = requiredFieldsEntry.getKey();
        Object expectedValue = requiredFieldsEntry.getValue();
        Object foundValue = null;
        if (expectedValue.getClass() == Integer.class) {
            foundValue = object.getInt(fieldName);
        } else if (expectedValue == idType) {
            return validateObjectIdType(object, fieldName);
        } else {
            foundValue = object.get(fieldName);
        }
        if (foundValue == null || !expectedValue.equals(foundValue)) {
            return false;
        }
    }
    return true;
}
 
Example 3
Source File: AbstractJdbcPOJOOutputOperator.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
/**
 * Function to initialize the list of {@link JdbcFieldInfo} from properties.xml
 * @param index
 * @param value
 */
public void setFieldInfosItem(int index, String value)
{
  try {
    JSONObject jo = new JSONObject(value);
    JdbcFieldInfo jdbcFieldInfo = new JdbcFieldInfo(jo.getString("columnName"), jo.getString("pojoFieldExpression"),
        FieldInfo.SupportType.valueOf(jo.getString("type")), jo.getInt("sqlType"));
    final int need = index - fieldInfos.size() + 1;
    for (int i = 0; i < need; i++) {
      fieldInfos.add(null);
    }
    fieldInfos.set(index,jdbcFieldInfo);
  } catch (Exception e) {
    throw new RuntimeException("Exception in setting JdbcFieldInfo");
  }
}
 
Example 4
Source File: ReleasePlanHelper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
private JSONObject updateJsonInfo(JSONObject jsonInfo) {
	try {
		// JSON是call by reference!!! 查memory=>System.identityHashCode(Object
		// x)
		JSONArray sprintJsonArray = (JSONArray) jsonInfo.get("Sprints");
		int sprintCount = jsonInfo.getInt("TotalSprintCount");
		int storyCount = jsonInfo.getInt("TotalStoryCount");
		int storyRemaining = jsonInfo.getInt("TotalStoryCount");
		double idealRange = (double) storyCount / sprintCount;
		for (int i = 0; i < sprintJsonArray.length(); i++) {
			JSONObject sprintJson = sprintJsonArray.getJSONObject(i);
			storyRemaining -= sprintJson.getInt("StoryDoneCount");
			sprintJson.put("StoryRemainingCount", storyRemaining);
			sprintJson.put("StoryIdealCount", storyCount
					- (idealRange * (i + 1)));
		}
		jsonInfo.put("Sprints", sprintJsonArray);
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return jsonInfo;
}
 
Example 5
Source File: StoryInfo.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void loadJSON(String jsonString) throws JSONException {
	JSONObject story = new JSONObject(jsonString);
	try {
		id = story.getLong("id");
	} catch (JSONException e) {
		id = -1;
	}
	name = story.getString("name");
	notes = story.getString("notes");
	howToDemo = story.getString("how_to_demo");
	importance = story.getInt("importance");
	value = story.getInt("value");
	estimate = story.getInt("estimate");
	status = story.getInt("status");
	sprintId = story.getLong("sprint_id");
	tags = story.getString("tags");
}
 
Example 6
Source File: SprintInfo.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
private void loadJSON(String jsonString) throws JSONException {
	JSONObject sprint = new JSONObject(jsonString);
	try {
		id = sprint.getLong("id");
	} catch (JSONException e) {
		id = -1;
	}
	interval = sprint.getInt(SprintEnum.INTERVAL);
	teamSize = sprint.getInt(SprintEnum.TEAM_SIZE);
	hoursCanCommit = sprint.getInt(SprintEnum.AVAILABLE_HOURS);
	focusFactor = sprint.getInt(SprintEnum.FOCUS_FACTOR);
	sprintGoal = sprint.getString(SprintEnum.GOAL);
	startDate = sprint.getString(SprintEnum.START_DATE);
	demoDate = sprint.getString(SprintEnum.DEMO_DATE);
	demoPlace = sprint.getString(SprintEnum.DEMO_PLACE);
	dailyInfo = sprint.getString(SprintEnum.DAILY_INFO);
	dueDate = sprint.getString(SprintEnum.DUE_DATE);
}
 
Example 7
Source File: TestRMWebServicesCapacitySched.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testPerUserResourcesJSON() throws Exception {
  //Start RM so that it accepts app submissions
  rm.start();
  try {
    rm.submitApp(10, "app1", "user1", null, "b1");
    rm.submitApp(20, "app2", "user2", null, "b1");

    //Get JSON
    WebResource r = resource();
    ClientResponse response = r.path("ws").path("v1").path("cluster")
        .path("scheduler/").accept(MediaType.APPLICATION_JSON)
        .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    JSONObject schedulerInfo = json.getJSONObject("scheduler").getJSONObject(
      "schedulerInfo");
    JSONObject b1 = getSubQueue(getSubQueue(schedulerInfo, "b"), "b1");
    //Check users user1 and user2 exist in b1
    JSONArray users = b1.getJSONObject("users").getJSONArray("user");
    for (int i=0; i<2; ++i) {
      JSONObject user = users.getJSONObject(i);
      assertTrue("User isn't user1 or user2",user.getString("username")
        .equals("user1") || user.getString("username").equals("user2"));
      user.getInt("numActiveApplications");
      user.getInt("numPendingApplications");
      checkResourcesUsed(user);
    }
  } finally {
    rm.stop();
  }
}
 
Example 8
Source File: TestRMWebServicesCapacitySched.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testPerUserResourcesJSON() throws Exception {
  //Start RM so that it accepts app submissions
  rm.start();
  try {
    rm.submitApp(10, "app1", "user1", null, "b1");
    rm.submitApp(20, "app2", "user2", null, "b1");

    //Get JSON
    WebResource r = resource();
    ClientResponse response = r.path("ws").path("v1").path("cluster")
        .path("scheduler/").accept(MediaType.APPLICATION_JSON)
        .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    JSONObject schedulerInfo = json.getJSONObject("scheduler").getJSONObject(
      "schedulerInfo");
    JSONObject b1 = getSubQueue(getSubQueue(schedulerInfo, "b"), "b1");
    //Check users user1 and user2 exist in b1
    JSONArray users = b1.getJSONObject("users").getJSONArray("user");
    for (int i=0; i<2; ++i) {
      JSONObject user = users.getJSONObject(i);
      assertTrue("User isn't user1 or user2",user.getString("username")
        .equals("user1") || user.getString("username").equals("user2"));
      user.getInt("numActiveApplications");
      user.getInt("numPendingApplications");
      checkResourcesUsed(user);
    }
  } finally {
    rm.stop();
  }
}
 
Example 9
Source File: DistributionTestFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
public void parse(String serialized) throws Exception {
    JSONObject json = new JSONObject(serialized);
    upStates = json.getString("up-states");
    nodeCount = json.getInt("redundancy");
    redundancy = json.getInt("redundancy");
    state = new ClusterState(json.getString("cluster-state"));
    distributionConfig = deserializeConfig(json.getString("distribution"));
    nodeType = NodeType.get(json.getString("node-type"));
    JSONArray results = json.getJSONArray("result");
    for (int i=0; i<results.length(); ++i) {
        JSONObject result = results.getJSONObject(i);
        Test t = new Test(new BucketId(Long.parseLong(result.getString("bucket"), 16)));
        {
            JSONArray nodes = result.getJSONArray("nodes");
            for (int j=0; j<nodes.length(); ++j) {
                t.nodes.add(nodes.getInt(j));
            }
        }
        if (nodeType == NodeType.STORAGE) {
            JSONArray disks = result.getJSONArray("disks");
            for (int j=0; j<disks.length(); ++j) {
                t.disks.add(disks.getInt(j));
            }
        }
        t.failure = Failure.valueOf(result.getString("failure"));
        this.results.add(t);
    }
}
 
Example 10
Source File: ArchaiusConnectionPoolConfiguration.java    From dyno with Apache License 2.0 5 votes vote down vote up
private ErrorRateMonitorConfig parseErrorRateMonitorConfig(String propertyPrefix) {
    String errorRateConfig = DynamicPropertyFactory.getInstance().getStringProperty(propertyPrefix + ".errorRateConfig", null).get();
    try {
        if (errorRateConfig == null) {
            return null;
        }

        // Classic format that is supported is json.

        JSONObject json = new JSONObject(errorRateConfig);

        int window = json.getInt("window");
        int frequency = json.getInt("frequency");
        int suppress = json.getInt("suppress");

        ErrorRateMonitorConfigImpl configImpl = new ErrorRateMonitorConfigImpl(window, frequency, suppress);

        JSONArray thresholds = json.getJSONArray("thresholds");
        for (int i = 0; i < thresholds.length(); i++) {

            JSONObject tConfig = thresholds.getJSONObject(i);

            int rps = tConfig.getInt("rps");
            int seconds = tConfig.getInt("seconds");
            int coverage = tConfig.getInt("coverage");

            configImpl.addThreshold(rps, seconds, coverage);
        }

        return configImpl;

    } catch (Exception e) {
        Logger.warn("Failed to parse error rate config: " + errorRateConfig, e);
    }

    return new ErrorRateMonitorConfigImpl();
}
 
Example 11
Source File: TestRMWebServicesCapacitySched.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private void verifySubQueue(JSONObject info, String q, 
    float parentAbsCapacity, float parentAbsMaxCapacity)
    throws JSONException, Exception {
  int numExpectedElements = 13;
  boolean isParentQueue = true;
  if (!info.has("queues")) {
    numExpectedElements = 25;
    isParentQueue = false;
  }
  assertEquals("incorrect number of elements", numExpectedElements, info.length());

  QueueInfo qi = isParentQueue ? new QueueInfo() : new LeafQueueInfo();
  qi.capacity = (float) info.getDouble("capacity");
  qi.usedCapacity = (float) info.getDouble("usedCapacity");
  qi.maxCapacity = (float) info.getDouble("maxCapacity");
  qi.absoluteCapacity = (float) info.getDouble("absoluteCapacity");
  qi.absoluteMaxCapacity = (float) info.getDouble("absoluteMaxCapacity");
  qi.absoluteUsedCapacity = (float) info.getDouble("absoluteUsedCapacity");
  qi.numApplications = info.getInt("numApplications");
  qi.queueName = info.getString("queueName");
  qi.state = info.getString("state");

  verifySubQueueGeneric(q, qi, parentAbsCapacity, parentAbsMaxCapacity);

  if (isParentQueue) {
    JSONArray arr = info.getJSONObject("queues").getJSONArray("queue");
    // test subqueues
    for (int i = 0; i < arr.length(); i++) {
      JSONObject obj = arr.getJSONObject(i);
      String q2 = q + "." + obj.getString("queueName");
      verifySubQueue(obj, q2, qi.absoluteCapacity, qi.absoluteMaxCapacity);
    }
  } else {
    LeafQueueInfo lqi = (LeafQueueInfo) qi;
    lqi.numActiveApplications = info.getInt("numActiveApplications");
    lqi.numPendingApplications = info.getInt("numPendingApplications");
    lqi.numContainers = info.getInt("numContainers");
    lqi.maxApplications = info.getInt("maxApplications");
    lqi.maxApplicationsPerUser = info.getInt("maxApplicationsPerUser");
    lqi.userLimit = info.getInt("userLimit");
    lqi.userLimitFactor = (float) info.getDouble("userLimitFactor");
    verifyLeafQueueGeneric(q, lqi);
    // resourcesUsed and users (per-user resources used) are checked in
    // testPerUserResource()
  }
}
 
Example 12
Source File: TestRMWebServicesCapacitySched.java    From big-c with Apache License 2.0 4 votes vote down vote up
private void verifySubQueue(JSONObject info, String q, 
    float parentAbsCapacity, float parentAbsMaxCapacity)
    throws JSONException, Exception {
  int numExpectedElements = 13;
  boolean isParentQueue = true;
  if (!info.has("queues")) {
    numExpectedElements = 25;
    isParentQueue = false;
  }
  assertEquals("incorrect number of elements", numExpectedElements, info.length());

  QueueInfo qi = isParentQueue ? new QueueInfo() : new LeafQueueInfo();
  qi.capacity = (float) info.getDouble("capacity");
  qi.usedCapacity = (float) info.getDouble("usedCapacity");
  qi.maxCapacity = (float) info.getDouble("maxCapacity");
  qi.absoluteCapacity = (float) info.getDouble("absoluteCapacity");
  qi.absoluteMaxCapacity = (float) info.getDouble("absoluteMaxCapacity");
  qi.absoluteUsedCapacity = (float) info.getDouble("absoluteUsedCapacity");
  qi.numApplications = info.getInt("numApplications");
  qi.queueName = info.getString("queueName");
  qi.state = info.getString("state");

  verifySubQueueGeneric(q, qi, parentAbsCapacity, parentAbsMaxCapacity);

  if (isParentQueue) {
    JSONArray arr = info.getJSONObject("queues").getJSONArray("queue");
    // test subqueues
    for (int i = 0; i < arr.length(); i++) {
      JSONObject obj = arr.getJSONObject(i);
      String q2 = q + "." + obj.getString("queueName");
      verifySubQueue(obj, q2, qi.absoluteCapacity, qi.absoluteMaxCapacity);
    }
  } else {
    LeafQueueInfo lqi = (LeafQueueInfo) qi;
    lqi.numActiveApplications = info.getInt("numActiveApplications");
    lqi.numPendingApplications = info.getInt("numPendingApplications");
    lqi.numContainers = info.getInt("numContainers");
    lqi.maxApplications = info.getInt("maxApplications");
    lqi.maxApplicationsPerUser = info.getInt("maxApplicationsPerUser");
    lqi.userLimit = info.getInt("userLimit");
    lqi.userLimitFactor = (float) info.getDouble("userLimitFactor");
    verifyLeafQueueGeneric(q, lqi);
    // resourcesUsed and users (per-user resources used) are checked in
    // testPerUserResource()
  }
}
 
Example 13
Source File: Multiplicity.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
public static Multiplicity fromJson(String jsonStr) throws JSONException {
    JSONObject json = new JSONObject(jsonStr);
    return new Multiplicity(json.getInt("lower"), json.getInt("upper"), json.getBoolean("isUnique"));
}
 
Example 14
Source File: MetadataDiscoveryJerseyResourceIT.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
@Test(dependsOnMethods = "testSearchDSLLimits")
public void testSearchUsingFullText() throws Exception {
    JSONObject response = atlasClientV1.searchByFullText(dbName, 10, 0);
    assertNotNull(response.get(AtlasClient.REQUEST_ID));

    assertEquals(response.getString("query"), dbName);
    assertEquals(response.getString("queryType"), "full-text");

    JSONArray results = response.getJSONArray(AtlasClient.RESULTS);
    assertEquals(results.length(), 1, "Results: " + results);

    JSONObject row = results.getJSONObject(0);
    assertNotNull(row.get("guid"));
    assertEquals(row.getString("typeName"), DATABASE_TYPE);
    assertNotNull(row.get("score"));

    int numRows = response.getInt(AtlasClient.COUNT);
    assertEquals(numRows, 1);

    //API works without limit and offset
    String query = dbName;
    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("query", query);
    response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH_FULL_TEXT, queryParams);
    results = response.getJSONArray(AtlasClient.RESULTS);
    assertEquals(results.length(), 1);

    //verify passed in limits and offsets are used
    //higher limit and 0 offset returns all results
    results = atlasClientV1.searchByFullText(query, 10, 0).getJSONArray(AtlasClient.RESULTS);
    assertEquals(results.length(), 1);

    //offset is used
    results = atlasClientV1.searchByFullText(query, 10, 1).getJSONArray(AtlasClient.RESULTS);
    assertEquals(results.length(), 0);

    //limit is used
    results = atlasClientV1.searchByFullText(query, 1, 0).getJSONArray(AtlasClient.RESULTS);
    assertEquals(results.length(), 1);

    //higher offset returns 0 results
    results = atlasClientV1.searchByFullText(query, 1, 2).getJSONArray(AtlasClient.RESULTS);
    assertEquals(results.length(), 0);
}
 
Example 15
Source File: FixedWidthSchema.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
/**
 * For a given json string, this method sets the field members
 *
 * @param json schema as provided by the user.
 */
private void initialize(String json) throws JSONException, IOException
{

  JSONObject jo = new JSONObject(json);
  JSONArray fieldArray = jo.getJSONArray(FIELDS);
  if (jo.has(FIELD_PADDING_CHARACTER)) {
    globalPadding = jo.getString(FIELD_PADDING_CHARACTER).charAt(0);
  } else {
    globalPadding = DEFAULT_PADDING_CHARACTER;
  }
  if (jo.has(FIELD_ALIGNMENT)) {
    globalAlignment = jo.getString(FIELD_ALIGNMENT);
  } else {
    globalAlignment = DEFAULT_ALIGNMENT;
  }

  for (int i = 0; i < fieldArray.length(); i++) {
    JSONObject obj = fieldArray.getJSONObject(i);
    Field field = new Field(obj.getString(NAME),
        obj.getString(TYPE).toUpperCase(), obj.getInt(FIELD_LENGTH));
    if (obj.has(FIELD_PADDING_CHARACTER)) {
      field.setPadding(obj.getString(FIELD_PADDING_CHARACTER).charAt(0));
    } else {
      field.setPadding(globalPadding);
    }
    if (obj.has(FIELD_ALIGNMENT)) {
      field.setAlignment(obj.getString(FIELD_ALIGNMENT));
    } else {
      field.setAlignment(globalAlignment);
    }
    //Get the format if the given data type is Date
    if (field.getType() == FieldType.DATE) {
      if (obj.has(DATE_FORMAT)) {
        field.setDateFormat(obj.getString(DATE_FORMAT));
      } else {
        field.setDateFormat(DEFAULT_DATE_FORMAT);
      }

    }
    //Get the trueValue and falseValue if the data type is Boolean
    if (field.getType() == FieldType.BOOLEAN) {
      if (obj.has(TRUE_VALUE)) {
        field.setTrueValue(obj.getString(TRUE_VALUE));
      } else {
        field.setTrueValue(DEFAULT_TRUE_VALUE);
      }
      if (obj.has(FALSE_VALUE)) {
        field.setFalseValue(obj.getString(FALSE_VALUE));
      } else {
        field.setFalseValue(DEFAULT_FALSE_VALUE);
      }

    }
    fields.add(field);
    fieldNames.add(field.name);
  }
}