/**
  * Removes all properties from "valueObject" where the value matches the corresponding value in
  * "defaultValueObject".
  *
  * @return <code>true</code> of the two objects are completely equal and no properties remain in
  *     "valueObject". This means that the valueObject itself MAY be removed. Return value <code>
  *     false</code> means that not all properties are equal (but nevertheless, some properties may
  *     have been removed from valueObject).
  */
 protected boolean filterDefaultObject(JSONObject valueObject, JSONObject defaultValueObject) {
   boolean sameKeys =
       CollectionUtility.equalsCollection(valueObject.keySet(), defaultValueObject.keySet());
   for (Iterator it = valueObject.keys(); it.hasNext(); ) {
     String prop = (String) it.next();
     Object subValue = valueObject.opt(prop);
     Object subDefaultValue = defaultValueObject.opt(prop);
     boolean valueEqualToDefaultValue = checkValueEqualToDefaultValue(subValue, subDefaultValue);
     if (valueEqualToDefaultValue) {
       // Property value value is equal to the static default value -> remove the property
       it.remove();
     } else {
       // Special case: Check if there is a "pseudo" default value, which will not
       // be removed itself, but might have sub-properties removed.
       subDefaultValue = defaultValueObject.opt("~" + prop);
       checkValueEqualToDefaultValue(subValue, subDefaultValue);
     }
   }
   // Even more special case: If valueObject is now empty and it used to have the same keys as
   // the defaultValueObject, it is considered equal to the default value and MAY be removed.
   if (valueObject.length() == 0 && sameKeys) {
     return true;
   }
   return false;
 }
Example #2
0
 // Credits to: http://stackoverflow.com/a/24012023/194609
 private static Map<String, Object> toMap(JSONObject object) throws JSONException {
   Map<String, Object> map = new HashMap<>(object.keySet().size());
   for (String key : object.keySet()) {
     Object value = object.get(key);
     if (value instanceof JSONArray) {
       value = toList((JSONArray) value);
     } else if (value instanceof JSONObject) {
       value = toMap((JSONObject) value);
     }
     map.put(key, value);
   }
   return map;
 }
Example #3
0
  public void applySettingStatusReport(JSONObject js) {
    /**
     * This breaks the mold a bit.. but its more efficient. This gets called off the top of
     * ParseJson if it has an "SR" in it. Sr's are called so often that instead of walking the
     * normal parsing tree.. this skips to the end
     */
    try {
      Iterator ii = js.keySet().iterator();
      // This is a special multi single value response object
      while (ii.hasNext()) {
        String key = ii.next().toString();

        responseCommand rc =
            new responseCommand(MNEMONIC_GROUP_SYSTEM, key.toString(), js.get(key).toString());
        TinygDriver.getInstance().machine.applyJsonStatusReport(rc);
        //                _applySettings(rc.buildJsonObject(), rc.getSettingParent()); //we will
        // supply the parent object name for each key pair
      }
      setChanged();
      message[0] = "STATUS_REPORT";
      message[1] = null;
      notifyObservers(message);

    } catch (Exception ex) {
      logger.error("[!] Error in applySettingStatusReport(JsonOBject js) : " + ex.getMessage());
      logger.error("[!]js.tostring " + js.toString());
      setChanged();
      message[0] = "STATUS_REPORT";
      message[1] = null;
      notifyObservers(message);
    }
  }
Example #4
0
 /**
  * Performs a deep conversion from JSONObject to Java Map.
  *
  * @param jsonObject the JSON array to convert
  * @return the Java equivalent
  */
 public static Map<String, Object> mapFromJsonObject(JSONObject jsonObject) {
   Map<String, Object> result = new HashMap<>();
   for (Object oKey : jsonObject.keySet()) {
     String key = oKey.toString();
     result.put(key, fromJsonStruct(jsonObject.get(key)));
   }
   return result;
 }
Example #5
0
  public void applySettingMasterGroup(JSONObject js, String pg) throws Exception {

    if (pg.equals(MNEMONIC_GROUP_STATUS_REPORT)) {
      // This is a status report master object that came in through a response object.
      // meaning that the response was asked for like this {"sr":""} and returned like this.
      // {"r":{"sr":{"line":0,"posx":0.000,"posy":0.000,"posz":0.000,"posa":0.000,"vel":0.000,"unit":1,"momo":0,"stat":3},"f":[1,0,10,885]}}
      // Right now its parsed down to JUST the json object for the SR like so.
      // {"sr":{"line":0,"posx":0.000,"posy":0.000,"posz":0.000,"posa":0.000,"vel":0.000,"unit":1,"momo":0,"stat":3},"f":[1,0,10,885]}
      // so we can now just pass it to the applySettingStatusReport method.
      applySettingStatusReport(js);
    } else {
      if (js.keySet().size() > 1) {
        Iterator ii = js.keySet().iterator();
        // This is a special multi single value response object
        while (ii.hasNext()) {
          String key = ii.next().toString();
          if (key.equals("f")) {
            parseFooter(
                js.getJSONArray(
                    "f")); // This is very important.  We break out our response footer.. error
                           // codes.. bytes availble in hardware buffer etc.
          } else {
            responseCommand rc =
                TinygDriver.getInstance().mneManager.lookupSingleGroupMaster(key, pg);
            if (rc
                == null) { // This happens when a new mnemonic has been added to the tinyG firmware
                           // but not added to tgFX's MnemonicManger
              // This is the error case
              logger.error(
                  "Mnemonic Lookup Failed in applySettingsMasterGroup. \n\tMake sure there are not new elements added to TinyG and not to the MnemonicManager Class.\n\tMNEMONIC FAILED: "
                      + key);
            } else {
              // This is the normal case
              rc.setSettingValue(js.get(key).toString());
              String parentGroup = rc.getSettingParent();
              _applySettings(
                  rc.buildJsonObject(),
                  rc.getSettingParent()); // we will supply the parent object name for each key pai
            }
          }
        }
      }
    }
  }
Example #6
0
 private ItemHint.ValueProvider toValueProvider(JSONObject object) {
   String name = object.getString("name");
   Map<String, Object> parameters = new HashMap<String, Object>();
   if (object.has("parameters")) {
     JSONObject parametersObject = object.getJSONObject("parameters");
     for (Object k : parametersObject.keySet()) {
       String key = (String) k;
       Object value = readItemValue(parametersObject.get(key));
       parameters.put(key, value);
     }
   }
   return new ItemHint.ValueProvider(name, parameters);
 }
Example #7
0
  // <editor-fold defaultstate="collapsed" desc="Internal Methods">
  private void readJsonKeyValues(JSONObject json, String spaces) {
    String keyString = null;
    Object keyValue = null;

    for (Object key : json.keySet()) {
      keyString = (String) key;
      keyValue = json.get(keyString);

      System.out.println(spaces + "K: " + keyString + ", V: " + keyValue);

      detectJsonType(keyValue, spaces);
    }
  }
Example #8
0
 public static void assertSuperset(
     final JSONObject superset, final JSONObject subset, @Nullable final String pathPrefix) {
   for (final String key : ((Set<String>) subset.keySet())) {
     final Object value = subset.get(key);
     if (!superset.has(key)) {
       throw new AssertionError(
           String.format(
               "Missing key '%s'%s. Expected '%s' on JSONObject:\n%s",
               key, pathPrefix == null ? "" : " at path " + pathPrefix, key, superset));
     }
     if (!value.getClass().equals(superset.get(key).getClass())) {
       throw new AssertionError(
           String.format(
               "Key '%s'%s has unexpected type. Expected %s but was %s on JSONObject:\n%s",
               key,
               pathPrefix == null ? "" : " at path " + pathPrefix,
               value.getClass(),
               superset.get(key).getClass(),
               superset));
     }
     if (value instanceof JSONObject) {
       assertJsonEquivalence(
           (JSONObject) value,
           superset.getJSONObject(key),
           pathPrefix == null ? key : pathPrefix + "." + key);
     } else if (value instanceof JSONArray) {
       assertJsonEquivalence(
           (JSONArray) value,
           superset.getJSONArray(key),
           pathPrefix == null ? key : pathPrefix + "." + key);
     } else if (!value.equals(superset.get(key))) {
       throw new AssertionError(
           String.format(
               "Key '%s'%s has unexpected value. Expected '%s' but was '%s' on JSONObject:\n%s",
               key,
               pathPrefix == null ? "" : " at path " + pathPrefix,
               value,
               superset.get(key),
               superset));
     }
   }
 }
  private void putStats(JSONObject nodesStats, JSONObject clusterStats) throws IOException {

    String indexName = IndexNameFactory.getIndexName();

    StringBuilder sb = new StringBuilder();
    if (nodesStats.has("nodes")) {
      JSONObject nodes = nodesStats.getJSONObject("nodes");

      for (String key : (Set<String>) nodes.keySet()) {
        JSONObject node_data = nodes.getJSONObject(key);
        if (node_data.has("name")) {
          String nodeName = node_data.getString("name");

          JSONObject nodeData = new JSONObject();
          nodeData.put("_index", indexName);
          nodeData.put("_type", nodeName);

          JSONObject metadata = new JSONObject();
          metadata.put("index", nodeData);

          sb.append(metadata);
          sb.append('\n');
          sb.append(node_data.toString());
          sb.append('\n');
        }
      }
    }

    JSONObject clusterData = new JSONObject();
    clusterData.put("_index", indexName);
    clusterData.put("_type", "cluster");
    JSONObject metadata = new JSONObject();
    metadata.put("index", clusterData);
    sb.append(metadata);
    sb.append('\n');
    sb.append(clusterStats.toString());
    sb.append('\n');

    httpHelper.postString("http://localhost:9200/_bulk", sb.toString());
  }
Example #10
0
  public void applySetting(JSONObject js) {
    try {
      if (js.length() == 0) {
        // This is a blank object we just return and move on
      } else if (js.keySet().size() > 1) { // If there are more than one object in the json response
        Iterator ii = js.keySet().iterator();
        // This is a special multi single value response object
        while (ii.hasNext()) {
          String key = ii.next().toString();
          switch (key) {
            case "f":
              parseFooter(js.getJSONArray("f"));
              // This is very important.
              // We break out our response footer.. error codes.. bytes availble in hardware buffer
              // etc.
              break;

            case "msg":
              message[0] = "TINYG_USER_MESSAGE";
              message[1] = (String) js.get(key) + "\n";
              logger.info("[+]TinyG Message Sent:  " + js.get(key) + "\n");
              setChanged();
              notifyObservers(message);
              break;
            case "rx":
              TinygDriver.getInstance().serialWriter.setBuffer(js.getInt(key));
              break;
            default:
              if (TinygDriver.getInstance().mneManager.isMasterGroupObject(key)) {
                //                            logger.info("Group Status Report Detected: " + key);
                applySettingMasterGroup(js.getJSONObject(key), key);
                continue;
              }
              responseCommand rc = TinygDriver.getInstance().mneManager.lookupSingleGroup(key);
              rc.setSettingValue(js.get(key).toString());
              _applySettings(
                  rc.buildJsonObject(),
                  rc.getSettingParent()); // we will supply the parent object name for each key pair
              break;
          }
        }
      } else {
        /* This else follows:
         * Contains a single object in the JSON response
         */
        if (js.keySet().contains("f")) {
          /** This is a single response footer object: Like So: {"f":[1,0,5,3330]} */
          parseFooter(js.getJSONArray("f"));
        } else {
          /**
           * Contains a single object in the json response I am not sure this else is needed any
           * longer.
           */
          _applySettings(js, js.keys().next().toString());
        }
      }
    } catch (JSONException ex) {
      logger.error("[!] Error in applySetting(JsonOBject js) : " + ex.getMessage());
      logger.error("[!]JSON String Was: " + js.toString());
      logger.error("Error in Line: " + js);
    } catch (Exception ex) {
      logger.error("[!] Error in applySetting(JsonOBject js) : " + ex.getMessage());
      logger.error(ex.getClass().toString());
    }
  }
Example #11
0
 protected void fillHeaders(JSONObject eachRow) {
   baseFieldNames.add("timestamp");
   if (eachRow != null) {
     baseFieldNames.addAll(eachRow.keySet());
   }
 }