Java Code Examples for org.json.JSONArray#getLong()

The following examples show how to use org.json.JSONArray#getLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JSONOpUtils.java    From Alibaba-Android-Certification with MIT License 6 votes vote down vote up
/**
 * 从JSONArray中获取String对象
 * @param jarr 源JSONArray
 * @param index 对象索引
 * @return 异常返回null
 */
public static <T> Object getObject(JSONArray jarr,int index,Class<T> clazz){
	if(jarr==null) return null;
	try{
		if(TypeValidation.isInteger(clazz)||TypeValidation.isNumber(clazz)){
			return jarr.getInt(index);
		}else if(TypeValidation.isString(clazz)){
			return jarr.getString(index);
		}else if(TypeValidation.isBoolean(clazz)){
			return jarr.getBoolean(index);
		}else if(TypeValidation.isLong(clazz)){
			return jarr.getLong(index);
		}else if(TypeValidation.isDouble(clazz)){
			return jarr.getDouble(index);
		}
		return jarr.get(index);
	}catch(Exception ex){
		LogCat.e("JSONOpUtils","getObject",ex);
		return null;
	}
}
 
Example 2
Source File: JsonUtils.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the long value from the Json Array for specified index
 * 
 * @param jsonArray The {@link JSONArray} to read the index from
 * @param index The key to read
 * @param required Whether the index is required. If <code>true</code>,
 *            attempting to read it when it is <code>null</code> will throw
 *            a {@link JSONException}
 * @param notNull Whether the value is allowed to be <code>null</code>. If
 *            <code>true</code>, will throw a {@link JSONException} if the
 *            value is null
 * @return The read value
 * @throws JSONException If the long was unable to be read, or if the
 *             required/notNull flags were violated
 */
public static long readLong(final JSONArray jsonArray, final int index,
                final boolean required, final boolean notNull)
                throws JSONException {

    if (required) {
        //Will throw JsonException if mapping doesn't exist
        return jsonArray.getLong(index);
    }

    if (notNull && jsonArray.isNull(index)) {
        //throw JsonException because key is null
        throw new JSONException(String.format(Locale.US, NULL_VALUE_FORMAT_ARRAY, index));
    }
    long value = 0l;
    if (!jsonArray.isNull(index)) {
        value = jsonArray.getLong(index);
    }
    return value;
}
 
Example 3
Source File: ExecutedTradeHandler.java    From bitfinex-v2-wss-api-java with Apache License 2.0 6 votes vote down vote up
private BitfinexExecutedTrade jsonToExecutedTrade(final JSONArray jsonArray) {
    final BitfinexExecutedTrade executedTrade = new BitfinexExecutedTrade();

    final long id = jsonArray.getNumber(0).longValue();
    executedTrade.setTradeId(id);

    final long timestamp = jsonArray.getNumber(1).longValue();
    executedTrade.setTimestamp(timestamp);

    final BigDecimal amount = jsonArray.getBigDecimal(2);
    executedTrade.setAmount(amount);

    // Funding or Currency
    if (jsonArray.optNumber(4) != null) {
        final BigDecimal rate = jsonArray.getBigDecimal(3);
        executedTrade.setRate(rate);

        final Long period = jsonArray.getLong(4);
        executedTrade.setPeriod(period);
    } else {
        final BigDecimal price = jsonArray.getBigDecimal(3);
        executedTrade.setPrice(price);
    }
    return executedTrade;
}
 
Example 4
Source File: JsonUtils.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static List<Long> readLongListFromJsonObject(JSONObject json, String key){
	JSONArray jsonArray = readJsonArrayFromJsonObject(json, key);
	
	if(jsonArray != null){
		int len = jsonArray.length();
		List<Long> result = new ArrayList<Long>(len);
		for(int i=0; i<len; i++){
			try {
				Long str = jsonArray.getLong(i);
				result.add(str);
			} catch (JSONException e) {}
		}
		return result;
	}
	
	return null;
}
 
Example 5
Source File: Reaction.java    From act with GNU General Public License v3.0 6 votes vote down vote up
private boolean metacycProteinDataHasSeq(JSONObject prt) {
  // Example of a protein field entry for a METACYC rxn:
  // *****************************************************
  // {
  //   "datasource" : "METACYC",
  //   "organisms" : [
  //     NumberLong(198094)
  //   ],
  //   "sequences" : [
  //     NumberLong(8033)
  //   ]
  // }
  // *****************************************************

  if (!prt.has("sequences"))
    return false;

  JSONArray seqs = prt.getJSONArray("sequences");
  for (int i = 0; i < seqs.length(); i++) {
    Long s = seqs.getLong(i);
    if (s != null)
      return true;
  }

  return false;
}
 
Example 6
Source File: JSONHelper.java    From libcommon with Apache License 2.0 6 votes vote down vote up
public static long optLong(final JSONArray payload, final int index, final long defaultValue) {
	long result = defaultValue;
	if (payload.length() > index) {
		try {
			result = payload.getLong(index);
		} catch (final JSONException e) {
			try {
				result = Long.parseLong(payload.getString(index));
			} catch (final Exception e1) {
				try {
					result = payload.getBoolean(index) ? 1 :0;
				} catch (final Exception e2) {
					Log.w(TAG, e2);
				}
			}
		}
	}
	return result;
}
 
Example 7
Source File: PythonUtils.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public static long[] jsonArrayToLongArray(JSONArray jsonArray) {
    long[] longs = new long[jsonArray.length()];
    for (int i = 0; i < longs.length; i++) {

        longs[i] = jsonArray.getLong(i);
    }
    return longs;
}
 
Example 8
Source File: ParseTypes.java    From cordova-plugin-app-launcher with MIT License 5 votes vote down vote up
public static long[] toLongArray(JSONArray arr) throws JSONException {
	int jsize = arr.length();
	long[] exVal = new long[jsize];
	for(int j=0; j < jsize; j++) {
		exVal[j] = arr.getLong(j);
	}
	return exVal;
}
 
Example 9
Source File: Vibration.java    From showCaseCordova with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArray of arguments for the plugin.
 * @param callbackContext   The callback context used when calling back into JavaScript.
 * @return                  True when the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("vibrate")) {
        this.vibrate(args.getLong(0));
    }
    else if (action.equals("vibrateWithPattern")) {
        JSONArray pattern = args.getJSONArray(0);
        int repeat = args.getInt(1);
        //add a 0 at the beginning of pattern to align with w3c
        long[] patternArray = new long[pattern.length()+1];
        patternArray[0] = 0;
        for (int i = 0; i < pattern.length(); i++) {
            patternArray[i+1] = pattern.getLong(i);
        }
        this.vibrateWithPattern(patternArray, repeat);
    }
    else if (action.equals("cancelVibration")) {
        this.cancelVibration();
    }
    else {
        return false;
    }

    // Only alert and confirm are async.
    callbackContext.success();

    return true;
}
 
Example 10
Source File: Vibration.java    From reacteu-app with MIT License 5 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArray of arguments for the plugin.
 * @param callbackContext   The callback context used when calling back into JavaScript.
 * @return                  True when the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("vibrate")) {
        this.vibrate(args.getLong(0));
    }
    else if (action.equals("vibrateWithPattern")) {
        JSONArray pattern = args.getJSONArray(0);
        int repeat = args.getInt(1);
        //add a 0 at the beginning of pattern to align with w3c
        long[] patternArray = new long[pattern.length()+1];
        patternArray[0] = 0;
        for (int i = 0; i < pattern.length(); i++) {
            patternArray[i+1] = pattern.getLong(i);
        }
        this.vibrateWithPattern(patternArray, repeat);
    }
    else if (action.equals("cancelVibration")) {
        this.cancelVibration();
    }
    else {
        return false;
    }

    // Only alert and confirm are async.
    callbackContext.success();

    return true;
}
 
Example 11
Source File: Vibration.java    From jpHolo with MIT License 5 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArray of arguments for the plugin.
 * @param callbackContext   The callback context used when calling back into JavaScript.
 * @return                  True when the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("vibrate")) {
        this.vibrate(args.getLong(0));
    }
    else if (action.equals("vibrateWithPattern")) {
        JSONArray pattern = args.getJSONArray(0);
        int repeat = args.getInt(1);
        //add a 0 at the beginning of pattern to align with w3c
        long[] patternArray = new long[pattern.length()+1];
        patternArray[0] = 0;
        for (int i = 0; i < pattern.length(); i++) {
            patternArray[i+1] = pattern.getLong(i);
        }
        this.vibrateWithPattern(patternArray, repeat);
    }
    else if (action.equals("cancelVibration")) {
        this.cancelVibration();
    }
    else {
        return false;
    }

    // Only alert and confirm are async.
    callbackContext.success();

    return true;
}
 
Example 12
Source File: JSONBackupAgent.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@Override
public long[] getLongArray(String key) {
    try {
        JSONArray array = json.getJSONArray(key);
        long[] returnValue = new long[array.length()];

        for(int i = 0; i < array.length(); i++) {
            returnValue[i] = array.getLong(i);
        }

        return returnValue;
    } catch (JSONException e) {
        return null;
    }
}
 
Example 13
Source File: SequenceNumberAuditor.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
/**
 * Check the public and the private sequence
 * @param jsonArray
 */
private void checkPublicAndPrivateSequence(final JSONArray jsonArray) {
	final long nextPublicSequnceNumber = jsonArray.getLong(jsonArray.length() - 2);
	final long nextPrivateSequnceNumber = jsonArray.getLong(jsonArray.length() - 1);

	auditPublicSequence(nextPublicSequnceNumber);
	auditPrivateSequence(nextPrivateSequnceNumber);
}
 
Example 14
Source File: CandlestickHandler.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
private BitfinexCandle jsonToCandlestick(final JSONArray parts) {
    // 0 = Timestamp, 1 = Open, 2 = Close, 3 = High, 4 = Low,  5 = Volume
    final long timestamp = parts.getLong(0);
    final BigDecimal open = parts.getBigDecimal(1);
    final BigDecimal close = parts.getBigDecimal(2);
    final BigDecimal high = parts.getBigDecimal(3);
    final BigDecimal low = parts.getBigDecimal(4);
    final BigDecimal volume = parts.getBigDecimal(5);

    return new BitfinexCandle(timestamp, open, close, high, low, Optional.of(volume));
}
 
Example 15
Source File: TupleOperationEx.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
PartitionKey getPartitionKey(boolean offline) {
    PartitionKey key = new PartitionKey();

    key.order = this.id;

    if (offline) {
        // open/close folder is expensive
        key.priority = this.priority + 10;
        return key;
    }

    key.priority = this.priority;

    if (ADD.equals(name) || DELETE.equals(name)) {
        key.id = "msg:" + message;
    } else if (FETCH.equals(name))
        try {
            JSONArray jargs = new JSONArray(args);
            long uid = jargs.getLong(0);
            key.id = "uid:" + uid;
        } catch (Throwable ex) {
            Log.e(ex);
        }
    else if (!MOVE.equals(name))
        key.id = "id:" + id;

    key.operation = this.name;

    return key;
}
 
Example 16
Source File: Core.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static void onAttachment(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, EntityOperation op, IMAPFolder ifolder) throws JSONException, MessagingException, IOException {
    // Download attachment
    DB db = DB.getInstance(context);

    long id = jargs.getLong(0);

    // Get attachment
    EntityAttachment attachment = db.attachment().getAttachment(id);
    if (attachment == null)
        attachment = db.attachment().getAttachment(message.id, (int) id); // legacy
    if (attachment == null)
        throw new IllegalArgumentException("Local attachment not found");
    if (attachment.available)
        return;

    // Get message
    Message imessage = ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    // Get message parts
    MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
    MessageHelper.MessageParts parts = helper.getMessageParts();

    // Download attachment
    parts.downloadAttachment(context, attachment);
}
 
Example 17
Source File: Core.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static void onRaw(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, IOException, JSONException {
    // Download raw message
    DB db = DB.getInstance(context);

    if (message.raw == null || !message.raw) {
        IMAPMessage imessage = (IMAPMessage) ifolder.getMessageByUID(message.uid);
        if (imessage == null)
            throw new MessageRemovedException();

        File file = message.getRawFile(context);
        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
            imessage.writeTo(os);
        }

        db.message().setMessageRaw(message.id, true);
    }

    if (jargs.length() > 0) {
        // Cross account move
        long tid = jargs.getLong(0);
        EntityFolder target = db.folder().getFolder(tid);
        if (target == null)
            throw new FolderNotFoundException();

        Log.i(folder.name + " queuing ADD id=" + message.id + ":" + target.id);

        EntityOperation operation = new EntityOperation();
        operation.account = target.account;
        operation.folder = target.id;
        operation.message = message.id;
        operation.name = EntityOperation.ADD;
        operation.args = jargs.toString();
        operation.created = new Date().getTime();
        operation.id = db.operation().insertOperation(operation);
    }
}
 
Example 18
Source File: Loader.java    From act with GNU General Public License v3.0 4 votes vote down vote up
private List<Precursor> getUpstreamPrecursors(Long parentId, JSONArray upstreamReactions) {
  Map<Long, InchiDescriptor> substrateCache = new HashMap<>();
  Map<List<InchiDescriptor>, Precursor> substratesToPrecursor = new HashMap<>();
  List<Precursor> precursors = new ArrayList<>();

  for (int i = 0; i < upstreamReactions.length(); i++) {
    JSONObject obj = upstreamReactions.getJSONObject(i);
    if (!obj.getBoolean("reachable")) {
      continue;
    }

    List<InchiDescriptor> thisRxnSubstrates = new ArrayList<>();

    JSONArray substratesArrays = (JSONArray) obj.get("substrates");
    for (int j = 0; j < substratesArrays.length(); j++) {
      Long subId = substratesArrays.getLong(j);
      InchiDescriptor parentDescriptor;
      if (subId >= 0 && !substrateCache.containsKey(subId)) {
        try {
          Chemical parent = sourceDBconn.getChemicalFromChemicalUUID(subId);
          upsert(constructOrFindReachable(parent.getInChI()));
          parentDescriptor = new InchiDescriptor(constructOrFindReachable(parent.getInChI()));
          thisRxnSubstrates.add(parentDescriptor);
          substrateCache.put(subId, parentDescriptor);
          // TODO Remove null pointer exception check
        } catch (NullPointerException e) {
          LOGGER.info("Null pointer, unable to write parent.");
        }
      } else if (substrateCache.containsKey(subId)) {
        thisRxnSubstrates.add(substrateCache.get(subId));
      }
    }

    if (!thisRxnSubstrates.isEmpty()) {
      // This is a previously unseen reaction, so add it to the list of precursors.
      List<SequenceData> rxnSequences =
              extractOrganismsAndSequencesForReactions(Collections.singleton(obj.getLong("rxnid")));
      List<String> sequenceIds = new ArrayList<>();
      for (SequenceData seq : rxnSequences) {
        WriteResult<SequenceData, String> result = jacksonSequenceCollection.insert(seq);
        sequenceIds.add(result.getSavedId());
      }

      // TODO: make sure this is what we actually want to do, and figure out why it's happening.
      // De-duplicate reactions based on substrates; somehow some duplicate cascade paths are appearing.
      if (substratesToPrecursor.containsKey(thisRxnSubstrates)) {
        substratesToPrecursor.get(thisRxnSubstrates).addSequences(sequenceIds);
      } else {
        Precursor precursor = new Precursor(thisRxnSubstrates, "reachables", sequenceIds);
        precursors.add(precursor);
        // Map substrates to precursor for merging later.
        substratesToPrecursor.put(thisRxnSubstrates, precursor);
      }
    }
  }

  if (parentId >= 0 && !substrateCache.containsKey(parentId)) {
    // Note: this should be impossible.
    LOGGER.error("substrate cache does not contain parent id %d after all upstream reactions processed", parentId);
  }

  return precursors;
}
 
Example 19
Source File: SequenceNumberAuditor.java    From bitfinex-v2-wss-api-java with Apache License 2.0 4 votes vote down vote up
/** 
 * Check the public sequence
 */
private void checkPublicSequence(final JSONArray jsonArray) {
	final long nextPublicSequnceNumber = jsonArray.getLong(jsonArray.length() - 1);
	
	auditPublicSequence(nextPublicSequnceNumber);
}
 
Example 20
Source File: UseByDayDataLoader.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    int kWhFeedId = myElectricDataManager.getSettings().getUseFeedId();

    long end = (long) Math.floor(((Calendar.getInstance().getTimeInMillis() * 0.001) + timeZoneOffset) / INTERVAL) * INTERVAL;

    end -= timeZoneOffset;
    long start = end - (INTERVAL * daysToDisplay);

    final long chart2EndTime = end * 1000;
    final long chart2StartTime = start * 1000;

    String url = String.format(FEED_URL, myElectricDataManager.getEmonCmsUrl(), myElectricDataManager.getEmoncmsApikey(), kWhFeedId, chart2StartTime, chart2EndTime);
    Log.i("EMONCMS:URL", "mDaysofWeekRunner:" + url);

    JsonArrayRequest jsArrayRequest = new JsonArrayRequest
            (url, new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {
                    List<Long> dates = new ArrayList<>();
                    List<Double> power = new ArrayList<>();
                    String dayOfWeekInitials[] = context.getResources().getStringArray(R.array.day_of_week_initials);
                    Calendar calendar = Calendar.getInstance();

                    for (int i = 0; i < response.length(); i++) {
                        JSONArray row;

                        try {
                            row = response.getJSONArray(i);
                            Long date = row.getLong(0);
                            if (date <= chart2EndTime) {
                                dates.add(date);
                                power.add(row.getDouble(1) *  myElectricDataManager.getSettings().getPowerScaleAsFloat());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    dailyUsageBarChart.clearData();

                    int[] chart2_colors = new int[power.size()];

                    for (int i = 0; i < power.size() - 1; i++) {
                        calendar.setTimeInMillis(dates.get(i));

                        dailyUsageBarChart.addData(dayOfWeekInitials[calendar.get(Calendar.DAY_OF_WEEK) - 1],power.get(i + 1) - power.get(i));

                        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
                                calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
                            chart2_colors[i] = ContextCompat.getColor(context, R.color.chartBlueDark);
                        else
                            chart2_colors[i] = ContextCompat.getColor(context, R.color.chartBlue);
                    }

                    if (power.size() > 0) {
                        double yesterdaysPowerUsage = power.get(power.size() - 1);
                        double powerToday = (myElectricDataManager.getTotalUsagekWh()) - yesterdaysPowerUsage;
                        myElectricDataManager.setUseToYesterday((float)yesterdaysPowerUsage);


                        calendar.setTimeInMillis(dates.get(dates.size() - 1));

                        dailyUsageBarChart.addData(dayOfWeekInitials[calendar.get(Calendar.DAY_OF_WEEK) - 1],powerToday);


                        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
                                calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                            chart2_colors[chart2_colors.length - 1] = ContextCompat.getColor(context, R.color.chartBlueDark);
                        } else {
                            chart2_colors[chart2_colors.length - 1] = ContextCompat.getColor(context, R.color.chartBlue);
                        }
                    }

                    dailyUsageBarChart.setBarColours(chart2_colors);
                    dailyUsageBarChart.refreshChart();

                   myElectricDataManager.clearMessage();
                   myElectricDataManager.loadPowerHistory(0);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    myElectricDataManager.showMessage(R.string.connection_error);
                    myElectricDataManager.loadUseHistory(5000);

                }
            });

    jsArrayRequest.setTag(myElectricDataManager.getPageTag());
    HTTPClient.getInstance(context).addToRequestQueue(jsArrayRequest);
}