Java Code Examples for org.codehaus.jettison.json.JSONArray#length()

The following examples show how to use org.codehaus.jettison.json.JSONArray#length() . 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: 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 2
Source File: TestAMWebServicesJobConf.java    From hadoop with Apache License 2.0 6 votes vote down vote up
public void verifyAMJobConf(JSONObject info, Job job) throws JSONException {

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

    WebServicesTestUtils.checkStringMatch("path", job.getConfFile().toString(),
        info.getString("path"));
    // just do simple verification of fields - not data is correct
    // in the fields
    JSONArray properties = info.getJSONArray("property");
    for (int i = 0; i < properties.length(); i++) {
      JSONObject prop = properties.getJSONObject(i);
      String name = prop.getString("name");
      String value = prop.getString("value");
      assertTrue("name not set", (name != null && !name.isEmpty()));
      assertTrue("value not set", (value != null && !value.isEmpty()));
    }
  }
 
Example 3
Source File: GraphBackedDiscoveryServiceTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypePreservedWhenFilterTraversesEdges() throws DiscoveryException, JSONException {

    String dsl = "hive_table db.name=\"Reporting\" limit 10";
    ImmutableSet<String> expectedTableNames = ImmutableSet.of("table1", "table2", "sales_fact_monthly_mv", "sales_fact_daily_mv");
    String jsonResults = discoveryService.searchByDSL(dsl, null);
    assertNotNull(jsonResults);

    JSONObject results = new JSONObject(jsonResults);
    JSONArray rows = results.getJSONArray("rows");
    assertEquals(rows.length(), expectedTableNames.size());
    for(int i = 0; i < rows.length(); i++) {
        JSONObject row = rows.getJSONObject(i);
        Assert.assertTrue(expectedTableNames.contains(row.get("name")));
    }
}
 
Example 4
Source File: TestAMWebServicesTasks.java    From big-c with Apache License 2.0 6 votes vote down vote up
public void verifyAMTask(JSONArray arr, Job job, String type)
    throws JSONException {
  for (Task task : job.getTasks().values()) {
    TaskId id = task.getID();
    String tid = MRApps.toString(id);
    Boolean found = false;
    if (type != null && task.getType() == MRApps.taskType(type)) {

      for (int i = 0; i < arr.length(); i++) {
        JSONObject info = arr.getJSONObject(i);
        if (tid.matches(info.getString("id"))) {
          found = true;
          verifyAMSingleTask(info, task);
        }
      }
      assertTrue("task with id: " + tid + " not in web service output", found);
    }
  }
}
 
Example 5
Source File: TestHsWebServicesJobConf.java    From big-c with Apache License 2.0 6 votes vote down vote up
public void verifyHsJobConf(JSONObject info, Job job) throws JSONException {

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

    WebServicesTestUtils.checkStringMatch("path", job.getConfFile().toString(),
        info.getString("path"));
    // just do simple verification of fields - not data is correct
    // in the fields
    JSONArray properties = info.getJSONArray("property");
    for (int i = 0; i < properties.length(); i++) {
      JSONObject prop = properties.getJSONObject(i);
      String name = prop.getString("name");
      String value = prop.getString("value");
      assertTrue("name not set", (name != null && !name.isEmpty()));
      assertTrue("value not set", (value != null && !value.isEmpty()));
    }
  }
 
Example 6
Source File: RelationToJobMetaEntity.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Override
public JobMetaEntity apply(ResultSet resultSet) throws SQLException {
    JobMetaEntity jobMetaEntity = new JobMetaEntity();
    jobMetaEntity.setUuid(resultSet.getString(1));
    jobMetaEntity.setJobDefId(resultSet.getString(2));
    jobMetaEntity.setSiteId(resultSet.getString(3));
    jobMetaEntity.setConfiguration(parse(resultSet.getString(4)));
    jobMetaEntity.setEvaluators(new ArrayList<>());
    try {
        JSONArray jsonArray = new JSONArray(resultSet.getString(5));
        for (int i = 0; i < jsonArray.length(); ++i) {
            jobMetaEntity.getEvaluators().add(jsonArray.getString(i));
        }
    } catch (Exception e) {
        LOG.warn("{}", e);
    }
    jobMetaEntity.setCreatedTime(resultSet.getLong(6));
    jobMetaEntity.setModifiedTime(resultSet.getLong(7));

    return jobMetaEntity;
}
 
Example 7
Source File: TestRMWebServicesCapacitySched.java    From big-c with Apache License 2.0 5 votes vote down vote up
private JSONObject getSubQueue(JSONObject queue, String subQueue)
  throws JSONException {
  JSONArray queues = queue.getJSONObject("queues").getJSONArray("queue");
  for (int i=0; i<queues.length(); ++i) {
    checkResourcesUsed(queues.getJSONObject(i));
    if (queues.getJSONObject(i).getString("queueName").equals(subQueue) ) {
      return queues.getJSONObject(i);
    }
  }
  return null;
}
 
Example 8
Source File: OperatorDiscoverer.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
private JSONArray enrichProperties(String operatorClass, JSONArray properties) throws JSONException
{
  JSONArray result = new JSONArray();
  for (int i = 0; i < properties.length(); i++) {
    JSONObject propJ = properties.getJSONObject(i);
    String propName = WordUtils.capitalize(propJ.getString("name"));
    String getPrefix = (propJ.getString("type").equals("boolean") || propJ.getString("type").equals("java.lang.Boolean")) ? "is" : "get";
    String setPrefix = "set";
    OperatorClassInfo oci = getOperatorClassWithGetterSetter(operatorClass, setPrefix + propName, getPrefix + propName);
    if (oci == null) {
      result.put(propJ);
      continue;
    }
    MethodInfo setterInfo = oci.setMethods.get(setPrefix + propName);
    MethodInfo getterInfo = oci.getMethods.get(getPrefix + propName);

    if ((getterInfo != null && getterInfo.omitFromUI) || (setterInfo != null && setterInfo.omitFromUI)) {
      continue;
    }
    if (setterInfo != null) {
      addTagsToProperties(setterInfo, propJ);
    } else if (getterInfo != null) {
      addTagsToProperties(getterInfo, propJ);
    }
    result.put(propJ);
  }
  return result;
}
 
Example 9
Source File: TestNMWebServicesContainers.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public void testNodeHelper(String path, String media) throws JSONException,
    Exception {
  WebResource r = resource();
  Application app = new MockApp(1);
  nmContext.getApplications().put(app.getAppId(), app);
  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(path)
      .accept(media).get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  JSONObject info = json.getJSONObject("containers");
  assertEquals("incorrect number of elements", 1, info.length());
  JSONArray conInfo = info.getJSONArray("container");
  assertEquals("incorrect number of elements", 4, conInfo.length());

  for (int i = 0; i < conInfo.length(); i++) {
    verifyNodeContainerInfo(
        conInfo.getJSONObject(i),
        nmContext.getContainers().get(
            ConverterUtils.toContainerId(conInfo.getJSONObject(i).getString(
                "id"))));
  }
}
 
Example 10
Source File: ATSImportTool.java    From tez with Apache License 2.0 5 votes vote down vote up
/**
 * Download data from ATS in batches
 *
 * @param url
 * @param zos
 * @param tag
 * @throws IOException
 * @throws TezException
 * @throws JSONException
 */
private void downloadJSONArrayFromATS(String url, ZipOutputStream zos, String tag)
    throws IOException, TezException, JSONException {

  Preconditions.checkArgument(zos != null, "ZipOutputStream can not be null");

  String baseUrl = url;
  JSONArray entities;

  long downloadedCount = 0;
  while ((entities = getJsonRootEntity(url).optJSONArray(Constants.ENTITIES)) != null
      && entities.length() > 0) {

    int limit = (entities.length() >= batchSize) ? (entities.length() - 1) : entities.length();
    LOG.debug("Limit={}, downloaded entities len={}", limit, entities.length());

    //write downloaded part to zipfile.  This is done to avoid any memory pressure when
    // downloading and writing 1000s of tasks.
    ZipEntry zipEntry = new ZipEntry("part-" + System.currentTimeMillis() + ".json");
    zos.putNextEntry(zipEntry);
    JSONObject finalJson = new JSONObject();
    finalJson.put(tag, entities);
    IOUtils.write(finalJson.toString(4), zos, "UTF-8");
    downloadedCount += entities.length();

    if (entities.length() < batchSize) {
      break;
    }

    //Set the last item in entities as the fromId
    url = baseUrl + "&fromId="
        + entities.getJSONObject(entities.length() - 1).getString(Constants.ENTITY);

    String firstItem = entities.getJSONObject(0).getString(Constants.ENTITY);
    String lastItem = entities.getJSONObject(entities.length() - 1).getString(Constants.ENTITY);
    LOG.info("Downloaded={}, First item={}, LastItem={}, new url={}", downloadedCount,
        firstItem, lastItem, url);
  }
}
 
Example 11
Source File: TargetHostsBuilderHelperCms.java    From parallec with Apache License 2.0 5 votes vote down vote up
/**
 * 20141022.
 *
 * @param jObj
 *            the j obj
 * @param projectionStr
 *            the projection str
 * @return the FQDN value list cms
 * @throws JSONException
 *             the JSON exception
 */
static List<String> getFQDNValueListCMS(JSONObject jObj,
        String projectionStr) throws JSONException {
    final List<String> labelList = new ArrayList<String>();

    if (!jObj.has("result")) {
        logger.error("!!CMS_ERROR! result key is not in jOBJ in getFQDNValueListCMS!!: \njObj:"
                + PcStringUtils.renderJson(jObj));

        return labelList;
    }
    JSONArray jArr = (JSONArray) jObj.get("result");
    if (jArr == null || jArr.length() == 0) {
        return labelList;
    }
    for (int i = 0; i < jArr.length(); ++i) {
        JSONObject agentObj = jArr.getJSONObject(i);
        // properties can be null

        if (!agentObj.has(projectionStr)) {
            continue;
        }
        String label = (String) agentObj.get(projectionStr);

        if (label != null && !label.trim().isEmpty()) {
            labelList.add(label);
        }
    }

    return labelList;
}
 
Example 12
Source File: SprintBacklogHelperTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGetAjaxGetSprintBacklogDateInfo() throws JSONException {
	String response = mSprintBacklogHelper
			.getAjaxGetSprintBacklogDateInfo();
	JSONObject json = new JSONObject(response);
	JSONArray dates = json.getJSONArray("Dates");
	assertEquals(10, dates.length());

	for (int i = 0; i < dates.length(); i++) {
		JSONObject date = dates.getJSONObject(i);
		assertEquals("Date_" + (i + 1), date.getString("Id"));
	}
}
 
Example 13
Source File: TestHsWebServicesJobs.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public void verifyHsJobAttempts(JSONObject info, Job job)
    throws JSONException {

  JSONArray attempts = info.getJSONArray("jobAttempt");
  assertEquals("incorrect number of elements", 2, attempts.length());
  for (int i = 0; i < attempts.length(); i++) {
    JSONObject attempt = attempts.getJSONObject(i);
    verifyHsJobAttemptsGeneric(job, attempt.getString("nodeHttpAddress"),
        attempt.getString("nodeId"), attempt.getInt("id"),
        attempt.getLong("startTime"), attempt.getString("containerId"),
        attempt.getString("logsLink"));
  }
}
 
Example 14
Source File: DefaultSchemaRegistryClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getSchemaBranches(String schemaMetadataName) {
    if(LOG.isDebugEnabled()) {
        LOG.debug("==> DefaultSchemaRegistryClient.getSchemaBranches( " + schemaMetadataName + " )");
    }

    ArrayList<String> res = new ArrayList<>();
    WebTarget target = currentSchemaRegistryTargets().schemasTarget.path(encode(schemaMetadataName) + "/branches");
    try {
        Response response = login.doAction(() ->
                target.request(MediaType.APPLICATION_JSON_TYPE).get(Response.class));

        if(LOG.isDebugEnabled()) {
            LOG.debug("DefaultSchemaRegistryClient.getSchemaBranches(): response statusCode = " + response.getStatus());
        }

        JSONArray mDataList = new JSONObject(response.readEntity(String.class)).getJSONArray("entities");
        int len = mDataList.length();
        for(int i = 0; i < len; i++) {
            JSONObject entity = mDataList.getJSONObject(i);
            JSONObject branchInfo = entity;
            String smName = (String) branchInfo.get("schemaMetadataName");
            if (smName.matches(schemaMetadataName)) {
                String bName = (String) branchInfo.get("name");
                res.add(bName);
            }

        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if(LOG.isDebugEnabled()) {
        LOG.debug("<== DefaultSchemaRegistryClient.getSchemaBranches( " + schemaMetadataName + " ): "
                + res.size()
                + " branches found.");
    }

    return res;
}
 
Example 15
Source File: GraphBackedMetadataRepositoryTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test(dependsOnMethods = "testCreateEntity")
public void testSearchByDSLQuery() throws Exception {
    String dslQuery = "hive_database as PII";
    System.out.println("Executing dslQuery = " + dslQuery);
    String jsonResults = discoveryService.searchByDSL(dslQuery, queryParams);
    Assert.assertNotNull(jsonResults);

    JSONObject results = new JSONObject(jsonResults);
    Assert.assertEquals(results.length(), 3);
    System.out.println("results = " + results);

    Object query = results.get("query");
    Assert.assertNotNull(query);

    JSONObject dataType = results.getJSONObject("dataType");
    Assert.assertNotNull(dataType);
    String typeName = dataType.getString("typeName");
    Assert.assertNotNull(typeName);

    JSONArray rows = results.getJSONArray("rows");
    Assert.assertNotNull(rows);
    Assert.assertTrue(rows.length() > 0);

    for (int index = 0; index < rows.length(); index++) {
        JSONObject row = rows.getJSONObject(index);
        String type = row.getString("$typeName$");
        Assert.assertEquals(type, "hive_database");

        String name = row.getString("name");
        Assert.assertEquals(name, TestUtils.DATABASE_NAME);
    }
}
 
Example 16
Source File: DefaultSchemaRegistryClient.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public List<String> getSchemaNames(List<String> schemaGroups) {
    if(LOG.isDebugEnabled()) {
        LOG.debug("==> DefaultSchemaRegistryClient.getSchemaNames( " + schemaGroups + " )");
    }

    ArrayList<String> res = new ArrayList<>();
    WebTarget webTarget = currentSchemaRegistryTargets().schemasTarget;
    try {
        Response response = login.doAction(() ->
                webTarget.request(MediaType.APPLICATION_JSON_TYPE).get(Response.class));

        if(LOG.isDebugEnabled()) {
            LOG.debug("DefaultSchemaRegistryClient.getSchemaNames(): response statusCode = " + response.getStatus());
        }

        JSONArray mDataList = new JSONObject(response.readEntity(String.class)).getJSONArray("entities");
        int len = mDataList.length();
        for(int i = 0; i < len; i++) {
            JSONObject entity = mDataList.getJSONObject(i);
            JSONObject schemaMetadata = (JSONObject)entity.get("schemaMetadata");
            String group = (String) schemaMetadata.get("schemaGroup");
            for(String schemaGroup:  schemaGroups) {
                if(group.matches(schemaGroup)) {
                    String name = (String) schemaMetadata.get("name");
                    res.add(name);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if(LOG.isDebugEnabled()) {
        LOG.debug("<== DefaultSchemaRegistryClient.getSchemaNames( " + schemaGroups + " ): "
                + res.size()
                + " schemaNames found");
    }

    return res;
}
 
Example 17
Source File: DagInfo.java    From tez with Apache License 2.0 4 votes vote down vote up
DagInfo(JSONObject jsonObject) throws JSONException {
  super(jsonObject);

  vertexNameMap = Maps.newHashMap();
  vertexNameIDMapping = new DualHashBidiMap<>();
  edgeInfoMap = Maps.newHashMap();
  basicVertexInfoMap = Maps.newHashMap();
  containerMapping = LinkedHashMultimap.create();

  Preconditions.checkArgument(jsonObject.getString(Constants.ENTITY_TYPE).equalsIgnoreCase
      (Constants.TEZ_DAG_ID));

  dagId = StringInterner.weakIntern(jsonObject.getString(Constants.ENTITY));

  //Parse additional Info
  JSONObject otherInfoNode = jsonObject.getJSONObject(Constants.OTHER_INFO);

  long sTime = otherInfoNode.optLong(Constants.START_TIME);
  long eTime= otherInfoNode.optLong(Constants.FINISH_TIME);
  userName = otherInfoNode.optString(Constants.USER);
  if (eTime < sTime) {
    LOG.warn("DAG has got wrong start/end values. "
        + "startTime=" + sTime + ", endTime=" + eTime + ". Will check "
        + "timestamps in DAG started/finished events");

    // Check if events DAG_STARTED, DAG_FINISHED can be made use of
    for(Event event : eventList) {
      switch (HistoryEventType.valueOf(event.getType())) {
      case DAG_STARTED:
        sTime = event.getAbsoluteTime();
        break;
      case DAG_FINISHED:
        eTime = event.getAbsoluteTime();
        break;
      default:
        break;
      }
    }

    if (eTime < sTime) {
      LOG.warn("DAG has got wrong start/end values in events as well. "
          + "startTime=" + sTime + ", endTime=" + eTime);
    }
  }
  startTime = sTime;
  endTime = eTime;

  //TODO: Not getting populated correctly for lots of jobs.  Verify
  submitTime = otherInfoNode.optLong(Constants.START_REQUESTED_TIME);
  diagnostics = otherInfoNode.optString(Constants.DIAGNOSTICS);
  failedTasks = otherInfoNode.optInt(Constants.NUM_FAILED_TASKS);
  JSONObject dagPlan = otherInfoNode.optJSONObject(Constants.DAG_PLAN);
  name = StringInterner.weakIntern((dagPlan != null) ? (dagPlan.optString(Constants.DAG_NAME)) : null);
  if (dagPlan != null) {
    JSONArray vertices = dagPlan.optJSONArray(Constants.VERTICES);
    if (vertices != null) {
      numVertices = vertices.length();
    } else {
      numVertices = 0;
    }
    parseDAGPlan(dagPlan);
  } else {
    numVertices = 0;
  }
  status = StringInterner.weakIntern(otherInfoNode.optString(Constants.STATUS));

  //parse name id mapping
  JSONObject vertexIDMappingJson = otherInfoNode.optJSONObject(Constants.VERTEX_NAME_ID_MAPPING);
  if (vertexIDMappingJson != null) {
    //get vertex name
    for (Map.Entry<String, BasicVertexInfo> entry : basicVertexInfoMap.entrySet()) {
      String vertexId = vertexIDMappingJson.optString(entry.getKey());
      //vertexName --> vertexId
      vertexNameIDMapping.put(entry.getKey(), vertexId);
    }
  }
}
 
Example 18
Source File: TranslationTest.java    From ezScrum with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testTranslateStoriesToJson() throws JSONException {
	// Test Data
	String TEST_STORY_NAME = "TEST_STORY_NAME";
	int TEST_STORY_ESTIMATE = 10;
	int TEST_STORY_IMPORTANCE = 96;
	String TEST_STORY_HOWTODEMO = "TEST_STORY_HOWTODEMO";
	String TEST_STORY_NOTES = "TEST_STORY_NOTES";
	int TEST_STORY_VALUE = 8;
	int TEST_STORY_SPRINTID = -1;
	int TEST_STORY_STATUS = StoryObject.STATUS_UNCHECK;
	// Tag data
	String tagName = "TEST_TAG_NAME";

	ProjectObject project = ProjectObject.get(mProject.getName());
	ProductBacklogHelper productBacklogHelper = new ProductBacklogHelper(project);
	ArrayList<StoryObject> stories = new ArrayList<StoryObject>();

	// setting stories
	for (int i = 0; i < mCPB.getStories().size(); i++) {
		// create tag
		TagObject tag = new TagObject(tagName, project.getId());
		tag.save();
		// Story Data
		StoryObject story = mCPB.getStories().get(i);
		StoryInfo storyInfo = new StoryInfo();
		storyInfo.id = story.getId();
		storyInfo.name = TEST_STORY_NAME + i;
		storyInfo.estimate = TEST_STORY_ESTIMATE;
		storyInfo.value = TEST_STORY_VALUE;
		storyInfo.importance = TEST_STORY_IMPORTANCE;
		storyInfo.howToDemo = TEST_STORY_HOWTODEMO;
		storyInfo.sprintId = TEST_STORY_SPRINTID;
		storyInfo.notes = TEST_STORY_NOTES;
		storyInfo.status = TEST_STORY_STATUS;
		storyInfo.tags = tag.getName();
		story = productBacklogHelper.updateStory(storyInfo.id, storyInfo);
		stories.add(story);
	}

	// call translateStoriesToJson
	String actualText = Translation.translateStoriesToJson(stories);
	// get JSON
	JSONObject storiesJSON = new JSONObject(actualText);
	assertTrue(storiesJSON.toString().contains("\"success\":true"));
	assertTrue(storiesJSON.toString().contains("\"Total\":10"));

	JSONArray storiesJSONArray = storiesJSON.getJSONArray("Stories");

	for (int i = 0; i < storiesJSONArray.length(); i++) {
		JSONObject storyJson = storiesJSONArray.getJSONObject(i);
		assertTrue(storyJson.toString().contains("\"Id\":" + stories.get(i).getId()));
		assertTrue(storyJson.toString().contains("\"Name\":\"" + TEST_STORY_NAME + i + "\""));
		assertTrue(storyJson.toString().contains("\"Value\":" + TEST_STORY_VALUE));
		assertTrue(storyJson.toString().contains("\"Estimate\":" + TEST_STORY_ESTIMATE));
		assertTrue(storyJson.toString().contains("\"Importance\":" + TEST_STORY_IMPORTANCE));
		assertTrue(storyJson.toString().contains("\"Tag\":\"" + tagName + "\""));
		assertTrue(storyJson.toString().contains("\"Status\":\"new\""));
		assertTrue(storyJson.toString().contains("\"Notes\":\"" + TEST_STORY_NOTES + "\""));
		assertTrue(storyJson.toString().contains("\"HowToDemo\":\"" + TEST_STORY_HOWTODEMO + "\""));
		assertTrue(storyJson.toString().contains("\"Sprint\":\"None\""));
		assertTrue(storyJson.toString().contains("\"FilterType\":\"DETAIL\""));
		assertTrue(storyJson.toString().contains("\"Attach\":false"));
	}

}
 
Example 19
Source File: DimensionalSchemaTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Test
public void testSchemaTags() throws Exception
{
  List<String> expectedTags = Lists.newArrayList("geo", "bullet");
  List<String> expectedKeyTags = Lists.newArrayList("geo.location");
  List<String> expectedValueTagsLat = Lists.newArrayList("geo.lattitude");
  List<String> expectedValueTagsLong = Lists.newArrayList("geo.longitude");

  String eventSchemaJSON = SchemaUtils.jarResourceFileToString("adsGenericEventSchemaTags.json");
  DimensionalSchema dimensional = new DimensionalSchema(
      new DimensionalConfigurationSchema(eventSchemaJSON, AggregatorRegistry.DEFAULT_AGGREGATOR_REGISTRY));

  String schemaJSON = dimensional.getSchemaJSON();

  JSONObject jo = new JSONObject(schemaJSON);
  List<String> tags = getStringList(jo.getJSONArray(FIELD_TAGS));
  Assert.assertEquals(expectedTags, tags);

  JSONArray keys = jo.getJSONArray(DimensionalConfigurationSchema.FIELD_KEYS);

  List<String> keyTags = null;

  for (int keyIndex = 0; keyIndex < keys.length(); keyIndex++) {
    JSONObject key = keys.getJSONObject(keyIndex);

    if (!key.has(FIELD_TAGS)) {
      continue;
    }

    Assert.assertEquals("location", key.get(DimensionalConfigurationSchema.FIELD_KEYS_NAME));
    keyTags = getStringList(key.getJSONArray(FIELD_TAGS));
  }

  Assert.assertTrue("No tags found for any key", keyTags != null);
  Assert.assertEquals(expectedKeyTags, keyTags);

  JSONArray values = jo.getJSONArray(DimensionalConfigurationSchema.FIELD_VALUES);

  boolean valueTagsLat = false;
  boolean valueTagsLong = false;

  for (int valueIndex = 0; valueIndex < values.length(); valueIndex++) {
    JSONObject value = values.getJSONObject(valueIndex);

    if (!value.has(FIELD_TAGS)) {
      continue;
    }

    String valueName = value.getString(DimensionalConfigurationSchema.FIELD_VALUES_NAME);
    List<String> valueTags = getStringList(value.getJSONArray(FIELD_TAGS));

    LOG.debug("value name: {}", valueName);

    if (valueName.startsWith("impressions")) {
      Assert.assertEquals(expectedValueTagsLat, valueTags);
      valueTagsLat = true;
    } else if (valueName.startsWith("clicks")) {
      Assert.assertEquals(expectedValueTagsLong, valueTags);
      valueTagsLong = true;
    } else {
      Assert.fail("There should be no tags for " + valueName);
    }
  }

  Assert.assertTrue("No tags found for impressions", valueTagsLat);
  Assert.assertTrue("No tags found for clicks", valueTagsLong);
}
 
Example 20
Source File: SolrFulltextSearchImpl.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Flattens a JSON result item, i.e. if the item is an array, it is
 * (non-recursively) flattened, applying toString() to sub items,
 * otherwise toString() is called directly.
 * 
 * @param obj the json result item
 * @return
 */
String flattenJsonResult(Object obj) {
   
   if (obj instanceof JSONArray) {
      
      StringBuffer buf = new StringBuffer();
      
      final JSONArray arr = (JSONArray)obj;
      for (int i=0; i<arr.length(); i++) {
         
         try {
            
            final Object cur = arr.get(i);
            
            if (cur!=null) {
               buf.append(cur.toString());
               
            }
            
         } catch (Exception e) {

            // ignoring is probably the best we can do here
            
         }
      }
      
      return buf.toString();
      
   } else {
      
      return obj.toString();
      
   }
   
}