コード例 #1
0
 /**
  * Transforms the purchase information into a JSON object.
  *
  * @return A JSONObject containing the purchase information.
  */
 public JSONObject toJSON() {
   JSONObject o = new JSONObject();
   try {
     o.putOpt("productId", productId);
     o.putOpt("transactionId", transactionId);
     o.put("purchaseDate", purchaseDate != null ? purchaseDate.getTime() : 0);
     o.put("quantity", quantity);
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return o;
 }
コード例 #2
0
  public void asyncJson() throws JSONException {
    JSONObject params1 = new JSONObject();
    params1.putOpt("startPlaceAuditID", GodObject.START_PLACE_AUDIT_ID);
    params1.putOpt("finishPlaceAuditID", GodObject.FINISH_PLACE_AUDIT_ID_CITY);
    params1.putOpt("userID", GodObject.USER_ID);
    params1.putOpt("currency", GOS.getCurrencyString());

    JSONObject params2 = new JSONObject();
    params2.putOpt("startPlaceAuditID", GodObject.START_PLACE_AUDIT_ID);
    params2.putOpt("finishPlaceAuditID", GodObject.FINISH_PLACE_AUDIT_ID_AERO);
    params2.putOpt("userID", GodObject.USER_ID);
    params2.putOpt("currency", GOS.getCurrencyString());

    AQUtility.setDebug(true);
    AjaxCallback<JSONObject> cb1 =
        new AjaxCallback<JSONObject>() {
          @Override
          public void callback(String url, JSONObject html, AjaxStatus status) {
            jsonCallback(url, html, status, "city");
          }
        };

    AjaxCallback<JSONObject> cb2 =
        new AjaxCallback<JSONObject>() {
          @Override
          public void callback(String url, JSONObject html, AjaxStatus status) {
            jsonCallback(url, html, status, "aero");
          }
        };

    if (GOS.isRub() && GOS.getPricesRub().size() < 4) makeRequest(params1, params2, cb1, cb2);
    if (GOS.isUsd() && GOS.getPricesUsd().size() < 4) makeRequest(params1, params2, cb1, cb2);
    if (GOS.isEur() && GOS.getPricesEur().size() < 4) makeRequest(params1, params2, cb1, cb2);
  }
コード例 #3
0
  // Returns either a JSONObject or JSONArray representation of the 'key' property of 'jsonObject'.
  public static Object getStringPropertyAsJSON(
      JSONObject jsonObject, String key, String nonJSONPropertyKey) throws JSONException {
    Object value = jsonObject.opt(key);
    if (value != null && value instanceof String) {
      JSONTokener tokener = new JSONTokener((String) value);
      value = tokener.nextValue();
    }

    if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) {
      if (nonJSONPropertyKey != null) {
        // Facebook sometimes gives us back a non-JSON value such as
        // literal "true" or "false" as a result.
        // If we got something like that, we present it to the caller as
        // a GraphObject with a single
        // property. We only do this if the caller wants that behavior.
        jsonObject = new JSONObject();
        jsonObject.putOpt(nonJSONPropertyKey, value);
        return jsonObject;
      } else {
        throw new FacebookException("Got an unexpected non-JSON object.");
      }
    }

    return value;
  }
コード例 #4
0
ファイル: CursorCoercer5.java プロジェクト: prakash122/Kirin
  /* (non-Javadoc)
   * @see com.futureplatforms.android.jscore.fragmentation.CursorCoercer#coerceToJSONObject(java.lang.String[], android.database.AbstractWindowedCursor)
   */
  @Override
  public JSONObject coerceToJSONObject(String[] cols, AbstractWindowedCursor c) {
    JSONObject obj = new JSONObject();
    for (int i = 0; i < cols.length; i++) {
      String name = cols[i];
      // do we have to worry about types?
      // if we do, then we need the CursorWindow.

      // TODO we can make this faster for SDK > 5.
      // TODO have a separate class depending on SDK.
      try {
        if (c.isString(i)) {
          obj.putOpt(name, c.getString(i));
        } else if (c.isLong(i)) {
          obj.put(name, c.getLong(i));
        } else if (c.isFloat(i)) {
          obj.put(name, c.getDouble(i));
        } else if (c.isNull(i)) {
          obj.remove(name);
        }
      } catch (JSONException e) {
        Log.e(C.TAG, e.getLocalizedMessage(), e);
      }
    }
    return obj;
  }
コード例 #5
0
  protected void buildDrillJSON() throws Exception {

    SourceBean confSB = null;
    String documentName = null;

    logger.debug("IN");
    confSB = (SourceBean) template.getAttribute(MobileConstants.DRILL_TAG);
    if (confSB == null) {
      logger.debug("Cannot find title drill settings: tag name " + MobileConstants.DRILL_TAG);
      return;
    }
    documentName = (String) confSB.getAttribute(MobileConstants.DRILL_DOCUMENT_ATTR);
    List paramslist =
        (List)
            template.getAttributeAsList(
                MobileConstants.DRILL_TAG + "." + MobileConstants.PARAM_TAG);

    if (paramslist != null) {
      JSONArray params = new JSONArray();
      for (int k = 0; k < paramslist.size(); k++) {
        SourceBean param = (SourceBean) paramslist.get(k);
        String paramName = (String) param.getAttribute(MobileConstants.PARAM_NAME_ATTR);
        String paramType = (String) param.getAttribute(MobileConstants.PARAM_TYPE_ATTR);
        String paramValue = (String) param.getAttribute(MobileConstants.PARAM_VALUE_ATTR);
        JSONObject paramJSON = new JSONObject();
        paramJSON.put("paramName", paramName);
        paramJSON.put("paramType", paramType);

        // FILLS RELATIVE TYPE PARAMETERS' VALUE FROM REQUEST
        if (paramType.equalsIgnoreCase(MobileConstants.PARAM_TYPE_RELATIVE)) {
          paramJSON.putOpt("paramValue", paramsMap.get(paramName));
        } else {
          paramJSON.putOpt("paramValue", paramValue); // should be applied only on absolute type
        }
        params.put(paramJSON);
      }
      drill.put("params", params);
    }

    drill.put("document", documentName);

    logger.debug("OUT");
  }
コード例 #6
0
 @Override
 public boolean exportValue(JSONObject json, String key, SharedPreferences preferences) {
   if (!preferences.contains(key)) return false;
   try {
     json.putOpt(key, preferences.getString(key, null));
   } catch (Exception ignore) {
     return false;
   }
   return true;
 }
コード例 #7
0
  private void getColumnsInfos(Column column) {
    try {
      Integer size = column.getSize();
      String sizeColumn = column.getField();
      boolean unsigned = column.isUnsigned();
      JSONObject infoObj = new JSONObject();

      infoObj.putOpt("sizeColumn", sizeColumn);
      infoObj.putOpt("size", size);

      infoObj.putOpt("unsigned", unsigned);
      if (size != null || unsigned != false) {
        columnsInfos.put(infoObj);
      }

    } catch (JSONException e) {
      logger.error("Error getting size column informations from template " + e.getMessage());
    }
  }
    @Override
    protected String doInBackground(String... params) {
      JSONObject jObject = new JSONObject();
      try {
        JSONObject jsonObj = GenericUtils.GetDefaultJSONObj();
        jsonObj.putOpt("account_id", params[0]);
        jObject.putOpt("data", jsonObj);
      } catch (JSONException e) {
        e.printStackTrace();
        LogManager.Error("GetTransactionsTask", e);
        return null;
      } catch (Exception e) {
        e.printStackTrace();
        LogManager.Error("GetTransactionsTask", e);
        return null;
      }

      LogManager.Info(">>>> " + jObject.toString());
      return GenericUtils.HTTPRequest("GetTransactions", jObject.toString());
    }
コード例 #9
0
 /**
  * Construct a JSONObject from an Object, using reflection to find the public members. The
  * resulting JSONObject's keys will be the strings from the names array, and the values will be
  * the field values associated with those keys in the object. If a key is not found or not
  * visible, then it will not be copied into the new JSONObject.
  *
  * @param object An object that has fields that should be used to make a JSONObject.
  * @param names An array of strings, the names of the fields to be obtained from the object.
  */
 public JSONObject(Object object, String names[]) {
   this();
   Class<?> c = object.getClass();
   for (int i = 0; i < names.length; i += 1) {
     String name = names[i];
     try {
       putOpt(name, c.getField(name).get(object));
     } catch (Exception ignore) {
     }
   }
 }
コード例 #10
0
ファイル: Trigger.java プロジェクト: pieterjm/JCosmAPI
  public JSONObject toJSONObject() throws JSONException {
    JSONObject jo = new JSONObject();

    jo.putOpt("threshold_value", this.thresholdValue);
    jo.putOpt("url", this.url);
    if (type != null) {
      jo.putOpt("trigger_type", type.toString());
    }
    jo.putOpt("environment_id", environment_id);
    jo.putOpt("stream_id", stream_id);
    jo.putOpt("user", user);
    jo.putOpt("notified_at", notifiedAt);
    jo.putOpt("id", id);

    return jo;
  }
コード例 #11
0
  @Override
  public void onRecvTrackData(Hashtable<String, String> trackData) {
    JSONObject msg = new JSONObject();
    try {
      Enumeration<String> keys = trackData.keys();
      while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        msg.putOpt(key, trackData.get(key));
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    onCall(func_swipeCard, msg);
  }
コード例 #12
0
ファイル: CKEditorPanel.java プロジェクト: srajeev/hippo
  private JSONObject getConfigurationForEditor() {
    try {
      JSONObject editorConfig = JsonUtils.createJSONObject(editorConfigJson);

      // configure extensions
      for (CKEditorPanelExtension extension : extensions) {
        extension.addConfiguration(editorConfig);
      }

      // always use the language of the current CMS locale
      final Locale locale = getLocale();
      editorConfig.put(CKEditorConstants.CONFIG_LANGUAGE, locale.getLanguage());

      // convert Hippo-specific 'declarative' keystrokes to numeric ones
      final JSONArray declarativeAndNumericKeystrokes =
          editorConfig.optJSONArray(CKEditorConstants.CONFIG_KEYSTROKES);
      final JSONArray numericKeystrokes =
          DeclarativeKeystrokesConverter.convertToNumericKeystrokes(
              declarativeAndNumericKeystrokes);
      editorConfig.putOpt(CKEditorConstants.CONFIG_KEYSTROKES, numericKeystrokes);

      // load the localized hippo styles if no other styles are specified
      JsonUtils.putIfAbsent(
          editorConfig, CKEditorConstants.CONFIG_STYLES_SET, HippoStyles.getConfigStyleSet(locale));

      // disable custom config loading if not configured
      JsonUtils.putIfAbsent(
          editorConfig, CKEditorConstants.CONFIG_CUSTOM_CONFIG, StringUtils.EMPTY);

      if (log.isInfoEnabled()) {
        log.info(
            "CKEditor configuration:\n"
                + editorConfig.toString(LOGGED_EDITOR_CONFIG_INDENT_SPACES));
      }

      return editorConfig;
    } catch (JSONException e) {
      throw new IllegalStateException("Error creating CKEditor configuration.", e);
    }
  }
コード例 #13
0
 /**
  * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to
  * identify the keys that should be copied. Missing keys are ignored.
  *
  * @param jo A JSONObject.
  * @param names An array of strings.
  * @exception JSONException If a value is a non-finite number.
  */
 public JSONObject(JSONObject jo, String[] names) throws JSONException {
   this();
   for (int i = 0; i < names.length; i += 1) {
     putOpt(names[i], jo.opt(names[i]));
   }
 }
コード例 #14
0
  public String toJSONString() {
    JSONObject tvShowObject = new JSONObject();

    try {
      tvShowObject.putOpt(C.jsonKeys.IN_APP_ID, inAppId);
      tvShowObject.putOpt(C.jsonKeys.SHOW_NAME, showName);
      tvShowObject.putOpt(C.jsonKeys.START_TIME, startTime);
      tvShowObject.putOpt(C.jsonKeys.END_TIME, endTime);
      tvShowObject.putOpt(C.jsonKeys.SEASON_INFO, seasonInformation);
      tvShowObject.putOpt(C.jsonKeys.EPISODE_INFO, episodeInformation);
      tvShowObject.putOpt(C.jsonKeys.IMAGE_URL, imageUrl);
      tvShowObject.putOpt(C.jsonKeys.DESCRIPTION, description);
      tvShowObject.putOpt(C.jsonKeys.CHANNEL, channel);
      tvShowObject.putOpt(C.jsonKeys.SHOW_ID, showId);

      JSONArray contestantsArray = new JSONArray();

      Log.v(tag, " at 1");
      if (contestants != null && contestants.size() > 0) {
        Log.v(tag, " at 2");
        for (Contestant c : contestants) {
          Log.v(tag, " at 3 ");
          if (c != null) {
            Log.v(tag, " at 4 " + c.name);
            Log.v(tag, "c " + c.toJSONString());
            contestantsArray.put(new JSONObject(c.toJSONString()));
          }
        }
      }

      tvShowObject.putOpt(C.jsonKeys.CONTESTANTS, contestantsArray);
    } catch (JSONException e) {
      e.printStackTrace();
    }

    Log.v(tag, "returning " + tvShowObject.toString());

    return tvShowObject.toString();
  }
コード例 #15
0
  @Override
  public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    CONTEXT = this.getApplicationContext();
    AM = this.getAssets();

    try {
      PLACEHOLDERBMP = BitmapFactory.decodeStream(AM.open("transparent.png"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    WPM = WallpaperManager.getInstance(this);
    PREFS = PreferenceManager.getDefaultSharedPreferences(OMWPP.CONTEXT);

    BMPQUERYOPTIONS = new BitmapFactory.Options();
    BMPQUERYOPTIONS.inJustDecodeBounds = true;

    BMPVALIDOPTIONS = new BitmapFactory.Options();
    BMPVALIDOPTIONS.inSampleSize = 4;

    BMPAPPLYOPTIONS = new BitmapFactory.Options();
    BMPAPPLYOPTIONS.inSampleSize = 1;
    BMPAPPLYOPTIONS.inScaled = false;
    BMPAPPLYOPTIONS.inDither = false;
    BMPAPPLYOPTIONS.inPreferredConfig = Config.ARGB_8888;

    // Initialize the four queues.
    THUMBNAILQUEUE = new ConcurrentLinkedQueue<File>();
    DOWNLOADQUEUE = new ArrayBlockingQueue<URL>(20, false);
    UNZIPQUEUE = new ArrayBlockingQueue<File>(20, false);

    SCREENWIDTH = getResources().getDisplayMetrics().widthPixels;
    SCREENHEIGHT = getResources().getDisplayMetrics().heightPixels;

    WPWIDTH = WPM.getDesiredMinimumWidth();
    WPHEIGHT = WPM.getDesiredMinimumHeight();
    if (WPWIDTH < SCREENWIDTH * 2) WPWIDTH = SCREENWIDTH * 2;
    if (WPHEIGHT < SCREENHEIGHT) WPHEIGHT = SCREENHEIGHT;
    if (OMWPP.DEBUG) Log.i("OMWPPApp", "Target Width is" + WPWIDTH);
    if (OMWPP.DEBUG) Log.i("OMWPPApp", "Target Height is " + WPHEIGHT);

    try {
      ENDMARKER_URL = new URL("http://localhost");
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (isSDPresent()) {
      // Check and/or create the wallpapers directory.
      SDROOT = new File(Environment.getExternalStorageDirectory().getPath() + "/ubuntuwps/");
      if (OMWPP.DEBUG) Log.i("OMWPPApp", "Checking/Creating " + SDROOT.getAbsoluteFile());
      SDROOT.mkdirs();
      THUMBNAILROOT = getExternalFilesDir(null);
      if (OMWPP.DEBUG) Log.i("OMWPPApp", "Checking/Creating " + THUMBNAILROOT.getAbsoluteFile());
      THUMBNAILROOT.mkdirs();
      File nomedia = new File(THUMBNAILROOT.getAbsolutePath() + "/.nomedia");
      try {
        if (!nomedia.exists()) nomedia.createNewFile();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    // First of all, let's load up the latest configuration JSON file.
    try {
      if (isSDPresent()) {
        if (OMWPP.DEBUG) Log.i("OMWPPApp", "Loading config file from TN folder");
        CONFIGJSON =
            streamToJSONObject(
                new FileInputStream(new File(THUMBNAILROOT.getPath() + "/omwpp_config.json")));
      } else {
        if (OMWPP.DEBUG) Log.i("OMWPPApp", "No config file in TN folder");
        throw new Exception();
      }
    } catch (Exception e) {
      try {
        if (OMWPP.DEBUG) Log.i("OMWPPApp", "Copying default files to Wallpaper folder");
        copyAssetToFile("omwpp_config.json", THUMBNAILROOT.getPath() + "/omwpp_config.json");
        CONFIGJSON =
            streamToJSONObject(
                new FileInputStream(new File(THUMBNAILROOT.getPath() + "/omwpp_config.json")));
        CONFIGJSON.putOpt("localpaths", new JSONArray("[\"" + SDROOT.toString() + "\"]"));
        commitJSONChanges();

        try {
          for (String sFile : OMWPP.AM.list("")) {
            copyAssetToFile(sFile, SDROOT.getPath() + "/" + sFile);
          }
        } catch (Exception ee) {
          ee.printStackTrace();
        }
      } catch (Exception ee) {
        e.printStackTrace();
      }
    }

    // Figure out when we last downloaded a new config file.
    LASTCONFIGREFRESH = OMWPP.PREFS.getLong("LASTCONFIGREFRESH", 0l);
  }
  private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor)
      throws JSONException {
    Object value = bundle.get(key);
    if (value == null) {
      // Cannot serialize null values.
      return;
    }

    String supportedType = null;
    JSONArray jsonArray = null;
    JSONObject json = new JSONObject();

    if (value instanceof Byte) {
      supportedType = TYPE_BYTE;
      json.put(JSON_VALUE, ((Byte) value).intValue());
    } else if (value instanceof Short) {
      supportedType = TYPE_SHORT;
      json.put(JSON_VALUE, ((Short) value).intValue());
    } else if (value instanceof Integer) {
      supportedType = TYPE_INTEGER;
      json.put(JSON_VALUE, ((Integer) value).intValue());
    } else if (value instanceof Long) {
      supportedType = TYPE_LONG;
      json.put(JSON_VALUE, ((Long) value).longValue());
    } else if (value instanceof Float) {
      supportedType = TYPE_FLOAT;
      json.put(JSON_VALUE, ((Float) value).doubleValue());
    } else if (value instanceof Double) {
      supportedType = TYPE_DOUBLE;
      json.put(JSON_VALUE, ((Double) value).doubleValue());
    } else if (value instanceof Boolean) {
      supportedType = TYPE_BOOLEAN;
      json.put(JSON_VALUE, ((Boolean) value).booleanValue());
    } else if (value instanceof Character) {
      supportedType = TYPE_CHAR;
      json.put(JSON_VALUE, value.toString());
    } else if (value instanceof String) {
      supportedType = TYPE_STRING;
      json.put(JSON_VALUE, (String) value);
    } else if (value instanceof Enum<?>) {
      supportedType = TYPE_ENUM;
      json.put(JSON_VALUE, value.toString());
      json.put(JSON_VALUE_ENUM_TYPE, value.getClass().getName());
    } else {
      // Optimistically create a JSONArray. If not an array type, we can null
      // it out later
      jsonArray = new JSONArray();
      if (value instanceof byte[]) {
        supportedType = TYPE_BYTE_ARRAY;
        for (byte v : (byte[]) value) {
          jsonArray.put((int) v);
        }
      } else if (value instanceof short[]) {
        supportedType = TYPE_SHORT_ARRAY;
        for (short v : (short[]) value) {
          jsonArray.put((int) v);
        }
      } else if (value instanceof int[]) {
        supportedType = TYPE_INTEGER_ARRAY;
        for (int v : (int[]) value) {
          jsonArray.put(v);
        }
      } else if (value instanceof long[]) {
        supportedType = TYPE_LONG_ARRAY;
        for (long v : (long[]) value) {
          jsonArray.put(v);
        }
      } else if (value instanceof float[]) {
        supportedType = TYPE_FLOAT_ARRAY;
        for (float v : (float[]) value) {
          jsonArray.put((double) v);
        }
      } else if (value instanceof double[]) {
        supportedType = TYPE_DOUBLE_ARRAY;
        for (double v : (double[]) value) {
          jsonArray.put(v);
        }
      } else if (value instanceof boolean[]) {
        supportedType = TYPE_BOOLEAN_ARRAY;
        for (boolean v : (boolean[]) value) {
          jsonArray.put(v);
        }
      } else if (value instanceof char[]) {
        supportedType = TYPE_CHAR_ARRAY;
        for (char v : (char[]) value) {
          jsonArray.put(String.valueOf(v));
        }
      } else if (value instanceof List<?>) {
        supportedType = TYPE_STRING_LIST;
        @SuppressWarnings("unchecked")
        List<String> stringList = (List<String>) value;
        for (String v : stringList) {
          jsonArray.put((v == null) ? JSONObject.NULL : v);
        }
      } else {
        // Unsupported type. Clear out the array as a precaution even though
        // it is redundant with the null supportedType.
        jsonArray = null;
      }
    }

    if (supportedType != null) {
      json.put(JSON_VALUE_TYPE, supportedType);
      if (jsonArray != null) {
        // If we have an array, it has already been converted to JSON. So use
        // that instead.
        json.putOpt(JSON_VALUE, jsonArray);
      }

      String jsonString = json.toString();
      editor.putString(key, jsonString);
    }
  }
コード例 #17
0
  public void endDocument() {
    if (OMC.DEBUG) Log.i(OMC.OMCSHORT + "YrNoWeather", "End Document.");

    //
    // Build out the forecast array.
    Time day = new Time();
    day.setToNow();
    //		while (HIGHTEMPS.containsKey(day.format("%Y%m%d"))) {
    //			try {
    //				JSONObject jsonOneDayForecast = new JSONObject();
    //				jsonOneDayForecast.put("day_of_week", day.format("%a"));
    //				jsonOneDayForecast.put("condition", CONDITIONS.get(day.format("%Y%m%d")));
    //				jsonOneDayForecast.put("condition_lcase",
    // CONDITIONS.get(day.format("%Y%m%d")).toLowerCase());
    //				double lowc = OMC.roundToSignificantFigures(LOWTEMPS.get(day.format("%Y%m%d")),3);
    //				double highc = OMC.roundToSignificantFigures(HIGHTEMPS.get(day.format("%Y%m%d")),3);
    //				double lowf = (int)(lowc/5f*9f+32.5f);
    //				double highf = (int)(highc/5f*9f+32.5f);
    //				jsonOneDayForecast.put("low_c", lowc);
    //				jsonOneDayForecast.put("high_c", highc);
    //				jsonOneDayForecast.put("low", lowf);
    //				jsonOneDayForecast.put("high", highf);
    //				jsonWeather.getJSONArray("zzforecast_conditions").put(
    //						jsonOneDayForecast);
    //				day.hour+=24;
    //				day.normalize(false);
    //			} catch (JSONException e) {
    //				e.printStackTrace();
    //			}
    //		}
    if (OMC.DEBUG) Log.i(OMC.OMCSHORT + "YrNoWeather", jsonWeather.toString());

    // Check if the reply was valid.
    //		if (jsonWeather.optString("condition",null)==null ||
    // jsonWeather.optString("problem_cause",null)!=null) {
    //			//Google returned error - retry by city name, then abandon refresh
    //			if (jsonWeather.optBoolean("bylatlong")) {
    //				if (OMC.DEBUG) Log.i(OMC.OMCSHORT + "YrNoWeather", "Error using Lat/Long, retrying using
    // city name.");
    //				YrNoWeatherXMLHandler.updateWeather(0d, 0d, jsonWeather.optString("country2"),
    // jsonWeather.optString("city2"), false);
    //				return;
    //			} else {
    //				if (OMC.DEBUG) Log.i(OMC.OMCSHORT + "YrNoWeather", "Error using city name. No refresh.");
    //				return;
    //			}
    //		}

    try {
      if (jsonWeather.optString("city") == null || jsonWeather.optString("city").equals("")) {
        if (!jsonWeather.optString("city2").equals(""))
          jsonWeather.putOpt("city", jsonWeather.optString("city2"));
        else if (!jsonWeather.optString("country2").equals(""))
          jsonWeather.putOpt("city", jsonWeather.optString("country2"));
      }

      // Mark weather forecast source.
      jsonWeather.put("source", "owm");

    } catch (JSONException e) {
      e.printStackTrace();
      return;
    }
    OMC.PREFS.edit().putString("weather", jsonWeather.toString()).commit();
    OMC.LASTWEATHERREFRESH = System.currentTimeMillis();
    if (OMC.DEBUG)
      Log.i(
          OMC.OMCSHORT + "YrNoWeather",
          "Update Succeeded.  Phone Time:"
              + new java.sql.Time(OMC.LASTWEATHERREFRESH).toLocaleString());

    Time t = new Time();
    // If the weather station information (international, mostly) doesn't have a timestamp, set the
    // timestamp to be jan 1st, 1970
    t.parse(jsonWeather.optString("current_local_time", "19700101T000000"));

    // If the weather station info looks too stale (more than 2 hours old), it's because the phone's
    // date/time is wrong.
    // Force the update to the default update period
    if (System.currentTimeMillis() - t.toMillis(false) > 7200000l) {
      OMC.NEXTWEATHERREFRESH =
          Math.max(
              OMC.LASTWEATHERREFRESH
                  + Long.parseLong(OMC.PREFS.getString("sWeatherFreq", "60")) * 60000l,
              OMC.LASTWEATHERTRY
                  + Long.parseLong(OMC.PREFS.getString("sWeatherFreq", "60")) / 4l * 60000l);
      if (OMC.DEBUG)
        Log.i(
            OMC.OMCSHORT + "YrNoWeather",
            "Weather Station Time:" + new java.sql.Time(t.toMillis(false)).toLocaleString());
      if (OMC.DEBUG)
        Log.i(
            OMC.OMCSHORT + "YrNoWeather",
            "Weather Station Time Missing or Stale.  Using default interval.");
    } else if (t.toMillis(false) > System.currentTimeMillis()) {
      // If the weather station time is in the future, something is definitely wrong!
      // Force the update to the default update period
      if (OMC.DEBUG)
        Log.i(
            OMC.OMCSHORT + "YrNoWeather",
            "Weather Station Time:" + new java.sql.Time(t.toMillis(false)).toLocaleString());
      if (OMC.DEBUG)
        Log.i(
            OMC.OMCSHORT + "YrNoWeather",
            "Weather Station Time in the future -> phone time is wrong.  Using default interval.");
      OMC.NEXTWEATHERREFRESH =
          Math.max(
              OMC.LASTWEATHERREFRESH
                  + Long.parseLong(OMC.PREFS.getString("sWeatherFreq", "60")) * 60000l,
              OMC.LASTWEATHERTRY
                  + Long.parseLong(OMC.PREFS.getString("sWeatherFreq", "60")) / 4l * 60000l);
    } else {
      // If we get a recent weather station timestamp, we try to "catch" the update by setting next
      // update to
      // 29 minutes + default update period
      // after the last station refresh.

      if (OMC.DEBUG)
        Log.i(
            OMC.OMCSHORT + "YrNoWeather",
            "Weather Station Time:" + new java.sql.Time(t.toMillis(false)).toLocaleString());
      OMC.NEXTWEATHERREFRESH =
          Math.max(
              t.toMillis(false)
                  + (29l + Long.parseLong(OMC.PREFS.getString("sWeatherFreq", "60"))) * 60000l,
              OMC.LASTWEATHERTRY
                  + Long.parseLong(OMC.PREFS.getString("sWeatherFreq", "60")) / 4l * 60000l);
    }
    if (OMC.DEBUG)
      Log.i(
          OMC.OMCSHORT + "YrNoWeather",
          "Next Refresh Time:" + new java.sql.Time(OMC.NEXTWEATHERREFRESH).toLocaleString());
    OMC.PREFS.edit().putLong("weather_nextweatherrefresh", OMC.NEXTWEATHERREFRESH).commit();
  }
コード例 #18
0
ファイル: TeacherAnswers.java プロジェクト: Potentii/Yukon
 public void setWeightTypeAnswerStructArray(WeightTypeAnswerStruct[] weightTypeAnswerStructArray)
     throws JSONException {
   super.putOpt(
       TeacherAnswersJSONKeys.WEIGHT_TYPE_ANSWER_STRUCT_ARRAY.getKey(),
       new JSONArray(weightTypeAnswerStructArray));
 }