Exemplo n.º 1
0
 /**
  * Produce a JSONArray containing the values of the members of this JSONObject.
  *
  * @param names A JSONArray containing a list of key strings. This determines the sequence of the
  *     values in the result.
  * @return A JSONArray of values.
  * @throws JSONException If any of the values are non-finite numbers.
  */
 public JSONArray toJSONArray(JSONArray names) throws JSONException {
   if (names == null || names.length() == 0) {
     return null;
   }
   JSONArray ja = new JSONArray();
   for (int i = 0; i < names.length(); i += 1) {
     ja.put(this.opt(names.getString(i)));
   }
   return ja;
 }
Exemplo n.º 2
0
 /**
  * Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names.
  * The list of names is not included in the output.
  *
  * @param names A JSONArray of strings.
  * @param ja A JSONArray of JSONObjects.
  * @return A comma delimited text.
  * @throws JSONException
  */
 public static String toString(JSONArray names, JSONArray ja) throws JSONException {
   if (names == null || names.length() == 0) {
     return null;
   }
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < ja.length(); i += 1) {
     JSONObject jo = ja.optJSONObject(i);
     if (jo != null) {
       sb.append(rowToString(jo.toJSONArray(names)));
     }
   }
   return sb.toString();
 }
Exemplo n.º 3
0
    /**
	 * Produce a comma delimited text row from a JSONArray. Values containing
	 * the comma character will be quoted. Troublesome characters may be 
	 * removed.
	 * @param ja A JSONArray of strings.
	 * @return A string ending in NEWLINE.
	 */
	public static String rowToString(JSONArray ja) {
	    StringBuffer sb = new StringBuffer();
	    for (int i = 0; i < ja.length(); i += 1) {
	        if (i > 0) {
	            sb.append(',');
	        }
	        Object object = ja.opt(i);
	        if (object != null) {
	            String string = object.toString();
	            if (string.length() > 0 && (string.indexOf(',') >= 0 || 
	            		string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || 
	            		string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
	                sb.append('"');
	            	int length = string.length();
	            	for (int j = 0; j < length; j += 1) {
	            		char c = string.charAt(j);
	            		if (c >= ' ' && c != '"') {
	            			sb.append(c);
	            		}
	                }
	                sb.append('"');
	            } else {
	                sb.append(string);
	            }
	        }
	    }
	    sb.append('\n');
	    return sb.toString();
	}
Exemplo n.º 4
0
 /**
  * Produce a comma delimited text row from a JSONArray. Values containing the comma character will
  * be quoted.
  *
  * @param ja A JSONArray of strings.
  * @return A string ending in NEWLINE.
  */
 public static String rowToString(JSONArray ja) {
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < ja.length(); i += 1) {
     if (i > 0) {
       sb.append(',');
     }
     Object o = ja.opt(i);
     if (o != null) {
       String s = o.toString();
       if (s.indexOf(',') >= 0) {
         if (s.indexOf('"') >= 0) {
           sb.append('\'');
           sb.append(s);
           sb.append('\'');
         } else {
           sb.append('"');
           sb.append(s);
           sb.append('"');
         }
       } else {
         sb.append(s);
       }
     }
   }
   sb.append('\n');
   return sb.toString();
 }
  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;
  }
Exemplo n.º 6
0
  private void getTrafficSpots() {
    controller.showProgressBar();
    String uploadWebsite =
        "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43";
    String[] ArrayOfData = null;
    StreamConnection c = null;
    InputStream s = null;
    StringBuffer b = new StringBuffer();

    String url = uploadWebsite;
    System.out.print(url);
    try {
      c = (StreamConnection) Connector.open(url);
      s = c.openDataInputStream();
      int ch;
      int k = 0;
      while ((ch = s.read()) != -1) {
        System.out.print((char) ch);
        b.append((char) ch);
      }
      // System.out.println("b"+b);
      try {
        JSONObject ff1 = new JSONObject(b.toString());
        String data1 = ff1.getString("locations");
        JSONArray jsonArray1 = new JSONArray(data1);
        Vector TrafficStatus = new Vector();
        for (int i = 0; i < jsonArray1.length(); i++) {

          System.out.println(jsonArray1.getJSONArray(i).getString(3));
          double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1));
          double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2));
          System.out.println(aDoubleLat + " " + aDoubleLon);
          TrafficStatus.addElement(
              new LocationPointer(
                  jsonArray1.getJSONArray(i).getString(3),
                  (float) aDoubleLon,
                  (float) aDoubleLat,
                  1,
                  true));
        }
        controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus));
      } catch (Exception E) {
        controller.setCurrentScreen(traf);
        new Thread() {
          public void run() {
            controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
          }
        }.start();
      }

    } catch (Exception e) {

      controller.setCurrentScreen(traf);
      new Thread() {
        public void run() {
          controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
        }
      }.start();
    }
  }
Exemplo n.º 7
0
 /**
  * Produce a JSONArray of strings from a row of comma delimited values.
  * @param x A JSONTokener of the source text.
  * @return A JSONArray of strings.
  * @throws JSONException
  */
 public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
     JSONArray ja = new JSONArray();
     for (;;) {
         String value = getValue(x);
         char c = x.next();
         if (value == null || 
         		(ja.length() == 0 && value.length() == 0 && c != ',')) {
             return null;
         }
         ja.put(value);
         for (;;) {                
             if (c == ',') {
                 break;
             }
             if (c != ' ') {
                 if (c == '\n' || c == '\r' || c == 0) {
                     return ja;
                 }
                 throw x.syntaxError("Bad character '" + c + "' (" +
                         (int)c + ").");
             }
             c = x.next();
         }
     }
 }
Exemplo n.º 8
0
                public void onSuccess(String s)
                {
                    super.onSuccess(s);
                    if (s == null || getActivity() == null)
                    {
                        return;
                    }
                    MixerBoxSharedPreferences.putAuthLoginResponse(getActivity(), s);
                    Object obj;
                    Object obj1;
                    JSONArray jsonarray;
                    obj = (new JSONObject(s)).getJSONObject("authLoginV2").getJSONObject("data");
                    obj1 = new ArrayList();
                    jsonarray = ((JSONObject) (obj)).getJSONArray("playlists");
                    int i;
                    if (android.os.Build.VERSION.SDK_INT >= 15)
                    {
                        s = "coverhq";
                    } else
                    {
                        s = "cover";
                    }
                    ((MainPage)getActivity()).myPlaylists.clear();
                    i = jsonarray.length() - 1;
_L10:
                    if (i < 0) goto _L2; else goto _L1
Exemplo n.º 9
0
 /**
  * Produce a JSONArray containing the names of the elements of this JSONObject.
  *
  * @return A JSONArray containing the key strings, or null if the JSONObject is empty.
  */
 public JSONArray names() {
   JSONArray ja = new JSONArray();
   Enumeration keys = keys();
   while (keys.hasMoreElements()) {
     ja.put(keys.nextElement());
   }
   return ja.length() == 0 ? null : ja;
 }
Exemplo n.º 10
0
 /**
  * Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied
  * JSONArray as the source of element names.
  *
  * @param names A JSONArray of strings.
  * @param x A JSONTokener of the source text.
  * @return A JSONArray of JSONObjects.
  * @throws JSONException
  */
 public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException {
   if (names == null || names.length() == 0) {
     return null;
   }
   JSONArray ja = new JSONArray();
   for (; ; ) {
     JSONObject jo = rowToJSONObject(names, x);
     if (jo == null) {
       break;
     }
     ja.put(jo);
   }
   if (ja.length() == 0) {
     return null;
   }
   return ja;
 }
Exemplo n.º 11
0
 /**
  * Produce a JSONArray containing the names of the elements of this JSONObject.
  *
  * @return A JSONArray containing the key strings, or null if the JSONObject is empty.
  */
 public JSONArray names() {
   JSONArray ja = new JSONArray();
   Iterator keys = keys();
   while (keys.hasNext()) {
     ja.put(keys.next());
   }
   return ja.length() == 0 ? null : ja;
 }
Exemplo n.º 12
0
  //
  // ONE TIME ADD VIOLATIONS
  //
  //
  private static void oneTimeAddViolations() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/violations.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
      System.out.println(e);
    }

    try {
      JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
      JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

      System.out.println("row lengths: " + rows.length());

      for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
        JSONObject element = rows.getJSONObject(j); // Get the element object

        int id = element.getInt("id");
        int citationNumber = element.getInt("citation_number");
        String violationNumber = element.getString("violation_number");
        String violationDescription = element.getString("violation_description");
        String warrantStatus = element.getString("warrant_status");
        String warrantNumber = " ";
        Boolean isWarrantNumberNull = element.isNull("warrant_number");
        if (!isWarrantNumberNull) warrantNumber = element.getString("warrant_number");
        String status = element.getString("status");
        String statusDate = element.getString("status_date");
        String fineAmount = " ";
        Boolean isFineAmountNull = element.isNull("fine_amount");
        if (!isFineAmountNull) fineAmount = element.getString("fine_amount");
        String courtCost = " ";
        Boolean isCourtCostNull = element.isNull("court_cost");
        if (!isCourtCostNull) courtCost = element.getString("court_cost");
        /*
        Map<String, AttributeValue> item = newViolationItem(citationNumber, violationNumber, violationDescription, warrantStatus, warrantNumber, status, statusDate, fineAmount, courtCost);
        PutItemRequest putItemRequest = new PutItemRequest("violations-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        */
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
Exemplo n.º 13
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String x = readTwitterFeed();
    String y = writeJSON();
    TextView tv = (TextView) findViewById(R.id.textview1);

    try {
      JSONArray jsonArray = new JSONArray(x);
      Log.i(MainActivity2.class.getName(), "Number of entries " + jsonArray.length());
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        y += jsonObject;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    tv.setText(y);
  }
 /**
  * Deserializa el bean en formato JSON
  *
  * @param json objeto que contiene los datos del bean en formato JSON
  * @throws es.tid.serial.json.JSONException Cuando se produce un error en la deserialización del
  *     objeto JSON
  */
 public void fromJSON(JSONObject json) throws JSONException {
   JSONArray jArray;
   JSONArray jObjectArray;
   jObjectArray = json.getJSONArray("literalProperties");
   this.clearLiteralProperties();
   for (int i = 0; i < jObjectArray.length(); i++) {
     JSONObject jObj_i = jObjectArray.getJSONObject(i);
     org.qualipso.advdoc.ws.client.retrieval.beans.LiteralProperty tmp =
         new org.qualipso.advdoc.ws.client.retrieval.beans.LiteralProperty();
     tmp.fromJSON(jObj_i);
     this.addLiteralProperties(tmp);
   }
   jObjectArray = json.getJSONArray("objectProperties");
   this.clearObjectProperties();
   for (int i = 0; i < jObjectArray.length(); i++) {
     JSONObject jObj_i = jObjectArray.getJSONObject(i);
     org.qualipso.advdoc.ws.client.retrieval.beans.ObjectProperty tmp =
         new org.qualipso.advdoc.ws.client.retrieval.beans.ObjectProperty();
     tmp.fromJSON(jObj_i);
     this.addObjectProperties(tmp);
   }
 }
 /**
  * Deserializa el bean en formato JSON
  *
  * @param json objeto que contiene los datos del bean en formato JSON
  * @throws es.tid.serial.json.JSONException Cuando se produce un error en la deserialización del
  *     objeto JSON
  */
 public void fromJSON(JSONObject json) throws JSONException {
   JSONArray jArray;
   JSONArray jObjectArray;
   jObjectArray = json.getJSONArray("subproperties");
   this.clearSubproperties();
   for (int i = 0; i < jObjectArray.length(); i++) {
     JSONObject jObj_i = jObjectArray.getJSONObject(i);
     org.qualipso.advdoc.ws.client.metadata.beans.ResourceElement tmp =
         new org.qualipso.advdoc.ws.client.metadata.beans.ResourceElement();
     tmp.fromJSON(jObj_i);
     this.addSubproperties(tmp);
   }
 }
Exemplo n.º 16
0
  public void googlesearch(String keyword) throws UnsupportedEncodingException {
    keyword = URLEncoder.encode(keyword, "UTF-8");
    this.keyword = keyword;
    searchResults = new GoogleSearchResult[amountOfResults];
    URL url = null;
    String urlString = generalUrl + keyword.replace("\\s+", "%20");

    try {
      // JSONArray jsonArr=null;
      JSONArray jsonArr = new JSONArray();
      int index = 0;
      for (int i = 0; i < amountOfResults; i++) {
        if (jsonArr == null || index >= jsonArr.length()) {
          url = new URL(urlString + "&start=" + i);
          URLConnection conn = url.openConnection();
          conn.addRequestProperty("Referer", "http://www.informatik.uni-trier.de/~ley/db/");
          StringBuilder builder = new StringBuilder();
          BufferedReader br =
              new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
          String line;
          while ((line = br.readLine()) != null) {
            // System.out.println(line);
            builder.append(line);
          }
          br.close();

          jsonArr =
              new JSONObject(builder.toString())
                  .getJSONObject("responseData")
                  .getJSONArray("results");
          index = 0;
        }
        JSONObject jsonObj = jsonArr.getJSONObject(index);
        GoogleSearchResult result = new GoogleSearchResult();
        result.setGSearchResultClass(jsonObj.getString("GsearchResultClass"));
        result.setUnescapedUrl(jsonObj.getString("unescapedUrl"));
        result.setUrl(jsonObj.getString("url"));
        result.setVisibleUrl(jsonObj.getString("visibleUrl"));
        result.setCacheUrl(jsonObj.getString("cacheUrl"));
        result.setTitle(jsonObj.getString("title"));
        result.setTitleNoFormatting(jsonObj.getString("titleNoFormatting"));
        result.setContent(jsonObj.getString("content"));
        searchResults[i] = result;
        ++index;
      }
    } catch (Exception e) {
      searchResults = null;
      e.printStackTrace();
    }
  }
Exemplo n.º 17
0
  private static Map<Object, String> parseObjects(JSONArray jsonArr) {
    int id = 0;
    String site = null;
    Map<Object, String> keyMap = new HashMap<Object, String>();

    try {
      for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject row = jsonArr.getJSONObject(i);
        id = row.getInt("id");
        site = row.getString("name");
        keyMap.put(id, site);
      }
    } catch (Exception ex) {
      keyMap.put(1, "No Sites Found."); // Try this but it may need to be taken out
      ex.printStackTrace();
    } finally {
      return keyMap;
    }
  }
Exemplo n.º 18
0
  /**
   * Install application/bundle.
   *
   * @param code - Operation code.
   * @param data - Data required(App data).
   */
  public void installAppBundle(String code, String data) {
    try {
      resultBuilder.build(code);

      if (code.equals(Constants.OPERATION_INSTALL_APPLICATION)) {
        JSONObject appData = new JSONObject(data);
        installApplication(appData, code);
      } else if (code.equals(Constants.OPERATION_INSTALL_APPLICATION_BUNDLE)) {
        JSONArray jArray = null;
        jArray = new JSONArray(data);
        for (int i = 0; i < jArray.length(); i++) {
          JSONObject appObj = (JSONObject) jArray.getJSONObject(i);
          installApplication(appObj, code);
        }
      }

    } catch (JSONException e) {
      Log.e(TAG, "Invalid JSON format." + e);
    }
  }
Exemplo n.º 19
0
 /**
  * Read recursively the JSON object in order to parse the content.
  *
  * @param jsonObj JSON object.
  * @param data Holds the parsed data.
  * @return Parsed data.
  * @throws ParserException If there is an error in the document format.
  */
 protected Hashtable readJSON(JSONObject jsonObj, Hashtable data) throws ParserException {
   Enumeration keys = jsonObj.keys();
   //
   while (keys.hasMoreElements()) {
     String key = keys.nextElement().toString();
     //
     if (isMember(jsonObj, key)) {
       data.put(key, readJSON(jsonObj.getJSONObject(key), new Hashtable()));
     } else if (isArray(jsonObj, key)) {
       JSONArray array = jsonObj.getJSONArray(key);
       Hashtable[] arrayObj = new Hashtable[array.length()];
       //
       for (int i = 0; i < arrayObj.length; i++) {
         arrayObj[i] = readJSON(array.getJSONObject(i), new Hashtable());
       }
       //
       data.put(key, arrayObj);
     } else {
       data.put(key, jsonObj.getString(key));
     }
   }
   //
   return data;
 }
Exemplo n.º 20
0
  /**
   * Convert a JSONObject into a well-formed, element-normal XML string.
   *
   * @param object A JSONObject.
   * @param tagName The optional name of the enclosing tag.
   * @return A string.
   * @throws JSONException
   */
  public static String toString(Object object, String tagName) throws JSONException {
    StringBuffer sb = new StringBuffer();
    int i;
    JSONArray ja;
    JSONObject jo;
    String key;
    Iterator keys;
    int length;
    String string;
    Object value;
    if (object instanceof JSONObject) {

      // Emit <tagName>

      if (tagName != null) {
        sb.append('<');
        sb.append(tagName);
        sb.append('>');
      }

      // Loop thru the keys.

      jo = (JSONObject) object;
      keys = jo.keys();
      while (keys.hasNext()) {
        key = keys.next().toString();
        value = jo.opt(key);
        if (value == null) {
          value = "";
        }
        if (value instanceof String) {
          string = (String) value;
        } else {
          string = null;
        }

        // Emit content in body

        if ("content".equals(key)) {
          if (value instanceof JSONArray) {
            ja = (JSONArray) value;
            length = ja.length();
            for (i = 0; i < length; i += 1) {
              if (i > 0) {
                sb.append('\n');
              }
              sb.append(escape(ja.get(i).toString()));
            }
          } else {
            sb.append(escape(value.toString()));
          }

          // Emit an array of similar keys

        } else if (value instanceof JSONArray) {
          ja = (JSONArray) value;
          length = ja.length();
          for (i = 0; i < length; i += 1) {
            value = ja.get(i);
            if (value instanceof JSONArray) {
              sb.append('<');
              sb.append(key);
              sb.append('>');
              sb.append(toString(value));
              sb.append("</");
              sb.append(key);
              sb.append('>');
            } else {
              sb.append(toString(value, key));
            }
          }
        } else if ("".equals(value)) {
          sb.append('<');
          sb.append(key);
          sb.append("/>");

          // Emit a new tag <k>

        } else {
          sb.append(toString(value, key));
        }
      }
      if (tagName != null) {

        // Emit the </tagname> close tag

        sb.append("</");
        sb.append(tagName);
        sb.append('>');
      }
      return sb.toString();

      // XML does not have good support for arrays. If an array appears in a place
      // where XML is lacking, synthesize an <array> element.

    } else {
      if (object.getClass().isArray()) {
        object = new JSONArray(object);
      }
      if (object instanceof JSONArray) {
        ja = (JSONArray) object;
        length = ja.length();
        for (i = 0; i < length; i += 1) {
          sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
        }
        return sb.toString();
      } else {
        string = (object == null) ? "null" : escape(object.toString());
        return (tagName == null)
            ? "\"" + string + "\""
            : (string.length() == 0)
                ? "<" + tagName + "/>"
                : "<" + tagName + ">" + string + "</" + tagName + ">";
      }
    }
  }
Exemplo n.º 21
0
  /**
   * Parse XML values and store them in a JSONArray.
   *
   * @param x The XMLTokener containing the source string.
   * @param arrayForm true if array form, false if object form.
   * @param ja The JSONArray that is containing the current tag or null if we are at the outermost
   *     level.
   * @return A JSONArray if the value is the outermost tag, otherwise null.
   * @throws JSONException
   */
  private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException {
    String attribute;
    char c;
    String closeTag = null;
    int i;
    JSONArray newja = null;
    JSONObject newjo = null;
    Object token;
    String tagName = null;

    // Test for and skip past these forms:
    //      <!-- ... -->
    //      <![  ... ]]>
    //      <!   ...   >
    //      <?   ...  ?>

    while (true) {
      if (!x.more()) {
        throw x.syntaxError("Bad XML");
      }
      token = x.nextContent();
      if (token == XML.LT) {
        token = x.nextToken();
        if (token instanceof Character) {
          if (token == XML.SLASH) {

            // Close tag </

            token = x.nextToken();
            if (!(token instanceof String)) {
              throw new JSONException("Expected a closing name instead of '" + token + "'.");
            }
            if (x.nextToken() != XML.GT) {
              throw x.syntaxError("Misshaped close tag");
            }
            return token;
          } else if (token == XML.BANG) {

            // <!

            c = x.next();
            if (c == '-') {
              if (x.next() == '-') {
                x.skipPast("-->");
              } else {
                x.back();
              }
            } else if (c == '[') {
              token = x.nextToken();
              if (token.equals("CDATA") && x.next() == '[') {
                if (ja != null) {
                  ja.put(x.nextCDATA());
                }
              } else {
                throw x.syntaxError("Expected 'CDATA['");
              }
            } else {
              i = 1;
              do {
                token = x.nextMeta();
                if (token == null) {
                  throw x.syntaxError("Missing '>' after '<!'.");
                } else if (token == XML.LT) {
                  i += 1;
                } else if (token == XML.GT) {
                  i -= 1;
                }
              } while (i > 0);
            }
          } else if (token == XML.QUEST) {

            // <?

            x.skipPast("?>");
          } else {
            throw x.syntaxError("Misshaped tag");
          }

          // Open tag <

        } else {
          if (!(token instanceof String)) {
            throw x.syntaxError("Bad tagName '" + token + "'.");
          }
          tagName = (String) token;
          newja = new JSONArray();
          newjo = new JSONObject();
          if (arrayForm) {
            newja.put(tagName);
            if (ja != null) {
              ja.put(newja);
            }
          } else {
            newjo.put("tagName", tagName);
            if (ja != null) {
              ja.put(newjo);
            }
          }
          token = null;
          for (; ; ) {
            if (token == null) {
              token = x.nextToken();
            }
            if (token == null) {
              throw x.syntaxError("Misshaped tag");
            }
            if (!(token instanceof String)) {
              break;
            }

            // attribute = value

            attribute = (String) token;
            if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
              throw x.syntaxError("Reserved attribute.");
            }
            token = x.nextToken();
            if (token == XML.EQ) {
              token = x.nextToken();
              if (!(token instanceof String)) {
                throw x.syntaxError("Missing value");
              }
              newjo.accumulate(attribute, XML.stringToValue((String) token));
              token = null;
            } else {
              newjo.accumulate(attribute, "");
            }
          }
          if (arrayForm && newjo.length() > 0) {
            newja.put(newjo);
          }

          // Empty tag <.../>

          if (token == XML.SLASH) {
            if (x.nextToken() != XML.GT) {
              throw x.syntaxError("Misshaped tag");
            }
            if (ja == null) {
              if (arrayForm) {
                return newja;
              } else {
                return newjo;
              }
            }

            // Content, between <...> and </...>

          } else {
            if (token != XML.GT) {
              throw x.syntaxError("Misshaped tag");
            }
            closeTag = (String) parse(x, arrayForm, newja);
            if (closeTag != null) {
              if (!closeTag.equals(tagName)) {
                throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'");
              }
              tagName = null;
              if (!arrayForm && newja.length() > 0) {
                newjo.put("childNodes", newja);
              }
              if (ja == null) {
                if (arrayForm) {
                  return newja;
                } else {
                  return newjo;
                }
              }
            }
          }
        }
      } else {
        if (ja != null) {
          ja.put(token instanceof String ? XML.stringToValue((String) token) : token);
        }
      }
    }
  }
Exemplo n.º 22
0
  /**
   * Reverse the JSONML transformation, making an XML text from a JSONObject. The JSONObject must
   * contain a "tagName" property. If it has children, then it must have a "childNodes" property
   * containing an array of objects. The other properties are attributes with string values.
   *
   * @param jo A JSONObject.
   * @return An XML string.
   * @throws JSONException
   */
  public static String toString(JSONObject jo) throws JSONException {
    StringBuilder sb = new StringBuilder();
    int i;
    JSONArray ja;
    String key;
    Iterator<String> keys;
    int length;
    Object object;
    String tagName;
    String value;

    // Emit <tagName

    tagName = jo.optString("tagName");
    if (tagName == null) {
      return XML.escape(jo.toString());
    }
    XML.noSpace(tagName);
    tagName = XML.escape(tagName);
    sb.append('<');
    sb.append(tagName);

    // Emit the attributes

    keys = jo.keys();
    while (keys.hasNext()) {
      key = keys.next();
      if (!"tagName".equals(key) && !"childNodes".equals(key)) {
        XML.noSpace(key);
        value = jo.optString(key);
        if (value != null) {
          sb.append(' ');
          sb.append(XML.escape(key));
          sb.append('=');
          sb.append('"');
          sb.append(XML.escape(value));
          sb.append('"');
        }
      }
    }

    // Emit content in body

    ja = jo.optJSONArray("childNodes");
    if (ja == null) {
      sb.append('/');
      sb.append('>');
    } else {
      sb.append('>');
      length = ja.length();
      for (i = 0; i < length; i += 1) {
        object = ja.get(i);
        if (object != null) {
          if (object instanceof String) {
            sb.append(XML.escape(object.toString()));
          } else if (object instanceof JSONObject) {
            sb.append(toString((JSONObject) object));
          } else if (object instanceof JSONArray) {
            sb.append(toString((JSONArray) object));
          } else {
            sb.append(object.toString());
          }
        }
      }
      sb.append('<');
      sb.append('/');
      sb.append(tagName);
      sb.append('>');
    }
    return sb.toString();
  }
Exemplo n.º 23
0
  /**
   * Reverse the JSONML transformation, making an XML text from a JSONArray.
   *
   * @param ja A JSONArray.
   * @return An XML string.
   * @throws JSONException
   */
  public static String toString(JSONArray ja) throws JSONException {
    int i;
    JSONObject jo;
    String key;
    Iterator<String> keys;
    int length;
    Object object;
    StringBuilder sb = new StringBuilder();
    String tagName;
    String value;

    // Emit <tagName

    tagName = ja.getString(0);
    XML.noSpace(tagName);
    tagName = XML.escape(tagName);
    sb.append('<');
    sb.append(tagName);

    object = ja.opt(1);
    if (object instanceof JSONObject) {
      i = 2;
      jo = (JSONObject) object;

      // Emit the attributes

      keys = jo.keys();
      while (keys.hasNext()) {
        key = keys.next();
        XML.noSpace(key);
        value = jo.optString(key);
        if (value != null) {
          sb.append(' ');
          sb.append(XML.escape(key));
          sb.append('=');
          sb.append('"');
          sb.append(XML.escape(value));
          sb.append('"');
        }
      }
    } else {
      i = 1;
    }

    // Emit content in body

    length = ja.length();
    if (i >= length) {
      sb.append('/');
      sb.append('>');
    } else {
      sb.append('>');
      do {
        object = ja.get(i);
        i += 1;
        if (object != null) {
          if (object instanceof String) {
            sb.append(XML.escape(object.toString()));
          } else if (object instanceof JSONObject) {
            sb.append(toString((JSONObject) object));
          } else if (object instanceof JSONArray) {
            sb.append(toString((JSONArray) object));
          }
        }
      } while (i < length);
      sb.append('<');
      sb.append('/');
      sb.append(tagName);
      sb.append('>');
    }
    return sb.toString();
  }
Exemplo n.º 24
0
  //
  // ONE TIME ADD CITATIONS
  //
  //
  private static void oneTimeAddCitations() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/citations.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
      System.out.println(e);
    }

    try {
      JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
      JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

      System.out.println("row lengths: " + rows.length());

      set1 = new HashSet<>();

      for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
        JSONObject element = rows.getJSONObject(j); // Get the element object

        int id = element.getInt("id");
        int citationNumber = element.getInt("citation_number");
        String citationDate = " ";
        Boolean isCitationDateNull = element.isNull("citation_date");
        if (!isCitationDateNull) citationDate = element.getString("citation_date");
        String firstName = element.getString("first_name");
        String lastName = element.getString("last_name");
        String firstLastName = firstName + lastName;
        firstLastName = firstLastName.toLowerCase();
        set1.add(firstLastName);

        // System.out.println(firstLastName);
        String dob = " ";
        Boolean isDobNull = element.isNull("date_of_birth");
        if (!isDobNull) {
          dob = element.getString("date_of_birth");
          dob = (dob.split(" "))[0];
        }

        // pick a ssn from list
        String ssn = ssnList.get(ssnCounter);
        ssnCounter--;
        ssnHashMap.put(firstLastName, ssn);

        System.out.println(firstLastName + " " + ssn);

        // compute salt
        final Random ran = new SecureRandom();
        byte[] salt = new byte[32];
        ran.nextBytes(salt);
        String saltString = Base64.encodeBase64String(salt);

        // System.out.println("saltstring: " + saltString);
        saltHashMap.put(firstLastName, saltString);

        // compute ripemd160 hash of ssn + salt
        String saltPlusSsn = saltString + ssn;
        // System.out.println("salt plus ssn: " + saltPlusSsn);

        String resultingHash = "";
        try {
          byte[] r = saltPlusSsn.getBytes("US-ASCII");
          RIPEMD160Digest d = new RIPEMD160Digest();
          d.update(r, 0, r.length);
          byte[] o = new byte[d.getDigestSize()];
          d.doFinal(o, 0);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
          Hex.encode(o, baos);
          resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

          hashedssnHashMap.put(firstLastName, resultingHash);
        } catch (UnsupportedEncodingException e) {
          System.out.println(e);
        } catch (IOException i) {
          System.out.println(i);
        }

        String fldob = firstLastName + dob;
        String da = " ";
        Boolean isDaNull = element.isNull("defendant_address");
        if (!isDaNull) da = element.getString("defendant_address");
        String dc = " ";
        Boolean isDcNull = element.isNull("defendant_city");
        if (!isDcNull) dc = element.getString("defendant_city");
        String ds = " ";
        Boolean isDsNull = element.isNull("defendant_state");
        if (!isDsNull) ds = element.getString("defendant_state");
        String dln = " ";
        Boolean isDlnNull = element.isNull("drivers_license_number");
        if (!isDlnNull) dln = element.getString("drivers_license_number");
        String cd = " ";
        Boolean isCdNull = element.isNull("court_date");
        if (!isCdNull) cd = element.getString("court_date");
        String cl = " ";
        Boolean isClNull = element.isNull("court_location");
        if (!isClNull) cl = element.getString("court_location");
        String ca = " ";
        Boolean isCaNull = element.isNull("court_address");
        if (!isCaNull) ca = element.getString("court_address");
        /*
        Map<String, AttributeValue> item = newCitationItem(citationNumber, citationDate, firstName, lastName, firstLastName, dob, fldob, resultingHash, da, dc, ds, dln, cd, cl, ca);
        PutItemRequest putItemRequest = new PutItemRequest("citations-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        */
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
Exemplo n.º 25
0
  //
  // ONE TIME ADD WARRANTS
  //
  //
  private static void oneTimeAddWarrants() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/warrants.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
      System.out.println(e);
    }

    try {
      JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
      JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

      // System.out.println("row lengths: " + rows.length());

      set2 = new HashSet<>();

      for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
        JSONObject element = rows.getJSONObject(j); // Get the element object

        String defendant = element.getString("Defendant");

        String strarr[] = defendant.split(" ");
        String temp = strarr[1];
        int len = strarr[0].length();
        strarr[0] = strarr[0].substring(0, len - 1);
        strarr[1] = strarr[0];
        strarr[0] = temp;

        String firstLast = strarr[0] + strarr[1];
        firstLast = firstLast.toLowerCase();

        set2.add(firstLast);
        // System.out.println(firstLast);

        int zipCode = 0;
        Boolean isZipCodeNull = element.isNull("ZIP Code");
        if (!isZipCodeNull) zipCode = element.getInt("ZIP Code");
        String dob = element.getString("Date of Birth");
        String caseNumber = element.getString("Case Number");

        String firstLastDOB = firstLast + dob;

        // pick a ssn from list
        String ssn = ssnList.get(ssnCounter);
        ssnCounter--;
        ssnHashMap.put(firstLast, ssn);

        // compute salt
        final Random ran = new SecureRandom();
        byte[] salt = new byte[32];
        ran.nextBytes(salt);
        String saltString = Base64.encodeBase64String(salt);

        // System.out.println("saltstring: " + saltString);
        saltHashMap.put(firstLast, saltString);

        // compute ripemd160 hash of ssn + salt
        String saltPlusSsn = saltString + ssn;
        // System.out.println("salt plus ssn: " + saltPlusSsn);

        String resultingHash = "";
        try {
          byte[] r = saltPlusSsn.getBytes("US-ASCII");
          RIPEMD160Digest d = new RIPEMD160Digest();
          d.update(r, 0, r.length);
          byte[] o = new byte[d.getDigestSize()];
          d.doFinal(o, 0);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
          Hex.encode(o, baos);
          resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

          hashedssnHashMap.put(firstLast, resultingHash);
        } catch (UnsupportedEncodingException e) {
          System.out.println(e);
        } catch (IOException i) {
          System.out.println(i);
        }

        // compareNames();

        Map<String, AttributeValue> item =
            newWarrantItem(
                firstLast, firstLastDOB, resultingHash, defendant, zipCode, dob, caseNumber);
        PutItemRequest putItemRequest = new PutItemRequest("warrants-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
  /**
   * Enrich portClassHier with class/interface names that map to a list of parent
   * classes/interfaces. For any class encountered, find its parents too.<br>
   * Also find the port types which have assignable schema classes.
   *
   * @param oper Operator to work on
   * @param portClassHierarchy In-Out param that contains a mapping of class/interface to its
   *     parents
   * @param portTypesWithSchemaClasses Json that will contain all the ports which have any schema
   *     classes.
   */
  public void buildAdditionalPortInfo(
      JSONObject oper, JSONObject portClassHierarchy, JSONObject portTypesWithSchemaClasses) {
    try {
      JSONArray ports = oper.getJSONArray(OperatorDiscoverer.PORT_TYPE_INFO_KEY);
      for (int i = 0; i < ports.length(); i++) {
        JSONObject port = ports.getJSONObject(i);

        String portType = port.optString("type");
        if (portType == null) {
          // skipping if port type is null
          continue;
        }

        if (typeGraph.size() == 0) {
          buildTypeGraph();
        }

        try {
          // building port class hierarchy
          LinkedList<String> queue = Lists.newLinkedList();
          queue.add(portType);
          while (!queue.isEmpty()) {
            String currentType = queue.remove();
            if (portClassHierarchy.has(currentType)) {
              // already present in the json so we skip.
              continue;
            }
            List<String> immediateParents = typeGraph.getParents(currentType);
            if (immediateParents == null) {
              portClassHierarchy.put(currentType, Lists.<String>newArrayList());
              continue;
            }
            portClassHierarchy.put(currentType, immediateParents);
            queue.addAll(immediateParents);
          }
        } catch (JSONException e) {
          LOG.warn("building port type hierarchy {}", portType, e);
        }

        // finding port types with schema classes
        if (portTypesWithSchemaClasses.has(portType)) {
          // already present in the json so skipping
          continue;
        }
        if (portType.equals("byte")
            || portType.equals("short")
            || portType.equals("char")
            || portType.equals("int")
            || portType.equals("long")
            || portType.equals("float")
            || portType.equals("double")
            || portType.equals("java.lang.String")
            || portType.equals("java.lang.Object")) {
          // ignoring primitives, strings and object types as this information is needed only for
          // complex types.
          continue;
        }
        if (port.has("typeArgs")) {
          // ignoring any type with generics
          continue;
        }
        boolean hasSchemaClasses = false;
        List<String> instantiableDescendants = typeGraph.getInstantiableDescendants(portType);
        if (instantiableDescendants != null) {
          for (String descendant : instantiableDescendants) {
            try {
              if (typeGraph.isInstantiableBean(descendant)) {
                hasSchemaClasses = true;
                break;
              }
            } catch (JSONException ex) {
              LOG.warn("checking descendant is instantiable {}", descendant);
            }
          }
        }
        portTypesWithSchemaClasses.put(portType, hasSchemaClasses);
      }
    } catch (JSONException e) {
      // should not reach this
      LOG.error("JSON Exception {}", e);
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 27
0
  /**
   * Convert a JSONObject into a well-formed, element-normal XML string.
   *
   * @param o A JSONObject.
   * @param tagName The optional name of the enclosing tag.
   * @return A string.
   * @throws JSONException
   */
  public static String toString(Object o, String tagName) throws JSONException {
    StringBuffer b = new StringBuffer();
    int i;
    JSONArray ja;
    JSONObject jo;
    String k;
    Iterator<?> keys;
    int len;
    String s;
    Object v;
    if (o instanceof JSONObject) {

      // Emit <tagName>

      if (tagName != null) {
        b.append('<');
        b.append(tagName);
        b.append('>');
      }

      // Loop thru the keys.

      jo = (JSONObject) o;
      keys = jo.keys();
      while (keys.hasNext()) {
        k = keys.next().toString();
        v = jo.opt(k);
        if (v == null) {
          v = "";
        }
        if (v instanceof String) {
          s = (String) v;
        } else {
          s = null;
        }

        // Emit content in body

        if (k.equals("content")) {
          if (v instanceof JSONArray) {
            ja = (JSONArray) v;
            len = ja.length();
            for (i = 0; i < len; i += 1) {
              if (i > 0) {
                b.append('\n');
              }
              b.append(escape(ja.get(i).toString()));
            }
          } else {
            b.append(escape(v.toString()));
          }

          // Emit an array of similar keys

        } else if (v instanceof JSONArray) {
          ja = (JSONArray) v;
          len = ja.length();
          for (i = 0; i < len; i += 1) {
            v = ja.get(i);
            if (v instanceof JSONArray) {
              b.append('<');
              b.append(k);
              b.append('>');
              b.append(toString(v));
              b.append("</");
              b.append(k);
              b.append('>');
            } else {
              b.append(toString(v, k));
            }
          }
        } else if (v.equals("")) {
          b.append('<');
          b.append(k);
          b.append("/>");

          // Emit a new tag <k>

        } else {
          b.append(toString(v, k));
        }
      }
      if (tagName != null) {

        // Emit the </tagname> close tag

        b.append("</");
        b.append(tagName);
        b.append('>');
      }
      return b.toString();

      // XML does not have good support for arrays. If an array appears in a place
      // where XML is lacking, synthesize an <array> element.

    } else if (o instanceof JSONArray) {
      ja = (JSONArray) o;
      len = ja.length();
      for (i = 0; i < len; ++i) {
        v = ja.opt(i);
        b.append(toString(v, (tagName == null) ? "array" : tagName));
      }
      return b.toString();
    } else {
      s = (o == null) ? "null" : escape(o.toString());
      return (tagName == null)
          ? "\"" + s + "\""
          : (s.length() == 0)
              ? "<" + tagName + "/>"
              : "<" + tagName + ">" + s + "</" + tagName + ">";
    }
  }