private IGeometry decodeGeometry(JSONObject object) throws JSONException { IGeometry geom = null; LineString[] lineStrings; if (object.get("type").equals("MultiLineString")) { JSONArray coordinates = object.getJSONArray("coordinates"); int size = coordinates.length(); lineStrings = new LineString[size]; LineString l; for (int i = 0; i < size; i++) { JSONArray lineStrCoord = coordinates.getJSONArray(i); double[][] coords = this.decodeLineStringCoords(lineStrCoord); l = new LineString(coords[0], coords[1]); lineStrings[i] = l; } geom = new MultiLineString(lineStrings); } else if (object.get("type").equals("LineString")) { JSONArray coordinates = object.getJSONArray("coordinates"); double[][] coords = this.decodeLineStringCoords(coordinates); geom = new LineString(coords[0], coords[1]); } else if (object.get("type").equals("Point")) { JSONArray coordinates = object.getJSONArray("coordinates"); geom = new Point(coordinates.getDouble(0), coordinates.getDouble(1)); } else if (object.get("type").equals("Polygon")) { JSONArray coordinates = object.getJSONArray("coordinates"); double[][] coords = this.decodeLineStringCoords(coordinates); geom = new Polygon(coords[0], coords[1]); } return geom; }
private ArrayList<LatLng> parseJsonLocation(JSONObject jsonLocation) { ArrayList<LatLng> points = new ArrayList<>(); try { JSONObject json = jsonLocation; // JSONArray features = json.getJSONArray("features"); // JSONObject feature = features.getJSONObject(0); JSONObject geometry = json.getJSONObject("geometry"); if (geometry != null) { String type = geometry.getString("type"); if (!TextUtils.isEmpty(type) && type.equalsIgnoreCase("LineString")) { JSONArray coords = geometry.getJSONArray("coordinates"); for (int i = 0; i < coords.length(); i++) { JSONArray coord = coords.getJSONArray(i); LatLng latLng = new LatLng(coord.getDouble(0), coord.getDouble(1)); points.add(latLng); Log.i(TAG, "아" + points.get(i).getLatitude() + " , " + points.get(i).getLongitude()); } } } } catch (Exception e) { Log.e(TAG, "Excepting Parsing GeoJson: " + e.toString()); } return points; }
public static Tweet parseTweet(JSONObject input) { // Example of a tweet in JSON format: // https://dev.twitter.com/docs/api/1/get/search // logger.info("parsing as twitter doc"); try { Tweet t = new Tweet(); JSONObject user; user = input.getJSONObject("user"); t.userID = user.getLong("id"); t.text = input.getString("text"); t.isRetweet = !input.isNull("retweeted_status"); t.setDoctype(DocumentType.TWIITER_DOC); if (input.has("coordinates") && !input.isNull("coordinates")) { JSONObject geo = (JSONObject) input.getJSONObject("coordinates"); if (geo.getString("type") == "Point") { JSONArray coords = geo.getJSONArray("coordinates"); GeoLabel.LonLatPair geotag = new GeoLabel.LonLatPair(); geotag.setLongitude(coords.getDouble(0)); geotag.setLatitude(coords.getDouble(1)); } } return t; } catch (JSONException e) { logger.error("Json exception in parsing tweet: " + input); logger.error(elog.toStringException(e)); throw new RuntimeException(e); } }
public List<Object> parseJSONArray(JSONArray values, Table table) throws ParseException { List<Object> parsedValues = new ArrayList<>(); for (int i = 0; i < table.getColumnsCount(); i++) { Class<?> type = table.getColumnType(i); Object val = values.get(i); if (val.equals(null)) { parsedValues.add(null); } else if (type == Integer.class && val.getClass() == Integer.class) { parsedValues.add(values.getInt(i)); } else if (type == Long.class && (val.getClass() == Long.class || val.getClass() == Integer.class)) { parsedValues.add(values.getLong(i)); } else if (type == Byte.class && val.getClass() == Integer.class) { Integer a = values.getInt(i); parsedValues.add(a.byteValue()); } else if (type == Float.class && val.getClass() == Double.class) { Double a = values.getDouble(i); parsedValues.add(a.floatValue()); } else if (type == Double.class && val.getClass() == Double.class) { parsedValues.add(values.getDouble(i)); } else if (type == Boolean.class && val.getClass() == Boolean.class) { parsedValues.add(values.getBoolean(i)); } else if (type == String.class && val.getClass() == String.class) { parsedValues.add(val); } else { throw new ParseException("types mismatch", 0); } } return parsedValues; }
/** * Creates a Fuzzy Set by parsing a JSON object. * * <p>{ "name" : String, "value" : [ [ Real, Real ], // X,Y ... ] } * * <p>Where name is the name of the Fuzzy Set, and value is a list of points that make up the set. * * @param object JSON object describing a fuzzy set */ public FuzzySet(JSONObject object) { name = object.getString("name"); values = new ArrayList<>(); JSONArray valuesArray = object.getJSONArray("value"); for (int i = 0; i < valuesArray.length(); ++i) { JSONArray point = valuesArray.getJSONArray(i); Pair pair = new Pair(point.getDouble(0), point.getDouble(1)); addValue(pair); } }
public Position(JSONArray pos) { for (int i = 0; i < 2; i++) { try { if (i == 0) { this.x = pos.getDouble(i); } else if (i == 1) { this.y = pos.getDouble(i); } } catch (JSONException e) { System.err.println("[Building Tank Position] JSON Error"); } } }
/** * set width * * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setWidth(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); float width = (float) args.getDouble(2) * this.density; this.setFloat("setWidth", id, width, callbackContext); }
private Marker processJSONObject(JSONObject jo) { if (jo == null) throw new NullPointerException(); if (!jo.has("geometry")) throw new NullPointerException(); Marker ma = null; try { Double lat = null, lon = null; if (!jo.isNull("geometry")) { JSONObject geo = jo.getJSONObject("geometry"); JSONArray coordinates = geo.getJSONArray("coordinates"); lon = coordinates.getDouble(0); lat = coordinates.getDouble(1); } if (lat != null) { String user = jo.getString("id"); ma = new IconMarker(user, lat, lon, 0, Color.RED, icon); } Log.i("point", lon + ", " + lat + ": " + ma.getName()); } catch (Exception e) { e.printStackTrace(); } return ma; }
/** * set z-index * * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setZIndex(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); float zIndex = (float) args.getDouble(2); this.setFloat("setZIndex", id, zIndex, callbackContext); }
private static List<?> getList(JSONArray jsonArray, Class<?> childrenType) throws JSONException, IllegalAccessException, InstantiationException { List<Object> list = new Vector<Object>(jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { Object child = null; if (childrenType == List.class) { child = getList(jsonArray.getJSONArray(i), childrenType); } else if (childrenType == String.class) { child = jsonArray.getString(i); } else if (childrenType == boolean.class || childrenType == Boolean.class) { child = jsonArray.getBoolean(i); } else if (childrenType == int.class || childrenType == Integer.class) { child = jsonArray.getInt(i); } else if (childrenType == double.class || childrenType == Double.class) { child = jsonArray.getDouble(i); } else { child = childrenType.newInstance(); reflectJsonObject(child, jsonArray.getJSONObject(i)); } list.add(child); } return list; }
public Reitti lueReitti(File tiedosto) { JSONObject obj = this.lataaJsonObject(tiedosto); JSONArray arr = obj.getJSONArray("features"); double[] lat = new double[arr.length()]; double[] lon = new double[arr.length()]; int[] aika = new int[arr.length()]; for (int i = 0; i < arr.length(); i++) { JSONArray piste = arr.getJSONObject(i).getJSONObject("geometry").getJSONArray("coordinates"); lat[i] = piste.getDouble(1); lon[i] = piste.getDouble(0); String aikaString = arr.getJSONObject(i).getJSONObject("properties").getString("time"); DateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss", Locale.ENGLISH); Date timestamp = null; try { timestamp = format.parse(aikaString); } catch (ParseException ex) { System.out.println("format ex"); } int sekunnit = (int) timestamp.getTime() / 1000; aika[i] = sekunnit; } Reitti reitti = new Reitti(lon, lat, aika); return reitti; }
/* Parse the json file into list of GeoPoints */ private List<GeoPoint> getGeoPoints(String json) { List<GeoPoint> geoPoints = new ArrayList<GeoPoint>(); try { // get rid of renderAdvancedNarrative JSONObject obj = new JSONObject(json.replace("renderAdvancedNarrative(", "").replace(")", "")); JSONObject route = obj.getJSONObject("route"); JSONObject shape = route.getJSONObject("shape"); JSONArray shapePoints = shape.getJSONArray("shapePoints"); // get each latlon pair and add to geopoint list for (int i = 0; i < shapePoints.length(); i = i + 2) { Double lat = shapePoints.getDouble(i); Double lng = shapePoints.getDouble(i + 1); geoPoints.add(new GeoPoint(lat, lng)); } } catch (JSONException e) { e.printStackTrace(); } return geoPoints; }
public static float[] getFloatArray(SharedPreferences pref, String key) { float[] array = null; String s = pref.getString(key, null); if (s != null) { try { JSONArray json = new JSONArray(s); array = new float[json.length()]; for (int i = 0; i < array.length; i++) array[i] = (float) json.getDouble(i); } catch (JSONException e) { e.printStackTrace(); } } return array; }
private void executeLogEvent(JSONArray args, CallbackContext callbackContext) throws JSONException { if (args.length() == 0) { // Not enough parameters callbackContext.error("Invalid arguments"); return; } String eventName = args.getString(0); if (args.length() == 1) { logger.logEvent(eventName); callbackContext.success(); return; } // Arguments is greater than 1 JSONObject params = args.getJSONObject(1); Bundle parameters = new Bundle(); Iterator<String> iter = params.keys(); while (iter.hasNext()) { String key = iter.next(); try { // Try get a String String value = params.getString(key); parameters.putString(key, value); } catch (JSONException e) { // Maybe it was an int Log.w(TAG, "Type in AppEvent parameters was not String for key: " + key); try { int value = params.getInt(key); parameters.putInt(key, value); } catch (JSONException e2) { // Nope Log.e(TAG, "Unsupported type in AppEvent parameters for key: " + key); } } } if (args.length() == 2) { logger.logEvent(eventName, parameters); callbackContext.success(); } if (args.length() == 3) { double value = args.getDouble(2); logger.logEvent(eventName, value, parameters); callbackContext.success(); } }
private void deserializeFromObj(JSONObject obj) throws JSONException { this.TravelMode = obj.optString("travelMode"); this.TravelDistance = obj.optDouble("travelDistance"); this.TravelDuration = obj.optLong("travelDuration"); JSONObject maneuverPoint = obj.getJSONObject("maneuverPoint"); if (maneuverPoint != null) { JSONArray jsonArray = maneuverPoint.optJSONArray("coordinates"); if (jsonArray != null && jsonArray.length() >= 2) { this.ManeuverPoint = new Coordinate(jsonArray.getDouble(0), jsonArray.getDouble(1)); } } JSONObject instruction = obj.getJSONObject("instruction"); this.Instruction = new Instruction(instruction); this.CompassDirection = obj.optString("compassDirection"); JSONArray hints = obj.optJSONArray("hint"); if (hints != null) { this.Hint = new Hint[hints.length()]; for (int i = 0; i < hints.length(); i++) { this.Hint[i] = new Hint(hints.getJSONObject(i)); } } JSONArray warnings = obj.optJSONArray("warning"); if (warnings != null) { this.Warning = new Warning[warnings.length()]; for (int i = 0; i < warnings.length(); i++) { this.Warning[i] = new Warning(warnings.getJSONObject(i)); } } }
// Generate a bathroom object based on an incoming JSON file from server public void setDetails(JSONObject details) throws JSONException { JSONArray loc = details.getJSONArray("loc"); mID = details.getInt("id"); mLocation = new LatLng(loc.getDouble(0), loc.getDouble(1)); mClass = details.getString("class"); mGender = details.getString("gender"); mNovelty = (float) details.getDouble("novelty"); mCleanliness = (float) details.getDouble("cleanliness"); mFloor = details.getInt("floor"); mPrivate = details.getBoolean("public"); mPaper = details.getBoolean("paper"); mDryers = details.getBoolean("dryers"); mStalls = details.getInt("stalls"); mHandicap = details.getBoolean("handicap"); mSinks = details.getInt("sinks"); mSanitizer = details.getBoolean("sanitizer"); mBaby = details.getBoolean("baby"); mUrinals = details.getInt("urinals"); mFeminine = details.getBoolean("feminine"); mMedicine = details.getBoolean("medicine"); mContraceptive = details.getBoolean("contraceptive"); mComplete = true; }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try { if (action.equals("isScreenReaderRunning")) { isScreenReaderRunning(callbackContext); return true; } else if (action.equals("isClosedCaptioningEnabled")) { isClosedCaptioningEnabled(callbackContext); return true; } else if (action.equals("isTouchExplorationEnabled")) { isTouchExplorationEnabled(callbackContext); return true; } else if (action.equals("postNotification")) { if (args.length() > 1) { String string = args.getString(1); if (!string.isEmpty()) { announceForAccessibility(string, callbackContext); } } return true; } else if (action.equals("getTextZoom")) { getTextZoom(callbackContext); return true; } else if (action.equals("setTextZoom")) { if (args.length() > 0) { double textZoom = args.getDouble(0); if (textZoom > 0) { setTextZoom(textZoom, callbackContext); } } return true; } else if (action.equals("updateTextZoom")) { updateTextZoom(callbackContext); return true; } else if (action.equals("start")) { start(callbackContext); return true; } else if (action.equals("stop")) { stop(); return true; } } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; }
public static float[] getFloatArray(SharedPreferences pref, String key) { float[] array = null; String s = pref.getString(key, null); if (s != null) { try { JSONArray json = new JSONArray(s); array = new float[json.length()]; for (int i = 0; i < array.length; i++) { array[i] = (float) json.getDouble(i); } } catch (JSONException e) { Log.e(TAG, "getFloatArray: " + e.getClass() + ": " + e.getLocalizedMessage()); } } return array; }
public static PredictionModel parseJSON(String jsonString) throws JSONException { PredictionModel result = new PredictionModel(); JSONObject object = new JSONObject(jsonString); result.setAccuracy((float) object.getDouble("acc")); result.setMinRssi((float) object.getDouble("min_rssi")); result.setMaxRssi((float) object.getDouble("max_rssi")); JSONArray bArray = object.getJSONArray("b"); float[] b = new float[bArray.length()]; for (int i = 0; i < bArray.length(); ++i) { b[i] = (float) bArray.getDouble(i); } result.setB(b); JSONArray WArray = object.getJSONArray("W"); int width = WArray.length(); int height = WArray.getJSONArray(0).length(); float[][] W = new float[height][width]; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { W[y][x] = (float) WArray.getJSONArray(x).getDouble(y); } } result.setW(W); JSONObject roomsObject = object.getJSONObject("rooms"); Iterator<String> roomKeys = roomsObject.keys(); while (roomKeys.hasNext()) { String roomName = roomKeys.next(); int roomIndex = roomsObject.getInt(roomName); result.getRooms().put(roomName, roomIndex); } JSONObject tagsObject = object.getJSONObject("tags"); Iterator<String> tagKeys = tagsObject.keys(); while (tagKeys.hasNext()) { String tagAddress = tagKeys.next(); int tagIndex = tagsObject.getInt(tagAddress); result.getTags().put(tagAddress, tagIndex); } return result; }
// 构造函数 public Line(JSONObject line) { try { lineName = line.getString("lineName"); lineSummary = line.getString("lineSummary"); coverThumbnail = line.getString("coverThumbnail"); mapType = line.getString("mapType"); mapAddress = line.getString("mapAddress"); JSONArray locatArray = line.getJSONArray("locate"); locate[0] = locatArray.getDouble(0); locate[0] = locatArray.getDouble(1); language = line.getString("language"); lineLength = line.getString("lineLength"); JSONArray topicsArray = line.getJSONArray("topics"); for (int i = 0; i < topicsArray.length(); i++) { topics[i] = topicsArray.getString(i); } price = line.getString(price); author = line.getString(author); authorImage = line.getString("authorImage"); authorEmail = line.getString("authorEmail"); authorBio = line.getString("authorBio"); authorType = line.getString("authorType"); keyWords = new ArrayList<String>(); traffics = line.getString("traffics"); cautions = line.getString("cautions"); lineLinks = line.getString("lineLinks"); lineVedio = line.getString("lineVedio"); totalPeople = (float) line.getDouble("totalPeople"); totalScore = (float) line.getDouble("totalScore"); JSONArray stopsArray = line.getJSONArray("stops"); for (int i = 0; i < stopsArray.length(); i++) { stops.add(new Stop(stopsArray.getJSONObject(i))); } } catch (Exception e) { e.printStackTrace(); } }
@Override public Vertex<LongWritable, VertexDataStructure, FloatWritable> getCurrentVertex() throws IOException, InterruptedException { Text line = getRecordReader().getCurrentValue(); Vertex<LongWritable, VertexDataStructure, FloatWritable> vertex = getConf().createVertex(); try { JSONArray jsonVertex = new JSONArray(line.toString()); vertex.initialize( new LongWritable(jsonVertex.getLong(0)), new VertexDataStructure(jsonVertex.getLong(1), new HashSet<Long>())); JSONArray jsonEdgeArray = jsonVertex.getJSONArray(2); for (int i = 0; i < jsonEdgeArray.length(); ++i) { JSONArray jsonEdge = jsonEdgeArray.getJSONArray(i); Edge<LongWritable, FloatWritable> edge = EdgeFactory.create( new LongWritable(jsonEdge.getLong(0)), new FloatWritable((float) jsonEdge.getDouble(1))); vertex.addEdge(edge); } } catch (JSONException e) { throw new IllegalArgumentException("next: Couldn't get vertex from line " + line, e); } return vertex; }
private void DrawTransports(String jsonString, Boolean isCenter) { List<Overlay> mapOverlays = null; MapView mapView = (MapView) findViewById(R.id.mapview); JSONArray array = String2JsonArray(jsonString); if (array != null) { int minLatitude = Integer.MAX_VALUE, minLongitude = Integer.MAX_VALUE; int maxLatitude = Integer.MIN_VALUE, maxLongitude = Integer.MIN_VALUE; EditText et = (EditText) findViewById(R.id.editTextInfo); // TODO: Add show marshruts // et.setText(GetCurrentTime()+". "+String.valueOf(spyMarshrut)+"("+array.length()+")"); Map<String, Integer> infoMap = new HashMap<String, Integer>(); for (int n = 0; n < array.length(); n++) { try { JSONObject jo = array.getJSONObject(n); String info = jo.getString("info"); String marshrutNumber = getTransportNumber(info); if (infoMap.containsKey(marshrutNumber)) { int oldValue = infoMap.get(marshrutNumber); oldValue++; infoMap.put(marshrutNumber, oldValue); } else { infoMap.put(marshrutNumber, 1); } JSONArray coordinatesJsonArray = jo.getJSONArray("cordinate"); int iLatitude, iLongitude; if (coordinatesJsonArray.length() > 1) { iLatitude = (int) (coordinatesJsonArray.getDouble(0) * 1000000); minLatitude = Math.min(minLatitude, iLatitude); maxLatitude = Math.max(minLatitude, iLatitude); iLongitude = (int) (coordinatesJsonArray.getDouble(1) * 1000000); minLongitude = Math.min(minLongitude, iLongitude); maxLongitude = Math.max(minLongitude, iLongitude); String transportNumber = getTransportNumber(info); Drawable drawable; drawable = new TextDrawable(transportNumber); DrawableItemizedOverlay itemizedoverlay = new DrawableItemizedOverlay(drawable, this); GeoPoint point = new GeoPoint(iLatitude, iLongitude); OverlayItem overlayitem = new OverlayItem(point, "Info", info); itemizedoverlay.addOverlay(overlayitem); if (mapOverlays == null) { mapOverlays = mapView.getOverlays(); mapOverlays.clear(); } mapOverlays.add(itemizedoverlay); } } catch (JSONException e) { e.printStackTrace(); } } String s = infoMap.toString(); et.setText(GetCurrentTime() + ". " + s); if (isCenter && minLatitude != Integer.MAX_VALUE) { MapController mapController = mapView.getController(); GeoPoint point = new GeoPoint((minLatitude + maxLatitude) / 2, (minLongitude + maxLongitude) / 2); mapController.animateTo(point); } mapView.invalidate(); } }
public void setParameters() { if (config == null) { read(); } try { JSONArray distribution; minGoToWaitingRoom = new TimeSpan(config.getInt("go_to_waiting_room_min_time_span"), TimeUnit.MINUTES); maxGoToPlatform = new TimeSpan(config.getInt("go_to_platform_max_time_span"), TimeUnit.MINUTES); externalDelayInfoSpan = new TimeSpan(config.getInt("external_delay_info_time_span"), TimeUnit.MINUTES); minCompanionComingTime = new TimeSpan(config.getInt("min_companion_coming_time_span"), TimeUnit.MINUTES); maxCompanionComingTime = new TimeSpan(config.getInt("max_companion_coming_time_span"), TimeUnit.MINUTES); minComingTimeWithTicket = new TimeSpan(config.getInt("min_coming_time_span_with_ticket"), TimeUnit.MINUTES); maxComingTimeWithTicket = new TimeSpan(config.getInt("max_coming_time_span_with_ticket"), TimeUnit.MINUTES); minComingTimeWithoutTicket = new TimeSpan(config.getInt("min_coming_time_span_without_ticket"), TimeUnit.MINUTES); maxComingTimeWithoutTicket = new TimeSpan(config.getInt("max_coming_time_span_without_ticket"), TimeUnit.MINUTES); complainingProbability = config.getInt("average_probability_of_complaining") / 100.0; gettingInformationProbability = config.getInt("average_probability_of_getting_information") / 100.0; buyingTicketProbability = config.getInt("average_probability_of_buying_ticket") / 100.0; externalDelayProbability = config.getInt("average_probability_of_external_delay") / 100.0; distribution = config.getJSONArray("companion_count_distribution"); companionCountDist = new double[distribution.length()]; for (int i = 0; i < distribution.length(); i++) { companionCountDist[i] = Math.max(0, distribution.getDouble(i)); } distribution = config.getJSONArray("visitor_coming_distribution"); visitorComingDist = new int[distribution.length()]; for (int i = 0; i < distribution.length(); i++) { visitorComingDist[i] = Math.max(distribution.getInt(i), 0); } platformCount = config.getInt("platform_count"); infoDeskCount = config.getInt("info_desk_count"); cashDeskCount = config.getInt("cash_desk_count"); waitingRoomCapacity = config.getInt("waiting_room_capacity"); minArrivingPassengerCount = config.getInt("min_arriving_passenger_count"); maxArrivingPassengerCount = config.getInt("max_arriving_passenger_count"); minDeparturingPassengerCount = config.getInt("min_departuring_passenger_count"); maxDeparturingPassengerCount = config.getInt("max_departuring_passenger_count"); internalArrivalDuration = new TimeSpan(config.getInt("internal_arrival_time"), TimeUnit.MINUTES); defaultPlatformWaitingTime = new TimeSpan(config.getInt("default_platform_waiting_time"), TimeUnit.MINUTES); minExternalDelay = new TimeSpan(config.getInt("min_external_delay"), TimeUnit.MINUTES); maxExternalDelay = new TimeSpan(config.getInt("max_external_delay"), TimeUnit.MINUTES); minSellingTicketTime = new TimeSpan(config.getInt("min_selling_ticket_time"), TimeUnit.MINUTES); maxSellingTicketTime = new TimeSpan(config.getInt("max_selling_ticket_time"), TimeUnit.MINUTES); minServingInformationTime = new TimeSpan(config.getInt("min_serving_information_time"), TimeUnit.MINUTES); maxServingInformationTime = new TimeSpan(config.getInt("max_serving_information_time"), TimeUnit.MINUTES); String schedulingAlgoName = config.getString("scheduling_algorithm"); if (schedulingAlgoName.equals("wait")) { schedulingAlgorithm = new WaitSchedulingAlgorithm(); } else if (schedulingAlgoName.equals("random")) { schedulingAlgorithm = new FirstFreeSchedulingAlgorithm(); } } catch (JSONException ex) { System.err.println("error parsing json configuration"); } }
/** * Load a terrain object from a JSON file * * @param mapFile * @return * @throws FileNotFoundException */ public static Terrain load(File mapFile) throws FileNotFoundException { Reader in = new FileReader(mapFile); JSONTokener jtk = new JSONTokener(in); JSONObject jsonTerrain = new JSONObject(jtk); int width = jsonTerrain.getInt("width"); int depth = jsonTerrain.getInt("depth"); Terrain terrain = new Terrain(width, depth); JSONArray jsonSun = jsonTerrain.getJSONArray("sunlight"); float dx = (float) jsonSun.getDouble(0); float dy = (float) jsonSun.getDouble(1); float dz = (float) jsonSun.getDouble(2); terrain.setSunlightDir(dx, dy, dz); JSONArray jsonAltitude = jsonTerrain.getJSONArray("altitude"); for (int i = 0; i < jsonAltitude.length(); i++) { int x = i % width; int z = i / width; double h = jsonAltitude.getDouble(i); terrain.setGridAltitude(x, z, h); } if (jsonTerrain.has("trees")) { JSONArray jsonTrees = jsonTerrain.getJSONArray("trees"); for (int i = 0; i < jsonTrees.length(); i++) { JSONObject jsonTree = jsonTrees.getJSONObject(i); double x = jsonTree.getDouble("x"); double z = jsonTree.getDouble("z"); terrain.addTree(x, z); } } if (jsonTerrain.has("others")) { JSONArray jsonTrees = jsonTerrain.getJSONArray("others"); for (int i = 0; i < jsonTrees.length(); i++) { JSONObject jsonTree = jsonTrees.getJSONObject(i); double x = jsonTree.getDouble("x"); double z = jsonTree.getDouble("z"); terrain.addOther(x, z); } } if (jsonTerrain.has("roads")) { JSONArray jsonRoads = jsonTerrain.getJSONArray("roads"); for (int i = 0; i < jsonRoads.length(); i++) { JSONObject jsonRoad = jsonRoads.getJSONObject(i); double w = jsonRoad.getDouble("width"); JSONArray jsonSpine = jsonRoad.getJSONArray("spine"); double[] spine = new double[jsonSpine.length()]; for (int j = 0; j < jsonSpine.length(); j++) { spine[j] = jsonSpine.getDouble(j); } terrain.addRoad(w, spine); } } return terrain; }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (START_TRACKER.equals(action)) { String id = args.getString(0); this.startTracker(id, callbackContext); return true; } else if (TRACK_VIEW.equals(action)) { String screen = args.getString(0); this.trackView(screen, callbackContext); return true; } else if (TRACK_EVENT.equals(action)) { int length = args.length(); if (length > 0) { this.trackEvent( args.getString(0), length > 1 ? args.getString(1) : "", length > 2 ? args.getString(2) : "", length > 3 ? args.getLong(3) : 0, callbackContext); } return true; } else if (TRACK_EXCEPTION.equals(action)) { String description = args.getString(0); Boolean fatal = args.getBoolean(1); this.trackException(description, fatal, callbackContext); return true; } else if (TRACK_TIMING.equals(action)) { int length = args.length(); if (length > 0) { this.trackTiming( args.getString(0), length > 1 ? args.getLong(1) : 0, length > 2 ? args.getString(2) : "", length > 3 ? args.getString(3) : "", callbackContext); } return true; } else if (ADD_DIMENSION.equals(action)) { Integer key = args.getInt(0); String value = args.getString(1); this.addCustomDimension(key, value, callbackContext); return true; } else if (ADD_TRANSACTION.equals(action)) { int length = args.length(); if (length > 0) { this.addTransaction( args.getString(0), length > 1 ? args.getString(1) : "", length > 2 ? args.getDouble(2) : 0, length > 3 ? args.getDouble(3) : 0, length > 4 ? args.getDouble(4) : 0, length > 5 ? args.getString(5) : null, callbackContext); } return true; } else if (ADD_TRANSACTION_ITEM.equals(action)) { int length = args.length(); if (length > 0) { this.addTransactionItem( args.getString(0), length > 1 ? args.getString(1) : "", length > 2 ? args.getString(2) : "", length > 3 ? args.getString(3) : "", length > 4 ? args.getDouble(4) : 0, length > 5 ? args.getLong(5) : 0, length > 6 ? args.getString(6) : null, callbackContext); } return true; } else if (SET_USER_ID.equals(action)) { String userId = args.getString(0); this.setUserId(userId, callbackContext); } else if (DEBUG_MODE.equals(action)) { this.debugMode(callbackContext); } else if (ENABLE_UNCAUGHT_EXCEPTION_REPORTING.equals(action)) { Boolean enable = args.getBoolean(0); this.enableUncaughtExceptionReporting(enable, callbackContext); } else if (ENABLE_ADVERTISING_ID_COLLECTION.equals(action)) { this.enableAdvertisingIdCollection(callbackContext); } return false; }
/** * Get rows results from query cursor. * * @param cur Cursor into query results * @return results in string form */ private JSONObject executeSqlStatementNDK( String query, JSONArray paramsAsJson, CallbackContext cbc) throws Exception { JSONObject rowsResult = new JSONObject(); boolean hasRows = false; SQLiteStatement myStatement = mydb.prepareStatement(query); try { String[] params = null; params = new String[paramsAsJson.length()]; for (int i = 0; i < paramsAsJson.length(); ++i) { if (paramsAsJson.isNull(i)) { myStatement.bindNull(i + 1); } else { Object p = paramsAsJson.get(i); if (p instanceof Float || p instanceof Double) myStatement.bindDouble(i + 1, paramsAsJson.getDouble(i)); else if (p instanceof Number) myStatement.bindLong(i + 1, paramsAsJson.getLong(i)); else myStatement.bindTextNativeString(i + 1, paramsAsJson.getString(i)); } } hasRows = myStatement.step(); } catch (Exception ex) { ex.printStackTrace(); String errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage); // cleanup statement and throw the exception: myStatement.dispose(); throw ex; } // If query result has rows if (hasRows) { JSONArray rowsArrayResult = new JSONArray(); String key = ""; int colCount = myStatement.getColumnCount(); // Build up JSON result object for each row do { JSONObject row = new JSONObject(); try { for (int i = 0; i < colCount; ++i) { key = myStatement.getColumnName(i); switch (myStatement.getColumnType(i)) { case SQLColumnType.NULL: row.put(key, JSONObject.NULL); break; case SQLColumnType.REAL: row.put(key, myStatement.getColumnDouble(i)); break; case SQLColumnType.INTEGER: row.put(key, myStatement.getColumnLong(i)); break; case SQLColumnType.BLOB: case SQLColumnType.TEXT: default: // (just in case) row.put(key, myStatement.getColumnTextNativeString(i)); } } rowsArrayResult.put(row); } catch (JSONException e) { e.printStackTrace(); } } while (myStatement.step()); try { rowsResult.put("rows", rowsArrayResult); } catch (JSONException e) { e.printStackTrace(); } } myStatement.dispose(); return rowsResult; }
public static Depth formatJsonOfMarketDepth(MarketType marketType, JSONObject json) throws JSONException { Depth depth = new Depth(); double rate = ExchangeUtil.getRate(marketType); int bidMaxPrice = 0; int askMinPrice = Integer.MAX_VALUE; List<DateValueEntity> bidDateValueEntities = new ArrayList<DateValueEntity>(); List<DateValueEntity> askDateValueEntities = new ArrayList<DateValueEntity>(); double bidSumVolume = 0; int splitIndex = 0; if (!json.isNull(BIDS)) { JSONArray bidArray = json.getJSONArray(BIDS); for (int i = bidArray.length() - 1; i >= 0; i--) { JSONArray bid = bidArray.getJSONArray(i); int bidPrice = bid.getInt(0); double price = ((double) bidPrice) / 100 * rate; double volume = bid.getDouble(1) / Math.pow(10, 8); if (bidMaxPrice < bidPrice) { bidMaxPrice = bidPrice; } bidSumVolume = bidSumVolume + volume; DateValueEntity dateValueEntity = new DateValueEntity( (float) bidSumVolume, StringUtil.formatDoubleToMoneyString(price), bidPrice); bidDateValueEntities.add(dateValueEntity); } splitIndex = bidArray.length(); } double askSumVolume = 0; if (!json.isNull(ASKS)) { JSONArray askArray = json.getJSONArray(ASKS); for (int i = 0; i < askArray.length(); i++) { JSONArray ask = askArray.getJSONArray(i); int askPrice = ask.getInt(0); double price = ((double) askPrice) / 100 * rate; double volume = ask.getDouble(1) / Math.pow(10, 8); askSumVolume = askSumVolume + volume; if (askPrice < askMinPrice) { askMinPrice = askPrice; } DateValueEntity dateValueEntity = new DateValueEntity( (float) askSumVolume, StringUtil.formatDoubleToMoneyString(price), askPrice); askDateValueEntities.add(dateValueEntity); } } int mixPrice = (askMinPrice + bidMaxPrice) / 2; DateValueEntity zeroDateValue = new DateValueEntity( 0, StringUtil.formatDoubleToMoneyString(((double) mixPrice) / 100 * rate), mixPrice); List<DateValueEntity> dateValueEntities = new ArrayList<DateValueEntity>(); dateValueEntities.addAll(bidDateValueEntities); dateValueEntities.add(zeroDateValue); dateValueEntities.addAll(askDateValueEntities); Collections.sort(dateValueEntities, new ComparatorDateValue()); depth.setMaxVolume(Math.max(askSumVolume, bidSumVolume)); depth.setDateValueEntities(dateValueEntities); depth.setSplitIndex(splitIndex); return depth; }
@Override public ContentValues fromJSON(Context context, Uri localItem, JSONObject item, String lProp) throws JSONException, NetworkProtocolException, IOException { final ContentValues cv = new ContentValues(); switch (getType()) { case SyncFieldMap.STRING: cv.put(lProp, item.getString(remoteKey)); break; case SyncFieldMap.INTEGER: cv.put(lProp, item.getInt(remoteKey)); break; case SyncFieldMap.DOUBLE: cv.put(lProp, item.getDouble(remoteKey)); break; case SyncFieldMap.BOOLEAN: cv.put(lProp, item.getBoolean(remoteKey)); break; case SyncFieldMap.LIST_INTEGER: case SyncFieldMap.LIST_STRING: case SyncFieldMap.LIST_DOUBLE: { final JSONArray ar = item.getJSONArray(remoteKey); final List<String> l = new Vector<String>(ar.length()); for (int i = 0; i < ar.length(); i++) { switch (getType()) { case SyncFieldMap.LIST_STRING: l.add(ar.getString(i)); break; case SyncFieldMap.LIST_DOUBLE: l.add(String.valueOf(ar.getDouble(i))); break; case SyncFieldMap.LIST_INTEGER: l.add(String.valueOf(ar.getInt(i))); break; } } cv.put(lProp, TextUtils.join(LIST_DELIM, l)); } break; case SyncFieldMap.DATE: try { cv.put(lProp, NetworkClient.parseDate(item.getString(remoteKey)).getTime()); } catch (final ParseException e) { final NetworkProtocolException ne = new NetworkProtocolException("bad date format"); ne.initCause(e); throw ne; } break; case SyncFieldMap.DURATION: { final Matcher m = durationPattern.matcher(item.getString(remoteKey)); if (!m.matches()) { throw new NetworkProtocolException("bad duration format"); } final int durationSeconds = 1200 * Integer.parseInt(m.group(1)) + 60 * Integer.parseInt(m.group(2)) + Integer.parseInt(m.group(3)); cv.put(lProp, durationSeconds); } break; } return cv; }
public int loadStream() throws YAPI_Exception { JSONArray coldiv = null; int coltyp[] = null; double colscl[]; int colofs[]; JSONObject jsonObj = null; try { JSONTokener jsonTokenner = _dataLogger.getData(_runNo, _timeStamp); jsonObj = new JSONObject(jsonTokenner); if (jsonObj.has("time")) { _timeStamp = jsonObj.getInt("time"); } if (jsonObj.has("UTC")) { _utcStamp = jsonObj.getLong("UTC"); } if (jsonObj.has("interval")) { _interval = jsonObj.getInt("interval"); } if (jsonObj.has("nRows")) { _nRows = jsonObj.getInt("nRows"); } if (jsonObj.has("keys")) { JSONArray jsonKeys = jsonObj.getJSONArray("keys"); if (_nCols == 0) { _nCols = jsonKeys.length(); } else if (_nCols != jsonKeys.length()) { _nCols = 0; throw new YAPI_Exception(YAPI.IO_ERROR, "DataStream corrupted"); } _columnNames = new ArrayList<String>(_nCols); for (int i = 0; i < jsonKeys.length(); i++) { _columnNames.add(jsonKeys.getString(i)); } } if (jsonObj.has("div")) { coldiv = jsonObj.getJSONArray("div"); if (_nCols == 0) { _nCols = coldiv.length(); } else if (_nCols != coldiv.length()) { _nCols = 0; throw new YAPI_Exception(YAPI.IO_ERROR, "DataStream corrupted"); } } if (jsonObj.has("type")) { JSONArray types = jsonObj.getJSONArray("type"); if (_nCols == 0) { _nCols = types.length(); } else if (_nCols != types.length()) { _nCols = 0; throw new YAPI_Exception(YAPI.IO_ERROR, "DataStream corrupted"); } coltyp = new int[_nCols]; for (int c = 0; c < _nCols; c++) { coltyp[c] = types.getInt(c); } } if (jsonObj.has("scal")) { JSONArray json_colscl = jsonObj.getJSONArray("scal"); if (_nCols == 0) { _nCols = json_colscl.length(); } else if (_nCols != json_colscl.length()) { _nCols = 0; throw new YAPI_Exception(YAPI.IO_ERROR, "DataStream corrupted"); } colscl = new double[json_colscl.length()]; colofs = new int[json_colscl.length()]; for (int i = 0; i < json_colscl.length(); i++) { double dval = json_colscl.getDouble(i); colscl[i] = dval / 65536.0; colofs[i] = (coltyp[i] != 0 ? -32767 : 0); } } else { colscl = new double[coldiv.length()]; colofs = new int[coldiv.length()]; for (int i = 0; i < coldiv.length(); i++) { colscl[i] = 1.0 / coldiv.getDouble(i); colofs[i] = (coltyp[i] != 0 ? -32767 : 0); } } } catch (JSONException ex) { throw new YAPI_Exception(YAPI.IO_ERROR, "json parse error"); } if (jsonObj != null && jsonObj.has("data")) { if (_nCols == 0 || coldiv == null || coltyp == null) { throw new YAPI_Exception(YAPI.IO_ERROR, "DataStream corrupted"); } ArrayList<Integer> udata = null; try { String data = jsonObj.getString("data"); udata = YAPI._decodeWords(data); } catch (JSONException ignore) { } if (udata == null) { try { JSONArray jsonData = jsonObj.getJSONArray("data"); udata = new ArrayList<Integer>(); for (int i = 0; i < jsonData.length(); i++) { udata.add(jsonData.getInt(i)); } } catch (JSONException ex) { throw new YAPI_Exception(YAPI.IO_ERROR, ""); } } _values = new ArrayList<ArrayList<Double>>(); ArrayList<Double> dat = new ArrayList<Double>(); int c = 0; for (int val_i : udata) { double val_d; if (coltyp[c] < 2) { val_d = (val_i + colofs[c]) * colscl[c]; } else { val_d = YAPI._decimalToDouble(val_i - 32767); } dat.add(val_d); c++; if (c == _nCols) { _values.add(dat); dat = new ArrayList<Double>(); c = 0; } } } return YAPI.SUCCESS; }
private void deserializeKey(String key, Bundle bundle) throws JSONException { String jsonString = cache.getString(key, "{}"); JSONObject json = new JSONObject(jsonString); String valueType = json.getString(JSON_VALUE_TYPE); if (valueType.equals(TYPE_BOOLEAN)) { bundle.putBoolean(key, json.getBoolean(JSON_VALUE)); } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); boolean[] array = new boolean[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getBoolean(i); } bundle.putBooleanArray(key, array); } else if (valueType.equals(TYPE_BYTE)) { bundle.putByte(key, (byte) json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_BYTE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); byte[] array = new byte[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (byte) jsonArray.getInt(i); } bundle.putByteArray(key, array); } else if (valueType.equals(TYPE_SHORT)) { bundle.putShort(key, (short) json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_SHORT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); short[] array = new short[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (short) jsonArray.getInt(i); } bundle.putShortArray(key, array); } else if (valueType.equals(TYPE_INTEGER)) { bundle.putInt(key, json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_INTEGER_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int[] array = new int[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getInt(i); } bundle.putIntArray(key, array); } else if (valueType.equals(TYPE_LONG)) { bundle.putLong(key, json.getLong(JSON_VALUE)); } else if (valueType.equals(TYPE_LONG_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); long[] array = new long[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getLong(i); } bundle.putLongArray(key, array); } else if (valueType.equals(TYPE_FLOAT)) { bundle.putFloat(key, (float) json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_FLOAT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); float[] array = new float[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (float) jsonArray.getDouble(i); } bundle.putFloatArray(key, array); } else if (valueType.equals(TYPE_DOUBLE)) { bundle.putDouble(key, json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); double[] array = new double[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getDouble(i); } bundle.putDoubleArray(key, array); } else if (valueType.equals(TYPE_CHAR)) { String charString = json.getString(JSON_VALUE); if (charString != null && charString.length() == 1) { bundle.putChar(key, charString.charAt(0)); } } else if (valueType.equals(TYPE_CHAR_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); char[] array = new char[jsonArray.length()]; for (int i = 0; i < array.length; i++) { String charString = jsonArray.getString(i); if (charString != null && charString.length() == 1) { array[i] = charString.charAt(0); } } bundle.putCharArray(key, array); } else if (valueType.equals(TYPE_STRING)) { bundle.putString(key, json.getString(JSON_VALUE)); } else if (valueType.equals(TYPE_STRING_LIST)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int numStrings = jsonArray.length(); ArrayList<String> stringList = new ArrayList<String>(numStrings); for (int i = 0; i < numStrings; i++) { Object jsonStringValue = jsonArray.get(i); stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue); } bundle.putStringArrayList(key, stringList); } else if (valueType.equals(TYPE_ENUM)) { try { String enumType = json.getString(JSON_VALUE_ENUM_TYPE); @SuppressWarnings({"unchecked", "rawtypes"}) Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType); @SuppressWarnings("unchecked") Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE)); bundle.putSerializable(key, enumValue); } catch (ClassNotFoundException e) { } catch (IllegalArgumentException e) { } } }