List of usage examples for org.json JSONArray getDouble
public double getDouble(int index) throws JSONException
From source file:com.jennifer.ui.chart.grid.RangeGrid.java
private void checkValueFormat(JSONArray ticks) { int doubleCount = 0; for (int i = 0, len = ticks.length(); i < len; i++) { if (ticks.getDouble(i) != ticks.getInt(i)) doubleCount++;//w w w .j a v a2s .c o m } if (!options.has("format")) { if (doubleCount > 0) { options.put("format", "###.##"); } else { options.put("format", "###"); } } }
From source file:com.graphhopper.http.GraphHopperWeb.java
@Override public GHResponse route(GHRequest request) { StopWatch sw = new StopWatch().start(); double took = 0; try {/* w w w .j av a2 s .com*/ String places = ""; for (GHPoint p : request.getPoints()) { places += "point=" + p.lat + "," + p.lon + "&"; } String url = serviceUrl + "?" + places + "&type=json" + "&points_encoded=" + pointsEncoded + "&min_path_precision=" + request.getHint("douglas.minprecision", 1) + "&algo=" + request.getAlgorithm() + "&locale=" + request.getLocale().toString() + "&elevation=" + withElevation; if (!request.getVehicle().isEmpty()) url += "&vehicle=" + request.getVehicle(); if (!key.isEmpty()) url += "&key=" + key; String str = downloader.downloadAsString(url); JSONObject json = new JSONObject(str); GHResponse res = new GHResponse(); if (json.getJSONObject("info").has("errors")) { JSONArray errors = json.getJSONObject("info").getJSONArray("errors"); for (int i = 0; i < errors.length(); i++) { JSONObject error = errors.getJSONObject(i); String exClass = error.getString("details"); String exMessage = error.getString("message"); if (exClass.equals(UnsupportedOperationException.class.getName())) { res.addError(new UnsupportedOperationException(exMessage)); } else if (exClass.equals(IllegalStateException.class.getName())) { res.addError(new IllegalStateException(exMessage)); } else if (exClass.equals(RuntimeException.class.getName())) { res.addError(new RuntimeException(exMessage)); } else if (exClass.equals(IllegalArgumentException.class.getName())) { res.addError(new IllegalArgumentException(exMessage)); } else { res.addError(new Exception(exClass + " " + exMessage)); } } return res; } else { took = json.getJSONObject("info").getDouble("took"); JSONArray paths = json.getJSONArray("paths"); JSONObject firstPath = paths.getJSONObject(0); double distance = firstPath.getDouble("distance"); int time = firstPath.getInt("time"); PointList pointList; if (pointsEncoded) { String pointStr = firstPath.getString("points"); pointList = WebHelper.decodePolyline(pointStr, 100, withElevation); } else { JSONArray coords = firstPath.getJSONObject("points").getJSONArray("coordinates"); pointList = new PointList(coords.length(), withElevation); for (int i = 0; i < coords.length(); i++) { JSONArray arr = coords.getJSONArray(i); double lon = arr.getDouble(0); double lat = arr.getDouble(1); if (withElevation) pointList.add(lat, lon, arr.getDouble(2)); else pointList.add(lat, lon); } } if (instructions) { JSONArray instrArr = firstPath.getJSONArray("instructions"); InstructionList il = new InstructionList(trMap.getWithFallBack(request.getLocale())); for (int instrIndex = 0; instrIndex < instrArr.length(); instrIndex++) { JSONObject jsonObj = instrArr.getJSONObject(instrIndex); double instDist = jsonObj.getDouble("distance"); String text = jsonObj.getString("text"); long instTime = jsonObj.getLong("time"); int sign = jsonObj.getInt("sign"); JSONArray iv = jsonObj.getJSONArray("interval"); int from = iv.getInt(0); int to = iv.getInt(1); PointList instPL = new PointList(to - from, withElevation); for (int j = from; j <= to; j++) { instPL.add(pointList, j); } // TODO way and payment type Instruction instr = new Instruction(sign, text, InstructionAnnotation.EMPTY, instPL) .setDistance(instDist).setTime(instTime); il.add(instr); } res.setInstructions(il); } return res.setPoints(pointList).setDistance(distance).setMillis(time); } } catch (Exception ex) { throw new RuntimeException( "Problem while fetching path " + request.getPoints() + ": " + ex.getMessage(), ex); } finally { logger.debug("Full request took:" + sw.stop().getSeconds() + ", API took:" + took); } }
From source file:com.jennifer.ui.chart.grid.RadarGrid.java
private void drawRadial(double centerX, double centerY, double x, double y, int count, double unit) { Transform group = root.group(); JSONArray points = new JSONArray(); points.put(new JSONArray().put(centerX + x).put(centerY + y)); double startX = x; double startY = y; for (int i = 0; i < count; i++) { JSONObject obj = MathUtil.rotate(startX, startY, unit); startX = obj.getDouble("x"); startY = obj.getDouble("y"); points.put(new JSONArray().put(centerX + startX).put(centerY + startY)); }/*from w w w .j a va2 s. c o m*/ Path path = group .path(new JSONObject().put("fill", "none").put("stroke", chart.theme("gridAxisBorderColor")) .put("stroke-width", chart.theme("gridBorderWidth"))); for (int i = 0, len = points.length(); i < len; i++) { JSONArray point = (JSONArray) points.getJSONArray(i); if (i == 0) { path.MoveTo(point.getDouble(0), point.getDouble(1)); } else { path.LineTo(point.getDouble(0), point.getDouble(1)); } } path.LineTo(points.getJSONArray(0).getDouble(0), points.getJSONArray(0).getDouble(1)); }
From source file:ca.uqac.florentinth.speakerauthentication.Utils.JSONUtils.java
public static List JSONToVoiceSampleObject(String json) { ArrayList list = new ArrayList(); try {//from ww w . j a v a 2 s . c o m JSONObject jsonObject = new JSONObject(json); JSONArray jsonArray = jsonObject.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject obj = jsonArray.getJSONObject(i); String className = obj.getString("class"); double[] voiceFeatures = new double[Features.getInstance().getNumberFeatures()]; JSONArray features = obj.getJSONArray("voice_features"); for (int j = 0; j < features.length(); j++) { voiceFeatures[j] = features.getDouble(j); } VoiceSample sample = new VoiceSample(className, voiceFeatures); list.add(sample); } } catch (JSONException e) { e.printStackTrace(); } return list; }
From source file:com.funzio.pure2D.particles.nova.vo.NovaVO.java
protected static ArrayList<Float> getListFloat(final JSONObject json, final String field) throws JSONException { // field check if (!json.has(field)) { return null; }/*w w w . j a v a2s . c o m*/ final ArrayList<Float> result = new ArrayList<Float>(); try { final JSONArray array = json.getJSONArray(field); if (array != null) { final int size = array.length(); for (int i = 0; i < size; i++) { result.add((float) array.getDouble(i)); } } } catch (JSONException e) { // single value result.add((float) json.getDouble(field)); } return result; }
From source file:com.microsoft.research.webngram.service.impl.GenerationServiceImpl.java
@Override public TokenSet generate(String authorizationToken, String modelUrn, String phraseContext, Integer maxN, String cookie) {// w ww. j a va 2 s. com try { NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder( NgramServiceApiUrls.GENERATE_URL); String apiUrl = urlBuilder.withParameter(ParameterNames.USER_TOKEN, authorizationToken) .withField(ParameterNames.MODEL_URL, modelUrn) .withParameter(ParameterNames.PHRASE, phraseContext) .withParameter(ParameterNames.MAX_TOKENS, maxN.toString()) .withParameter(ParameterNames.COOKIE, cookie).buildUrl(); TokenSet tokenSet = new TokenSet(); JSONObject object = new JSONObject(convertStreamToString(callApiGet(apiUrl))); tokenSet.setBackoff(object.getDouble("backoff")); tokenSet.setCookie(object.getString("cookie")); JSONArray probabilities = object.getJSONArray("probabilities"); for (int i = 0; i < probabilities.length(); i++) { tokenSet.getProbabilities().add(probabilities.getDouble(i)); } JSONArray words = object.getJSONArray("words"); for (int i = 0; i < words.length(); i++) { tokenSet.getWords().add(words.getString(i)); } return tokenSet; } catch (Exception e) { throw new NgramServiceException("An error occurred while generating token set.", e); } }
From source file:com.galactogolf.serialization.JSONSerializer.java
private static float[] fromFloatArrayJSON(JSONArray floatArrayJSON) throws JSONException { float[] floatArray = new float[floatArrayJSON.length()]; for (int i = 0; i < floatArrayJSON.length(); i++) { floatArray[i] = (float) floatArrayJSON.getDouble(i); }/*from ww w .j a va2 s . c om*/ return floatArray; }
From source file:com.graphhopper.http.NearestServletIT.java
@Test public void testBasicNearestQuery() throws Exception { JSONObject json = nearestQuery("point=42.554851,1.536198"); assertFalse(json.has("error")); JSONArray point = json.getJSONArray("coordinates"); assertTrue("returned point is not 2D: " + point, point.length() == 2); double lon = point.getDouble(0); double lat = point.getDouble(1); assertTrue("nearest point wasn't correct: lat=" + lat + ", lon=" + lon, lat == 42.55483907636756 && lon == 1.5363742288086868); }
From source file:com.sesamtv.cordova.chromecast.ChromeCast.java
private boolean executeActions(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { switch (Actions.valueOf(action)) { case sendMessage: cordova.getThreadPool().execute(new Runnable() { public void run() { try { String channelName = args.getString(0); String msg = args.getString(1); sendMessage(channelName, msg, callbackContext); } catch (Exception e) { callbackContext.error(e.getMessage()); }/*w w w .j a va2 s.c om*/ } }); break; case loadMedia: loadMediaAction(args.getJSONObject(0), callbackContext); break; case pauseMedia: pauseMediaAction(callbackContext); break; case stopMedia: stopMediaAction(callbackContext, args); break; case playMedia: playMediaAction(callbackContext); break; case seekMediaBy: try { seekMediaByAction(args.getLong(0)); callbackContext.success(); } catch (IOException e) { callbackContext.error(e.getMessage()); } break; case seekMedia: try { seekMediaAction(args.getLong(0)); callbackContext.success(); } catch (IOException e) { callbackContext.error(e.getMessage()); } break; case setDeviceVolume: final double vol = args.getDouble(0); Log.d(TAG, "setVolume " + vol); cordova.getThreadPool().execute(new Runnable() { public void run() { setVolumeAction(vol, callbackContext); } }); break; case setDeviceVolumeBy: cordova.getThreadPool().execute(new Runnable() { public void run() { try { setVolumeByAction(args.getDouble(0), callbackContext); } catch (JSONException e) { callbackContext.error(e.getMessage()); } } }); break; case setMuted: final boolean muted = args.getBoolean(0); Log.d(TAG, "setMuted " + muted); cordova.getThreadPool().execute(new Runnable() { public void run() { setDeviceMutedAction(muted, callbackContext); } }); break; case toggleMuted: Log.d(TAG, "toggleMuted "); cordova.getThreadPool().execute(new Runnable() { public void run() { toggleDeviceMutedAction(callbackContext); } }); break; case getMediaStatus: Log.d(TAG, "getMediaStatus"); callbackContext.sendPluginResult(getMediaStatus()); break; case stopApplication: try { Log.d(TAG, "stopCast"); stopApplication(); callbackContext.success(); } catch (Exception e) { callbackContext.error("stop cast failed :" + e.getMessage()); return false; } break; default: callbackContext.error("Invalid action: " + action); } return true; }