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

The following examples show how to use org.json.JSONArray#getInt() . 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: Cache.java    From unity-ads-android with Apache License 2.0 6 votes vote down vote up
@TargetApi(10)
private static SparseArray<String> getMetaData (final String videoFile, JSONArray requestedMetaDatas) throws JSONException, IOException, RuntimeException {
	File f = new File(videoFile);
	SparseArray<String> returnArray = new SparseArray<>();

	if (f.exists()) {
		MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
		metadataRetriever.setDataSource(f.getAbsolutePath());

		for (int i = 0; i < requestedMetaDatas.length(); i++) {
			int metaDataKey = requestedMetaDatas.getInt(i);
			String metaDataValue = metadataRetriever.extractMetadata(metaDataKey);

			if (metaDataValue != null) {
				returnArray.put(metaDataKey, metaDataValue);
			}
		}
	}
	else {
		throw new IOException("File: " + f.getAbsolutePath() + " doesn't exist");
	}

	return returnArray;
}
 
Example 2
Source File: DisconnectionTask.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
@Override
public void execute(JSONArray args, CallbackContext ctx) {
    try {
        int id = args.getInt(0);
        int code = args.getInt(1);
        String reason = args.getString(2);
        Connection conn = _map.get(id);

        if (conn != null) {
            if (code > 0) {
                conn.close(code, reason);
            } else {
                conn.close();
            }
        }
    } catch (Exception e) {
        ctx.error("close");
    }
}
 
Example 3
Source File: JobCoder.java    From firebase-jobdispatcher-android with Apache License 2.0 6 votes vote down vote up
@NonNull
private static List<ObservedUri> convertJsonToObservedUris(@NonNull String contentUrisJson) {
  List<ObservedUri> uris = new ArrayList<>();
  try {
    JSONObject json = new JSONObject(contentUrisJson);
    JSONArray jsonFlags = json.getJSONArray(JSON_URI_FLAGS);
    JSONArray jsonUris = json.getJSONArray(JSON_URIS);
    int length = jsonFlags.length();

    for (int i = 0; i < length; i++) {
      int flags = jsonFlags.getInt(i);
      String uri = jsonUris.getString(i);
      uris.add(new ObservedUri(Uri.parse(uri), flags));
    }
  } catch (JSONException e) {
    throw new RuntimeException(e);
  }
  return uris;
}
 
Example 4
Source File: RouterServiceValidator.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected boolean verifyVersion(int version, JSONArray versions){
	if(version<0){
		return false;
	}
	if(versions == null || versions.length()==0){
		return true;
	}
	for(int i=0;i<versions.length();i++){
		try {
			if(version == versions.getInt(i)){
				return false;
			}
		} catch (JSONException e) {
			continue;
		}
	}//We didn't find our version in the black list.
	return true;
}
 
Example 5
Source File: JideSplitPaneElementTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@Test
public void select2() {
    final JideSplitPane splitPaneNode = (JideSplitPane) ComponentUtils.findComponent(JideSplitPane.class, frame);
    final JSONArray initialValue = new JSONArray(splitPaneNode.getDividerLocations());
    driver = new JavaAgent();
    final IJavaElement splitPane = driver.findElementByCssSelector("jide-split-pane");
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            splitPane.marathon_select("[238,450]");
        }
    });
    new Wait("Waiting for split pane to set divider location") {
        @Override
        public boolean until() {
            return initialValue.getInt(1) != new JSONArray(splitPaneNode.getDividerLocations()).getInt(1);
        }
    };
    JSONArray pa = new JSONArray(splitPaneNode.getDividerLocations());
    AssertJUnit.assertEquals(450, pa.getInt(1));
}
 
Example 6
Source File: SendingTask.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
@Override
public void execute(JSONArray args, CallbackContext ctx) {
    try {
        int id = args.getInt(0);
        String data = args.getString(1);
        boolean binaryString = args.getBoolean(2);
        Connection conn = _map.get(id);

        if (conn != null) {
            if (binaryString) {
                byte[] binary = Base64.decode(data, Base64.NO_WRAP);
                conn.sendMessage(binary, 0, binary.length);
            } else {
                conn.sendMessage(data);
            }
        }
    } catch (Exception e) {
        ctx.error("send");
    }
}
 
Example 7
Source File: OpenWithPlugin.java    From android with GNU General Public License v3.0 6 votes vote down vote up
public boolean setVerbosity(final JSONArray data, final CallbackContext context) {
    log(DEBUG, "setVerbosity() " + data);
    if (data.length() != 1) {
        log(WARN, "setVerbosity() -> invalidAction");
        return false;
    }
    try {
        verbosity = data.getInt(0);
        log(DEBUG, "setVerbosity() -> ok");
        return PluginResultSender.ok(context);
    }
    catch (JSONException ex) {
        log(WARN, "setVerbosity() -> invalidAction");
        return false;
    }
}
 
Example 8
Source File: Message.java    From DragonGoApp with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void newMessage(JSONArray headers, JSONArray jsonmsg) {
    int msgididx=-1, fromididx=-1, typeidx=-1, subjectidx=-1, txtidx=-1;
    try {
        for (int i=0;i<headers.length();i++) {
            String h;
            h = headers.getString(i);
            System.out.println("jsonheader "+i+" ["+h+"]");
            if (h.equals("id")) msgididx=i;
            else if (h.equals("user_from.handle")) fromididx=i;
            else if (h.equals("type")) typeidx=i;
            else if (h.equals("text")) txtidx=i;
            else if (h.equals("subject")) subjectidx=i;
        }
        Message m = new Message();
        msgs.add(m);
        m.msgid = jsonmsg.getInt(msgididx);
        m.type = jsonmsg.getString(typeidx);
        if (fromididx<0) m.from = "unknown";
        else m.from = jsonmsg.getString(fromididx);
        m.subject = jsonmsg.getString(subjectidx);
        m.text = jsonmsg.getString(txtidx);
        m.show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example 9
Source File: Bundle.java    From shattered-pixel-dungeon-gdx with GNU General Public License v3.0 5 votes vote down vote up
public int[] getIntArray( String key ) {
	try {
		JSONArray array = data.getJSONArray( key );
		int length = array.length();
		int[] result = new int[length];
		for (int i=0; i < length; i++) {
			result[i] = array.getInt( i );
		}
		return result;
	} catch (JSONException e) {
		Game.reportException(e);
		return null;
	}
}
 
Example 10
Source File: OrderbookHandler.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
private BitfinexOrderBookEntry jsonToOrderBookEntry(final JSONArray jsonArray) {
    final BigDecimal price = jsonArray.getBigDecimal(0);
    final Integer count = jsonArray.getInt(1);
    final BigDecimal amount = jsonArray.getBigDecimal(2);

    return new BitfinexOrderBookEntry(null, price, amount, count);
}
 
Example 11
Source File: ParseTypes.java    From cordova-plugin-app-launcher with MIT License 5 votes vote down vote up
public static int[] toIntArray(JSONArray arr) throws JSONException {
	int jsize = arr.length();
	int[] exVal = new int[jsize];
	for(int j=0; j < jsize; j++) {
		exVal[j] = arr.getInt(j);
	}
	return exVal;
}
 
Example 12
Source File: CPUFreq.java    From SmartPack-Kernel-Manager with GNU General Public License v3.0 5 votes vote down vote up
private Integer[] getIntArray(JSONObject jsonObject, String key) {
    try {
        JSONArray array = jsonObject.getJSONArray(key);
        Integer[] integers = new Integer[array.length()];
        for (int i = 0; i < integers.length; i++) {
            integers[i] = array.getInt(i);
        }
        return integers;
    } catch (JSONException ignored) {
        return null;
    }
}
 
Example 13
Source File: PredesignedLevel.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
private void fillMapLayer(String layerName, int[] tiles) throws JSONException {
	if(mLevelDesc.has(layerName)) {
		JSONArray layer = mLevelDesc.getJSONArray(layerName);

		for (int i = 0; i < layer.length(); i++) {
			tiles[i]=layer.getInt(i);
		}
	}
}
 
Example 14
Source File: Bundle.java    From shattered-pixel-dungeon with GNU General Public License v3.0 5 votes vote down vote up
public int[] getIntArray( String key ) {
	try {
		JSONArray array = data.getJSONArray( key );
		int length = array.length();
		int[] result = new int[length];
		for (int i=0; i < length; i++) {
			result[i] = array.getInt( i );
		}
		return result;
	} catch (JSONException e) {
		Game.reportException(e);
		return null;
	}
}
 
Example 15
Source File: JideSplitPaneElement.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean marathon_select(String value) {
    JideSplitPane splitPane = (JideSplitPane) getComponent();
    JSONArray locations = new JSONArray(value);
    int[] dividerLocations = new int[locations.length()];
    for (int i = 0; i < locations.length(); i++) {
        dividerLocations[i] = locations.getInt(i);
    }
    splitPane.setDividerLocations(dividerLocations);
    return true;
}
 
Example 16
Source File: QSJSONUtil.java    From qingstor-sdk-java with Apache License 2.0 5 votes vote down vote up
public static int toJSONInt(JSONArray jsonArray, int index) {
    int obj = 0;
    if (jsonArray == null || jsonArray.length() <= index) {
        return obj;
    }
    try {
        obj = jsonArray.getInt(index);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}
 
Example 17
Source File: SolrJSONResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected Map<String,List<Map<String,String>>> buildRanges(JSONObject facet_ranges) throws JSONException
{
    Map<String,List<Map<String,String>>> ranges = new HashMap<>();

    for(Iterator it = facet_ranges.keys(); it.hasNext();)
    {
        String fieldName = (String) it.next();
        String end = "";
        try
        {
            end = facet_ranges.getJSONObject(fieldName).getString("end");
        }
        catch(JSONException e)
        {
            end = String.valueOf(facet_ranges.getJSONObject(fieldName).getInt("end"));
        }
        JSONArray rangeCollection = facet_ranges.getJSONObject(fieldName).getJSONArray("counts");
        List<Map<String, String>> buckets = new ArrayList<Map<String, String>>();
        for(int i = 0; i < rangeCollection.length(); i+=2)
        {
            String position = i == 0 ? "head":"body";
            if( i+2 == rangeCollection.length())
            {
                position = "tail";
            }
            Map<String,String> rangeMap = new HashMap<String,String>(3);
            String rangeFrom = rangeCollection.getString(i);
            int facetRangeCount = rangeCollection.getInt(i+1);
            String rangeTo = (i+2 < rangeCollection.length() ? rangeCollection.getString(i+2):end);
            String label = rangeFrom + " - " + rangeTo;
            rangeMap.put(GenericFacetResponse.LABEL, label);
            rangeMap.put(GenericFacetResponse.COUNT, String.valueOf(facetRangeCount));
            rangeMap.put(GenericFacetResponse.START, rangeFrom);
            rangeMap.put(GenericFacetResponse.END, rangeTo);
            rangeMap.put("bucketPosition", position);
            buckets.add(rangeMap);
        }
        ranges.put(fieldName, buckets);
    }

    return ranges;
}
 
Example 18
Source File: JsCallJava.java    From AgentWeb with Apache License 2.0 4 votes vote down vote up
public String call(WebView webView, JSONObject jsonObject) {
    long time = 0;
    if (LogUtils.isDebug()) {
        time = android.os.SystemClock.uptimeMillis();
    }
    if (jsonObject != null) {
        try {
            String methodName = jsonObject.getString(KEY_METHOD);
            JSONArray argsTypes = jsonObject.getJSONArray(KEY_TYPES);
            JSONArray argsVals = jsonObject.getJSONArray(KEY_ARGS);
            String sign = methodName;
            int len = argsTypes.length();
            Object[] values = new Object[len];
            int numIndex = 0;
            String currType;

            for (int k = 0; k < len; k++) {
                currType = argsTypes.optString(k);
                if ("string".equals(currType)) {
                    sign += "_S";
                    values[k] = argsVals.isNull(k) ? null : argsVals.getString(k);
                } else if ("number".equals(currType)) {
                    sign += "_N";
                    numIndex = numIndex * 10 + k + 1;
                } else if ("boolean".equals(currType)) {
                    sign += "_B";
                    values[k] = argsVals.getBoolean(k);
                } else if ("object".equals(currType)) {
                    sign += "_O";
                    values[k] = argsVals.isNull(k) ? null : argsVals.getJSONObject(k);
                } else if ("function".equals(currType)) {
                    sign += "_F";
                    values[k] = new JsCallback(webView, mInterfacedName, argsVals.getInt(k));
                } else {
                    sign += "_P";
                }
            }

            Method currMethod = mMethodsMap.get(sign);

            // 方法匹配失败
            if (currMethod == null) {
                return getReturn(jsonObject, 500, "not found method(" + sign + ") with valid parameters", time);
            }
            // 数字类型细分匹配
            if (numIndex > 0) {
                Class[] methodTypes = currMethod.getParameterTypes();
                int currIndex;
                Class currCls;
                while (numIndex > 0) {
                    currIndex = numIndex - numIndex / 10 * 10 - 1;
                    currCls = methodTypes[currIndex];
                    if (currCls == int.class) {
                        values[currIndex] = argsVals.getInt(currIndex);
                    } else if (currCls == long.class) {
                        //WARN: argsJson.getLong(k + defValue) will return a bigger incorrect number
                        values[currIndex] = Long.parseLong(argsVals.getString(currIndex));
                    } else {
                        values[currIndex] = argsVals.getDouble(currIndex);
                    }
                    numIndex /= 10;
                }
            }

            return getReturn(jsonObject, 200, currMethod.invoke(mInterfaceObj, values), time);
        } catch (Exception e) {
            LogUtils.safeCheckCrash(TAG, "call", e);
            //优先返回详细的错误信息
            if (e.getCause() != null) {
                return getReturn(jsonObject, 500, "method execute result:" + e.getCause().getMessage(), time);
            }
            return getReturn(jsonObject, 500, "method execute result:" + e.getMessage(), time);
        }
    } else {
        return getReturn(jsonObject, 500, "call data empty", time);
    }
}
 
Example 19
Source File: OrderHandler.java    From bitfinex-v2-wss-api-java with Apache License 2.0 4 votes vote down vote up
private BitfinexSubmittedOrder jsonToBitfinexSubmittedOrder(final JSONArray json) {
    final BitfinexSubmittedOrder order = new BitfinexSubmittedOrder();
    order.setOrderId(json.getLong(0));
    final String gid = json.optString(1, null);
    if (gid != null) {
        order.setClientGroupId(Long.parseLong(gid));
    }
    final String cid = json.optString(2, null);
    if (cid != null) {
        order.setClientId(Long.parseLong(cid));
    }
    order.setCurrencyPair(BitfinexCurrencyPair.fromSymbolString(json.getString(3)));
    order.setCreatedTimestamp(json.getLong(4));
    final String updatedTimestamp = json.optString(5, null);
    if (updatedTimestamp != null) {
        order.setUpdatedTimestamp(Long.parseLong(updatedTimestamp));
    }
    order.setAmount(json.getBigDecimal(6));
    order.setAmountAtCreation(json.getBigDecimal(7));
    order.setOrderType(BitfinexOrderType.fromBifinexString(json.getString(8)));
    
    final int flags = json.getInt(12);
    if (flags > 0) {      
    		order.setOrderFlags(flags);
    }
    
    final String orderStatus = json.getString(13);
    if (orderStatus != null) {
        order.setStatus(BitfinexSubmittedOrderStatus.fromString(orderStatus));
    }
    
    order.setPrice(json.optBigDecimal(16, null));
    order.setPriceAverage(json.optBigDecimal(17, null));
    order.setPriceTrailing(json.optBigDecimal(18, null));
    order.setPriceAuxLimit(json.optBigDecimal(19, null));

    final String parentOrderId = json.optString(25, null);
    if (parentOrderId != null) {
        order.setParentOrderId(Long.parseLong(parentOrderId));
    }
    final String parentOrderType = json.optString(9, null);
    if (parentOrderType != null) {
        order.setParentOrderType(BitfinexOrderType.fromBifinexString(parentOrderType));
    }
    return order;
}
 
Example 20
Source File: ReadPlista.java    From StreamingRec with Apache License 2.0 4 votes vote down vote up
/**
 * This method extracts the information about a user click from a json
 * string
 * 
 * @param jsonstr -
 * @param eventNotification -
 * @return a csv line
 */
private static String readRecommendationRequestOrEventNotification(String jsonstr, boolean eventNotification) {
	//parse the JSON sting to a json object
	JSONObject linejson = new JSONObject(jsonstr);
	// context
	JSONObject contextRR = linejson.getJSONObject("context");
	// each context object contains object of type: simple, lists, cluster
	JSONObject simpleRR = contextRR.getJSONObject("simple");
	JSONObject listRR = contextRR.getJSONObject("lists");

	//create a tmp transaction project (click info + some item metadata 
	//that needs to be merged to item objects later)
	TmpPlistaTransaction transaction = new TmpPlistaTransaction();
	// each list object contains a list of tuples
	// code_11 is Category of the news article
	if (listRR.has("11")) {
		JSONArray categoryArray = listRR.getJSONArray("11");
		if (categoryArray.length() > 1) {
			System.err.println("More than one category.");
		} else if (categoryArray.length() == 1) {
			transaction.category = categoryArray.getInt(0);
		}
	}

	// each simple objects contains a list of tuples
	// code_27 is publisher ID
	if (simpleRR.has("27")) {
		transaction.publisher = simpleRR.getInt("27");
	}

	// code_57 is user cookie
	if (simpleRR.has("57")) {
		transaction.cookie = simpleRR.getLong("57");
	}
	
	// code_25 is item ID
	if (simpleRR.has("25")) {
		transaction.item = new Item();
		transaction.item.id = simpleRR.getLong("25");
	}

	// timestamp
	if (linejson.has("timestamp")) {
		transaction.timestamp = new Date(linejson.getLong("timestamp"));
	}

	// Different branch for event notification
	if (eventNotification) {
		// We dont need to differentiate between event notification and
		// recommendation request right now.
		// But maybe in the future. We can do it here.
	}
	
	JSONObject clustersRR = contextRR.getJSONObject("clusters");
	//keywords
	if (extractText && clustersRR.has("33")) {
		Object object = clustersRR.get("33");
		if(!(object instanceof JSONArray)){
			//replace special line-breaking character 0xAD
			JSONObject keywordObj = (JSONObject) object;
			transaction.keywords = new Object2IntOpenHashMap<>();
			for (String key : keywordObj.keySet()) {
				transaction.keywords.addTo(key.replaceAll(",", " ").replaceAll(Character.toString((char) 0xAD), ""), keywordObj.getInt(key));
			}
		}			
	}

	// create CSV line
	return transaction.toString();
}