Ejemplo n.º 1
0
  private JSONObject castEventToJSONObj(Event event) {
    JSONObject jsonObj = new JSONObject();

    DateFormat dfDeadline = new SimpleDateFormat("yyyy-M-dd");
    Date deadLine = null;

    try {
      deadLine = dfDeadline.parse("1970-01-01");
    } catch (ParseException e) {
      e.printStackTrace();
    }

    try {
      jsonObj.put("name", event.getName());
      jsonObj.put("description", event.getDescription());
      jsonObj.put("category", event.getCategory());
      jsonObj.put("status", event.getStatus());
      jsonObj.put("location", event.getLocation());

      if (event.getCategory().equals(GenericEvent.Category.DEADLINE)) {
        jsonObj.put("startTime", deadLine);
        jsonObj.put("endTime", event.getEndTime());
      } else {
        jsonObj.put("startTime", event.getStartTime());
        jsonObj.put("endTime", event.getEndTime());
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return jsonObj;
  }
Ejemplo n.º 2
0
  private Event castJSONObjToEvent(JSONObject jsonObj) {
    Event event = new Event();
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);

    try {
      String startTime = jsonObj.get("startTime").toString();
      String endTime = jsonObj.get("endTime").toString();

      event.setName(jsonObj.getString("name"));
      event.setDescription(jsonObj.getString("description"));
      event.setCategory(getCategory(jsonObj));
      event.setStatus(getStatus(jsonObj));
      event.setLocation(jsonObj.getString("location"));

      if (event.getCategory().equals(GenericEvent.Category.FLOATING)) {
        // doesn't set start time and end time
      } else {
        event.setStartTime(df.parse(startTime));
        event.setEndTime(df.parse(endTime));
      }

    } catch (JSONException e2) {
      e2.printStackTrace();
    } catch (ParseException e1) {
      e1.printStackTrace();
    }

    return event;
  }
Ejemplo n.º 3
0
  /**
   * Configure device WIFI profile.
   *
   * @param code - Operation code.
   * @param data - Data required(SSID, Password).
   * @param requestMode - Request mode(Normal mode or policy bundle mode).
   */
  public void configureWifi(String code, String data) {
    boolean wifistatus = false;
    String ssid = null;
    String password = null;

    try {
      JSONObject wifiData = new JSONObject(data);
      if (!wifiData.isNull(resources.getString(R.string.intent_extra_ssid))) {
        ssid = (String) wifiData.get(resources.getString(R.string.intent_extra_ssid));
      }
      if (!wifiData.isNull(resources.getString(R.string.intent_extra_password))) {
        password = (String) wifiData.get(resources.getString(R.string.intent_extra_password));
      }
    } catch (JSONException e) {
      Log.e(TAG, "Invalid JSON format " + e.toString());
    }

    WiFiConfig config = new WiFiConfig(context.getApplicationContext());

    wifistatus = config.saveWEPConfig(ssid, password);

    String status = null;
    if (wifistatus) {
      status = resources.getString(R.string.shared_pref_default_status);
    } else {
      status = resources.getString(R.string.shared_pref_false_status);
    }

    resultBuilder.build(code, status);
  }
Ejemplo n.º 4
0
 private void testJSONArray(Object array, String expected) {
   try {
     JSONArray jsonArray = JSONArray.fromObject(array);
     assertEquals(expected, jsonArray.toString());
   } catch (JSONException jsone) {
     fail(jsone.getMessage());
   }
 }
Ejemplo n.º 5
0
 public String WriteJSON() {
   JSONObject object = new JSONObject();
   try {
     object.put("name", "Jack Hack");
     object.put("score", new Integer(200));
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return object.toString();
 }
Ejemplo n.º 6
0
 public JSONObject toJSON() {
   JSONObject jsonobject = new JSONObject();
   try {
     jsonobject.put("data_type", dataType.getName());
     jsonobject.put("value", value);
   } catch (JSONException jsonexception) {
     jsonexception.printStackTrace();
     return jsonobject;
   }
   return jsonobject;
 }
Ejemplo n.º 7
0
  public State readStorage(String fileName) {
    String line = null;
    State state = new State();
    String jsonData = "";

    try {
      FileReader fr = new FileReader(fileName);
      BufferedReader br = new BufferedReader(fr);

      while ((line = br.readLine()) != null) {
        jsonData += line + "\n";
      }

      if (jsonData.contains("{")) {
        JSONObject object = new JSONObject(jsonData);

        JSONArray arrCompleted = object.getJSONArray("completed");
        JSONArray arrIncompleted = object.getJSONArray("incompleted");
        JSONArray arrUndetermined = object.getJSONArray("undetermined");
        JSONArray arrReserved = object.getJSONArray("reserved");

        for (int i = 0; i < arrCompleted.length(); i++) {
          Event e = castJSONObjToEvent(arrCompleted.getJSONObject(i));
          state.completedEvents.add(e);
        }
        for (int i = 0; i < arrIncompleted.length(); i++) {
          Event e = castJSONObjToEvent(arrIncompleted.getJSONObject(i));
          state.incompletedEvents.add(e);
        }
        for (int i = 0; i < arrUndetermined.length(); i++) {
          ReservedEvent e = castJSONObjToFloatingEvent(arrUndetermined.getJSONObject(i));
          state.undeterminedEvents.add(e);
        }
        for (int i = 0; i < arrReserved.length(); i++) {
          ReservedEvent e = castJSONObjToReservedEvent(arrReserved.getJSONObject(i));
          state.reservedEvents.add(e);
        }
      }
    } catch (FileNotFoundException ex) {
      System.out.println("Unable to open file '" + fileName + "'");
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    updatedDisplayedEvents(state);

    return state;
  }
Ejemplo n.º 8
0
 /** Attempts to create a CookieList from a malformed string. Expects a JSONException. */
 @Test
 public void malFormedCookieListException() {
   String cookieStr = "thisCookieHasNoEqualsChar";
   try {
     CookieList.toJSONObject(cookieStr);
     assertTrue("should throw an exception", false);
   } catch (JSONException e) {
     /** Not sure of the missing char, but full string compare fails */
     assertTrue(
         "Expecting an exception message",
         e.getMessage().startsWith("Expected '=' and instead saw '")
             && e.getMessage().endsWith("' at 27 [character 28 line 1]"));
   }
 }
Ejemplo n.º 9
0
  public void stateToStorage(State completeState, String fileName) {
    clearFile(fileName);

    JSONArray arrCompleted = new JSONArray();
    JSONArray arrIncompleted = new JSONArray();
    JSONArray arrUndetermined = new JSONArray();
    JSONArray arrReserved = new JSONArray();

    for (Event e : completeState.completedEvents) {
      JSONObject object = new JSONObject();
      object = castEventToJSONObj(e);
      arrCompleted.put(object);
    }
    for (Event e : completeState.incompletedEvents) {
      JSONObject object = new JSONObject();
      object = castEventToJSONObj(e);
      arrIncompleted.put(object);
    }
    for (ReservedEvent e : completeState.undeterminedEvents) {
      JSONObject object = new JSONObject();
      object = castFloatingEventToJSONObj(e);
      arrUndetermined.put(object);
    }
    for (ReservedEvent e : completeState.reservedEvents) {
      JSONObject object = new JSONObject();
      object = castReservedEventToJSONObj(e);
      arrReserved.put(object);
    }

    JSONObject o = new JSONObject();
    try {
      o.put("completed", arrCompleted);
      o.put("incompleted", arrIncompleted);
      o.put("undetermined", arrUndetermined);
      o.put("reserved", arrReserved);
    } catch (JSONException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try {
      FileWriter fw = new FileWriter(fileName, true);
      PrintWriter pw = new PrintWriter(fw);
      pw.println(o.toString());
      pw.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
Ejemplo n.º 10
0
  private ReservedEvent castJSONObjToFloatingEvent(JSONObject jsonObj) {
    ReservedEvent event = new ReservedEvent();
    try {
      event.setName(jsonObj.getString("name"));
      event.setDescription(jsonObj.getString("description"));
      event.setCategory(getCategory(jsonObj));
      event.setStatus(getStatus(jsonObj));
      event.setLocation(jsonObj.getString("location"));

    } catch (JSONException e2) {
      e2.printStackTrace();
    }

    return event;
  }
Ejemplo n.º 11
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();
    }
  }
Ejemplo n.º 12
0
  private JSONObject castFloatingEventToJSONObj(ReservedEvent event) {
    JSONObject jsonObj = new JSONObject();

    try {
      jsonObj.put("name", event.getName());
      jsonObj.put("description", event.getDescription());
      jsonObj.put("category", event.getCategory());
      jsonObj.put("status", event.getStatus());
      jsonObj.put("location", event.getLocation());
      jsonObj.put("startTime", "");
      jsonObj.put("endTime", "");
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return jsonObj;
  }
Ejemplo n.º 13
0
  private ReservedEvent castJSONObjToReservedEvent(JSONObject jsonObj) {
    ReservedEvent event = new ReservedEvent();
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
    int max = 100;
    int count = 0;

    try {
      event.setName(jsonObj.getString("name"));
      event.setDescription(jsonObj.getString("description"));
      event.setCategory(getCategory(jsonObj));
      event.setStatus(getStatus(jsonObj));
      event.setLocation(jsonObj.getString("location"));

      for (int i = 0; i < 100; i++) {
        try {
          jsonObj.getString("startTime" + i);
        } catch (JSONException e) {
          count = i;
          break;
        }
      }

      ArrayList<TimePair> reservedTimes = new ArrayList<TimePair>();
      for (int i = 0; i < count; i++) {
        TimePair t =
            new TimePair(
                df.parse(jsonObj.get("startTime" + i).toString()),
                df.parse(jsonObj.get("endTime" + i).toString()));
        reservedTimes.add(t);
      }

      event.setReservedTimes(reservedTimes);

    } catch (JSONException e2) {
      e2.printStackTrace();
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return event;
  }
Ejemplo n.º 14
0
 public static Object parse(String json) throws ShellException {
   try {
     final String input = json.trim();
     if (input.isEmpty()) {
       return null;
     }
     if (input.charAt(0) == '{') {
       return new JSONObject(input).toMap();
     }
     if (input.charAt(0) == '[') {
       return new JSONArray(input).toList();
     }
     final Object value = JSONObject.stringToValue(input);
     if (value.equals(null)) {
       return null;
     }
     return value;
   } catch (JSONException e) {
     throw new ShellException("Could not parse value " + json + " " + e.getMessage());
   }
 }
Ejemplo n.º 15
0
  private void init(JSONObject json) throws TwitterException {
    id = ParseUtil.getLong("id", json);
    name = ParseUtil.getRawString("name", json);
    fullName = ParseUtil.getRawString("full_name", json);
    slug = ParseUtil.getRawString("slug", json);
    description = ParseUtil.getRawString("description", json);
    subscriberCount = ParseUtil.getInt("subscriber_count", json);
    memberCount = ParseUtil.getInt("member_count", json);
    uri = ParseUtil.getRawString("uri", json);
    mode = "public".equals(ParseUtil.getRawString("mode", json));
    following = ParseUtil.getBoolean("following", json);
    createdAt = ParseUtil.getDate("created_at", json);

    try {
      if (!json.isNull("user")) {
        user = new UserJSONImpl(json.getJSONObject("user"));
      }
    } catch (JSONException jsone) {
      throw new TwitterException(jsone.getMessage() + ":" + json.toString(), jsone);
    }
  }
Ejemplo n.º 16
0
  private JSONObject castReservedEventToJSONObj(ReservedEvent event) {
    JSONObject jsonObj = new JSONObject();

    try {
      jsonObj.put("name", event.getName());
      jsonObj.put("description", event.getDescription());
      jsonObj.put("category", event.getCategory());
      jsonObj.put("status", event.getStatus());
      jsonObj.put("location", event.getLocation());

      int count = event.getReservedTimes().size();
      for (int i = 0; i < count; i++) {
        jsonObj.put("startTime" + i, event.getReservedTimes().get(i).getStartTime());
        jsonObj.put("endTime" + i, event.getReservedTimes().get(i).getEndTime());
      }
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return jsonObj;
  }
Ejemplo n.º 17
0
  /**
   * Process HTTP request.
   *
   * @param act Action.
   * @param req Http request.
   * @param res Http response.
   */
  private void processRequest(String act, HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");

    GridRestCommand cmd = command(req);

    if (cmd == null) {
      res.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return;
    }

    if (!authChecker.apply(req.getHeader("X-Signature"))) {
      res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      return;
    }

    GridRestResponse cmdRes;

    Map<String, Object> params = parameters(req);

    try {
      GridRestRequest cmdReq = createRequest(cmd, params, req);

      if (log.isDebugEnabled()) log.debug("Initialized command request: " + cmdReq);

      cmdRes = hnd.handle(cmdReq);

      if (cmdRes == null)
        throw new IllegalStateException("Received null result from handler: " + hnd);

      byte[] sesTok = cmdRes.sessionTokenBytes();

      if (sesTok != null) cmdRes.setSessionToken(U.byteArray2HexString(sesTok));

      res.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
      res.setStatus(HttpServletResponse.SC_OK);

      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      cmdRes = new GridRestResponse(STATUS_FAILED, e.getMessage());
    } catch (Throwable e) {
      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      throw e;
    }

    JsonConfig cfg = new GridJettyJsonConfig();

    // Workaround for not needed transformation of string into JSON object.
    if (cmdRes.getResponse() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getClass(), "response", SKIP_STR_VAL_PROC);

    if (cmdRes.getResponse() instanceof GridClientTaskResultBean
        && ((GridClientTaskResultBean) cmdRes.getResponse()).getResult() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getResponse().getClass(), "result", SKIP_STR_VAL_PROC);

    JSON json;

    try {
      json = JSONSerializer.toJSON(cmdRes, cfg);
    } catch (JSONException e) {
      U.error(log, "Failed to convert response to JSON: " + cmdRes, e);

      json = JSONSerializer.toJSON(new GridRestResponse(STATUS_FAILED, e.getMessage()), cfg);
    }

    try {
      if (log.isDebugEnabled())
        log.debug("Parsed command response into JSON object: " + json.toString(2));

      res.getWriter().write(json.toString());

      if (log.isDebugEnabled())
        log.debug(
            "Processed HTTP request [action=" + act + ", jsonRes=" + cmdRes + ", req=" + req + ']');
    } catch (IOException e) {
      U.error(log, "Failed to send HTTP response: " + json.toString(2), e);
    }
  }
Ejemplo n.º 18
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();
    }
  }
Ejemplo n.º 19
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();
    }
  }
Ejemplo n.º 20
0
    /**
     * Handles an activity result that's part of the purchase flow in in-app billing. If you
     * are calling {@link #launchPurchaseFlow}, then you must call this method from your
     * Activity's {@link android.app.Activity@onActivityResult} method. This method
     * MUST be called from the UI thread of the Activity.
     *
     * @param requestCode The requestCode as you received it.
     * @param resultCode The resultCode as you received it.
     * @param data The data (Intent) as you received it.
     * @return Returns true if the result was related to a purchase flow and was handled;
     *     false if the result was not related to a purchase, in which case you should
     *     handle it normally.
     */
    public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
        IabResult result;
        if (requestCode != mRequestCode) return false;

        checkNotDisposed();
        checkSetupDone("handleActivityResult");

        // end of async purchase operation that started on launchPurchaseFlow
        flagEndAsync();

        if (data == null) {
            logError("Null data in IAB activity result.");
            result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result");
            if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
            return true;
        }

        int responseCode = getResponseCodeFromIntent(data);
        String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA);
        String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE);

        if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) {
            logDebug("Successful resultcode from purchase activity.");
            logDebug("Purchase data: " + purchaseData);
            logDebug("Data signature: " + dataSignature);
            logDebug("Extras: " + data.getExtras());
            logDebug("Expected item type: " + mPurchasingItemType);

            if (purchaseData == null || dataSignature == null) {
                logError("BUG: either purchaseData or dataSignature is null.");
                logDebug("Extras: " + data.getExtras().toString());
                result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature");
                if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
                return true;
            }

            Purchase purchase = null;
            try {
                purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature);
                String sku = purchase.getSku();

                // Verify signature
                if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) {
                    logError("Purchase signature verification FAILED for sku " + sku);
                    result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku);
                    if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase);
                    return true;
                }
                logDebug("Purchase signature successfully verified.");
            }
            catch (JSONException e) {
                logError("Failed to parse purchase data.");
                e.printStackTrace();
                result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
                if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
                return true;
            }

            if (mPurchaseListener != null) {
                mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase);
            }
        }
        else if (resultCode == Activity.RESULT_OK) {
            // result code was OK, but in-app billing response was not OK.
            logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode));
            if (mPurchaseListener != null) {
                result = new IabResult(responseCode, "Problem purchashing item.");
                mPurchaseListener.onIabPurchaseFinished(result, null);
            }
        }
        else if (resultCode == Activity.RESULT_CANCELED) {
            logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode));
            result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled.");
            if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
        }
        else {
            logError("Purchase failed. Result code: " + Integer.toString(resultCode)
                    + ". Response: " + getResponseDesc(responseCode));
            result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response.");
            if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
        }
        return true;
    }
Ejemplo n.º 21
0
  public List<Tweet> readFile(String fileLocation, int limit, String fromTweetId) {

    long startTime = System.currentTimeMillis();

    int errors = 0;
    int added = 0;
    int ignored = 0;
    int skipped = 0;

    List<Tweet> tweets = new ArrayList<Tweet>();

    try {

      // Read gzFile
      InputStream inputStream = new GZIPInputStream(new FileInputStream(fileLocation));
      Reader decoder = new InputStreamReader(inputStream);
      BufferedReader br = new BufferedReader(decoder);

      String status;

      while ((status = br.readLine()) != null) {

        // Ignore garbage and log output lines, all statuses start with JSON bracket
        if (!status.equals("") && status.charAt(0) == '{') {
          try {
            JSONObject jsonObject = new JSONObject(status);

            // We use created_at as an indicator that this is a Tweet.
            if (jsonObject.has("created_at")) {

              Status statusObject = TwitterObjectFactory.createStatus(status);

              Tweet tweet = this.getTweetObjectFromStatus(statusObject);

              if (fromTweetId != null) {

                if (fromTweetId.equals(tweet.getId())) {
                  this.log.write("StatusFileReader - Scanner pickup from " + fromTweetId);
                  fromTweetId = null;
                } else {
                  skipped++;
                }

                continue;
              }

              added++;
              tweets.add(tweet);

              if (limit > 0 && added >= limit) {
                break;
              }

            } else {
              ignored++;
            }

          } catch (JSONException e) {
            this.log.write(
                "Exception in StatusFileReader: Json Parse Failure on: "
                    + status
                    + ", "
                    + e.getMessage());
          }
        } else {
          ignored++;
        }
      }

      br.close();
      decoder.close();
      inputStream.close();

    } catch (Exception e) {
      this.log.write(
          "Exception in StatusFileReader: Error Reading File: "
              + e.getClass().getName()
              + ": "
              + e.getMessage());
    }

    long runTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime);

    double ops = ((double) added / (double) Math.max(runTimeSeconds, 1));

    this.log.write(
        "StatusFileReader - "
            + fileLocation
            + " processed in "
            + runTimeSeconds
            + "s. "
            + added
            + " ok / "
            + errors
            + " errors / "
            + ignored
            + " ignored / "
            + skipped
            + " skipped. "
            + ops
            + " ops. Limit: "
            + limit
            + ", Fetch: "
            + tweets.size());

    return tweets;
  }