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

The following examples show how to use org.codehaus.jettison.json.JSONObject#get() . 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: MappedXMLStreamReader.java    From jettison with Apache License 2.0 6 votes vote down vote up
public MappedXMLStreamReader(JSONObject obj, MappedNamespaceConvention con)
        throws JSONException, XMLStreamException {
    String rootName = (String) obj.keys().next();

    this.convention = con;
    this.nodes = new FastStack();
    this.ctx = con;
    Object top = obj.get(rootName);
    if (top instanceof JSONObject) {
        this.node = new Node(null, rootName, (JSONObject)top, convention);
    } else if (top instanceof JSONArray && !(((JSONArray)top).length() == 1 && ((JSONArray)top).get(0).equals(""))) {
        if (con.isRootElementArrayWrapper()) {
            this.node = new Node(null, rootName, obj, convention);
        } else {
            this.node = new Node(null, rootName, ((JSONArray)top).getJSONObject(0), convention);
        }
    } else {
        node = new Node(rootName, convention);
        convention.processAttributesAndNamespaces(node, obj);
        currentValue = JSONObject.NULL.equals(top) ? null : top.toString();
    }
    nodes.push(node);
    event = START_DOCUMENT;
}
 
Example 2
Source File: QuickStartIT.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testLineageIsMaintained() throws AtlasServiceException, JSONException {
    String salesFactTableId = getTableId(QuickStart.SALES_FACT_TABLE);
    String timeDimTableId = getTableId(QuickStart.TIME_DIM_TABLE);
    String salesFactDailyMVId = getTableId(QuickStart.SALES_FACT_DAILY_MV_TABLE);

    JSONObject inputGraph = atlasClientV1.getInputGraph(QuickStart.SALES_FACT_DAILY_MV_TABLE);
    JSONObject vertices = (JSONObject) ((JSONObject) inputGraph.get("values")).get("vertices");
    JSONObject edges = (JSONObject) ((JSONObject) inputGraph.get("values")).get("edges");

    assertTrue(vertices.has(salesFactTableId));
    assertTrue(vertices.has(timeDimTableId));
    assertTrue(vertices.has(salesFactDailyMVId));

    assertTrue(edges.has(salesFactDailyMVId));
    JSONArray inputs = (JSONArray)edges.get((String) ((JSONArray) edges.get(salesFactDailyMVId)).get(0));
    String i1 = inputs.getString(0);
    String i2 = inputs.getString(1);
    assertTrue(salesFactTableId.equals(i1) || salesFactTableId.equals(i2));
    assertTrue(timeDimTableId.equals(i1) || timeDimTableId.equals(i2));
}
 
Example 3
Source File: DataSetLineageServiceTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test(enabled = false)
public void testSearchByDSLQueries(String dslQuery) throws Exception {
    System.out.println("Executing dslQuery = " + dslQuery);
    String jsonResults = discoveryService.searchByDSL(dslQuery, new QueryParams(100, 0));
    assertNotNull(jsonResults);

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

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

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

    JSONArray rows = results.getJSONArray("rows");
    assertNotNull(rows);
    Assert.assertTrue(rows.length() >= 0); // some queries may not have any results
    System.out.println("query [" + dslQuery + "] returned [" + rows.length() + "] rows");
}
 
Example 4
Source File: RunningJobManager.java    From eagle with Apache License 2.0 6 votes vote down vote up
public Map<String, Map<String, String>> parse(JSONObject object) throws JSONException {
    Map<String, Map<String, String>> result = new HashMap<>();

    Iterator<String> keysItr = object.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();
        result.put(key, new HashMap<>());
        String value = (String) object.get(key);

        JSONObject jsonObject = new JSONObject(value);
        Map<String, String> items = result.get(key);
        Iterator<String> keyItemItr = jsonObject.keys();
        while (keyItemItr.hasNext()) {
            String itemKey = keyItemItr.next();
            items.put(itemKey, (String) jsonObject.get(itemKey));
        }
    }
    return result;
}
 
Example 5
Source File: GraphBackedDiscoveryServiceTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
private void runAndValidateQuery(String dslQuery, ResultChecker checker) throws Exception {
    System.out.println("Executing dslQuery = " + dslQuery);
    String jsonResults = searchByDSL(dslQuery);
    assertNotNull(jsonResults);

    JSONObject results = new JSONObject(jsonResults);
    assertEquals(results.length(), 3);
    Object query = results.get("query");
    assertNotNull(query);

    JSONArray rows = results.getJSONArray("rows");
    assertNotNull(rows);
    if (checker != null) {
        checker.validateResult(dslQuery, rows);
    }

    System.out.println("query [" + dslQuery + "] returned [" + rows.length() + "] rows");
}
 
Example 6
Source File: GraphBackedMetadataRepositoryTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = "testSubmitEntity")
public void testSearchByDSLWithInheritance() throws Exception {
    String dslQuery = "Person where name = 'Jane'";
    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.assertEquals(typeName, "Person");

    JSONArray rows = results.getJSONArray("rows");
    Assert.assertEquals(rows.length(), 1);

    JSONObject row = rows.getJSONObject(0);
    Assert.assertEquals(row.getString("$typeName$"), "Manager");
    Assert.assertEquals(row.getString("name"), "Jane");
}
 
Example 7
Source File: Question.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Recursively look for all key, value pairs and remove keys whose value is "${{@code varName}}".
 * Is this fragile? To be doubly sure, we do this only for keys with a sibling key "class" that is
 * a Question class
 */
private static void recursivelyRemoveOptionalVar(JSONObject questionObject, String varName)
    throws JSONException {
  Iterator<?> iter = questionObject.keys();
  while (iter.hasNext()) {
    String key = (String) iter.next();
    Object value = questionObject.get(key);
    if (value instanceof String) {
      if (value.equals("${" + varName + "}")) {
        iter.remove();
      }
    } else if (value instanceof JSONObject) {
      JSONObject childObject = (JSONObject) value;
      if (childObject.has("class")) {
        Object classValue = childObject.get("class");
        if (classValue instanceof String && isQuestionClass((String) classValue)) {
          recursivelyRemoveOptionalVar(childObject, varName);
        }
      }
    }
  }
}
 
Example 8
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 9
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 10
Source File: SimpleHistoryParser.java    From tez with Apache License 2.0 5 votes vote down vote up
private void populateOtherInfo(JSONObject source, JSONObject destination) throws JSONException {
  if (source == null || destination == null) {
    return;
  }
  for (Iterator it = source.keys(); it.hasNext(); ) {
    String key = (String) it.next();
    Object val = source.get(key);
    destination.put(key, val);
  }
}
 
Example 11
Source File: DefaultSchemaRegistryClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getSchemaGroups() {
    if(LOG.isDebugEnabled()) {
        LOG.debug("==> DefaultSchemaRegistryClient.getSchemaGroups()");
    }

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

        if(LOG.isDebugEnabled()) {
            LOG.debug("DefaultSchemaRegistryClient.getSchemaGroups(): 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");
            res.add(group);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

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

    return res;
}
 
Example 12
Source File: ZeppelinhubClient.java    From zeppelin with 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 13
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 14
Source File: GeoSpatialConfig.java    From database with GNU General Public License v2.0 4 votes vote down vote up
private void initDatatypes(List<String> geoSpatialDatatypeConfigs) {
   
    datatypeConfigs = new ArrayList<GeoSpatialDatatypeConfiguration>();
   
    if (geoSpatialDatatypeConfigs==null)
        return; // nothing to be done

    /**
     * We expect a JSON config string of the following format (example):
     * 
     * {"config": { 
     *   "uri": "http://my.custom.datatype2.uri", 
     *   "literalSerializer": "com.bigdata.service.GeoSpatialLiteralSerializer",
     *   "fields": [ 
     *     { "valueType": "DOUBLE", "multiplier": "100000", "serviceMapping": "LATITUDE" }, 
     *     { "valueType": "DOUBLE", "multiplier": "100000", "serviceMapping": "LONGITUDE" }, 
     *     { "valueType": "LONG, "multiplier": "1", "minValue" : "0" , "serviceMapping": "TIME"  }, 
     *     { "valueType": "LONG", "multiplier": "1", "minValue" : "0" , "serviceMapping" : "COORD_SYSTEM"  } 
     *   ] 
     * }}
     */
    for (final String configStr : geoSpatialDatatypeConfigs) {
       
        if (configStr==null || configStr.isEmpty())
            continue; // skip

        try {

            // read values from JSON
            final JSONObject json = new JSONObject(configStr);
            final JSONObject topLevelNode = (JSONObject)json.get(JSON_STR_CONFIG);
            final String uri = (String)topLevelNode.get(JSON_STR_URI);
            final String literalSerializer = topLevelNode.has(JSON_STR_LITERALSERIALIZER) ?
                    (String)topLevelNode.get(JSON_STR_LITERALSERIALIZER) : null;
            final JSONArray fields = (JSONArray)topLevelNode.get(JSON_STR_FIELDS);

            // delegate to GeoSpatialDatatypeConfiguration for construction
            datatypeConfigs.add(new GeoSpatialDatatypeConfiguration(uri, literalSerializer, fields));
            
        } catch (JSONException e) {
            
            log.warn("Illegal JSON configuration: " + e.getMessage());
            throw new IllegalArgumentException(e); // forward exception
        }
       
        // validate that there are no duplicate URIs used for the datatypeConfigs
        final Set<URI> uris = new HashSet<URI>();
        for (int i=0; i<datatypeConfigs.size(); i++) {
            
            final URI curUri = datatypeConfigs.get(i).getUri();
            
            if (uris.contains(curUri)) {
                throw new IllegalArgumentException("Duplicate URI used for geospatial datatype config: " + curUri);
            }
            
            uris.add(curUri);
        }

    }
}
 
Example 15
Source File: GPOUtils.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
/**
 * This method deserializes the fields in the given {@link FieldsDescriptor} into a map.
 * @param fieldsDescriptor The {@link FieldsDescriptor} to fetch fields from.
 * @param dpou The {@link JSONObject} which contains the fields whose values need to be fetched.
 * @return A {@link Map} whose keys are field names, and whose values are possible values for those fields.
 */
public static Map<String, Set<Object>> deserializeToMap(FieldsDescriptor fieldsDescriptor, JSONObject dpou)
{
  Map<String, Set<Object>> keyToValues = Maps.newHashMap();

  for (String key : fieldsDescriptor.getFields().getFields()) {
    if (!dpou.has(key)) {
      throw new IllegalArgumentException("The given key " + key + " is not contained in the given JSON");
    }

    Set<Object> keyValues;
    Object keyValue;

    try {
      keyValue = dpou.get(key);
    } catch (JSONException ex) {
      throw new IllegalStateException("This should never happen", ex);
    }

    if (keyValue instanceof JSONArray) {

      JSONArray ja = (JSONArray)keyValue;
      keyValues = Sets.newHashSetWithExpectedSize(ja.length());

      Type type = fieldsDescriptor.getType(key);

      for (int index = 0; index < ja.length(); index++) {
        keyValues.add(getFieldFromJSON(type, ja, index));
      }

    } else if (keyValue instanceof JSONObject) {
      throw new UnsupportedOperationException("Cannot extract objects from JSONObjects");
    } else {
      keyValues = Sets.newHashSetWithExpectedSize(1);
      keyValues.add(getFieldFromJSON(fieldsDescriptor, key, dpou));
    }

    keyToValues.put(key, keyValues);
  }

  return keyToValues;
}
 
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: GraphBackedDiscoveryServiceTest.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "dslOrderByQueriesProvider")
public void  testSearchByDSLQueriesWithOrderBy(String dslQuery, Integer expectedNumRows, String orderBy, boolean ascending) throws Exception {
    System.out.println("Executing dslQuery = " + dslQuery);
    String jsonResults = searchByDSL(dslQuery);
    assertNotNull(jsonResults);

    JSONObject results = new JSONObject(jsonResults);
    assertEquals(results.length(), 3);

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

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

    JSONArray rows = results.getJSONArray("rows");

    assertNotNull(rows);
    assertEquals(rows.length(), expectedNumRows.intValue()); // some queries may not have any results
    List<String> returnedList = new ArrayList<>();
    for (int i = 0; i < rows.length(); i++) {
        JSONObject row = rows.getJSONObject(i);
        try
        {
            returnedList.add(row.get(orderBy).toString());
        }
        catch(Exception ex)
        {
            System.out.println( " Exception occured " + ex.getMessage() + " found row: "+row);
        }
    }
    Iterator<String> iter = returnedList.iterator();
    String _current = null, _prev = null;
    if (orderBy != null) {
        // Following code compares the results in rows and makes sure data
        // is sorted as expected
        while (iter.hasNext()) {
            _prev = _current;
            _current = iter.next().toLowerCase();
            if (_prev != null && _prev.compareTo(_current) != 0) {
                if(ascending) {
                    Assert.assertTrue(_prev.compareTo(_current) < 0,  _prev + " is greater than " + _current);
                }
                else {
                    Assert.assertTrue(_prev.compareTo(_current) > 0, _prev + " is less than " + _current);
                }
            }
        }
    }

    System.out.println("query [" + dslQuery + "] returned [" + rows.length() + "] rows");
}
 
Example 18
Source File: JobHistoryFileParserHadoop2.java    From hraven with Apache License 2.0 4 votes vote down vote up
/**
 * understand the schema so that we can parse the rest of the file
 * @throws JSONException
 */
private void understandSchema(String schema) throws JSONException {

  JSONObject j1 = new JSONObject(schema);
  JSONArray fields = j1.getJSONArray(FIELDS);

  String fieldName;
  String fieldTypeValue;
  Object recName;

  for (int k = 0; k < fields.length(); k++) {
    if (fields.get(k) == null) {
      continue;
    }
    JSONObject allEvents = new JSONObject(fields.get(k).toString());
    Object name = allEvents.get(NAME);
    if (name != null) {
      if (name.toString().equalsIgnoreCase(EVENT)) {
        JSONArray allTypeDetails = allEvents.getJSONArray(TYPE);
        for (int i = 0; i < allTypeDetails.length(); i++) {
          JSONObject actual = (JSONObject) allTypeDetails.get(i);
          JSONArray types = actual.getJSONArray(FIELDS);
          Map<String, String> typeDetails = new HashMap<String, String>();
          for (int j = 0; j < types.length(); j++) {
            if (types.getJSONObject(j) == null ) {
              continue;
            }
            fieldName = types.getJSONObject(j).getString(NAME);
            fieldTypeValue = types.getJSONObject(j).getString(TYPE);
            if ((fieldName != null) && (fieldTypeValue != null)) {
              typeDetails.put(fieldName, fieldTypeValue);
            }
          }

          recName = actual.get(NAME);
          if (recName != null) {
            /* the next statement may throw an IllegalArgumentException if
             * it finds a new string that's not part of the Hadoop2RecordType enum
             * that way we know what types of events we are parsing
             */
            fieldTypes.put(Hadoop2RecordType.valueOf(recName.toString()), typeDetails);
          }
        }
      }
    }
  }
}
 
Example 19
Source File: JsonReader.java    From vespa with Apache License 2.0 4 votes vote down vote up
public SetRequestData getStateRequestData(HttpRequest request) throws Exception {
    JSONObject json = new JSONObject(request.getPostContent().toString());

    final boolean probe = json.has("probe") && json.getBoolean("probe");

    final SetUnitStateRequest.Condition condition;
    if (json.has("condition")) {
        condition = SetUnitStateRequest.Condition.fromString(json.getString("condition"));
    } else {
        condition = SetUnitStateRequest.Condition.FORCE;
    }

    final SetUnitStateRequest.ResponseWait responseWait = json.has("response-wait")
            ? SetUnitStateRequest.ResponseWait.fromString(json.getString("response-wait"))
            : SetUnitStateRequest.ResponseWait.WAIT_UNTIL_CLUSTER_ACKED;

    Map<String, UnitState> stateMap = new HashMap<>();
    if (!json.has("state")) {
        throw new InvalidContentException("Set state requests must contain a state object");
    }
    Object o = json.get("state");
    if (!(o instanceof JSONObject)) {
        throw new InvalidContentException("value of state is not a json object");
    }

    JSONObject state = (JSONObject) o;

    JSONArray stateTypes = state.names();
    for (int i=0; i<stateTypes.length(); ++i) {
        o = stateTypes.get(i);
        String type = (String) o;
        o = state.get(type);
        if (!(o instanceof JSONObject)) {
            throw new InvalidContentException("value of state->" + type + " is not a json object");
        }
        JSONObject userState = (JSONObject) o;
        String code = "up";
        if (userState.has("state")) {
            o = userState.get("state");
            if (!(o instanceof String)) {
                throw new InvalidContentException("value of state->" + type + "->state is not a string");
            }
            code = o.toString();
        }
        String reason = "";
        if (userState.has("reason")) {
            o = userState.get("reason");
            if (!(o instanceof String)) {
                throw new InvalidContentException("value of state->" + type + "->reason is not a string");
            }
            reason = o.toString();
        }
        stateMap.put(type, new UnitStateImpl(code, reason));
    }

    return new SetRequestData(probe, stateMap, condition, responseWait);
}
 
Example 20
Source File: RequestExecutionHelper.java    From cloud-espm-v2 with Apache License 2.0 2 votes vote down vote up
/**
 * Get Inline Count from request
 * 
 * @param response
 *            Body of response
 * @return inline count
 * @throws JSONException
 */
public static int getInlineCount(String response) throws JSONException {
	JSONObject jo = new JSONObject(response);
	JSONObject jod = (JSONObject) jo.get("d");
	return (Integer.parseInt((String) jod.get("__count")));
}