Example usage for org.json JSONObject getDouble

List of usage examples for org.json JSONObject getDouble

Introduction

In this page you can find the example usage for org.json JSONObject getDouble.

Prototype

public double getDouble(String key) throws JSONException 

Source Link

Document

Get the double value associated with a key.

Usage

From source file:gr.cti.android.experimentation.controller.api.RestApiDataController.java

private JSONObject getExperimentHourlyData(final String experiment, final int deviceId, final String after,
        final String to, final int accuracy) {
    final String format = getFormat(accuracy);
    final DecimalFormat df = new DecimalFormat(format);
    final long start = parseDateMillis(after);
    final long end = parseDateMillis(to);

    final Set<Result> results;
    if (deviceId == 0) {
        results = resultRepository.findByExperimentIdAndTimestampAfter(Integer.parseInt(experiment), start);
    } else {/*from w  w w  .j a  v a 2 s.co m*/
        results = resultRepository.findByExperimentIdAndDeviceIdAndTimestampAfterOrderByTimestampAsc(
                Integer.parseInt(experiment), deviceId, start);
    }

    try {
        final Map<Integer, Map<String, Map<String, Map<String, DescriptiveStatistics>>>> dataAggregates = new HashMap<>();
        String longitude;
        String latitude;
        final DescriptiveStatistics wholeDataStatistics = new DescriptiveStatistics();
        final Map<Integer, Map<String, Map<String, Long>>> locationsHeatMap = new HashMap<>();
        for (final Result result : results) {
            try {
                if (!result.getMessage().startsWith("{")) {
                    continue;
                }
                if (end != 0 && result.getTimestamp() > end) {
                    continue;
                }
                final JSONObject message = new JSONObject(result.getMessage());

                int hour = new DateTime(result.getTimestamp()).getHourOfDay();

                if (message.has(LATITUDE) && message.has(LONGITUDE)) {
                    longitude = df.format(message.getDouble(LONGITUDE));
                    latitude = df.format(message.getDouble(LATITUDE));
                    if (!dataAggregates.containsKey(hour)) {
                        dataAggregates.put(hour, new HashMap<>());
                    }
                    if (!dataAggregates.get(hour).containsKey(longitude)) {
                        dataAggregates.get(hour).put(longitude, new HashMap<>());
                    }
                    if (!dataAggregates.get(hour).get(longitude).containsKey(latitude)) {
                        dataAggregates.get(hour).get(longitude).put(latitude, new HashMap<>());
                    }

                    //HeatMap
                    if (!locationsHeatMap.containsKey(hour)) {
                        locationsHeatMap.put(hour, new HashMap<>());
                    }
                    if (!locationsHeatMap.get(hour).containsKey(longitude)) {
                        locationsHeatMap.get(hour).put(longitude, new HashMap<>());
                    }
                    if (!locationsHeatMap.get(hour).get(longitude).containsKey(latitude)) {
                        locationsHeatMap.get(hour).get(longitude).put(latitude, 0L);
                    }

                    final Long val = locationsHeatMap.get(hour).get(longitude).get(latitude);
                    locationsHeatMap.get(hour).get(longitude).put(latitude, val + 1);

                    final Iterator iterator = message.keys();
                    if (longitude != null && latitude != null) {
                        while (iterator.hasNext()) {
                            final String key = (String) iterator.next();
                            if (key.equals(LATITUDE) || key.equals(LONGITUDE)) {
                                continue;
                            }

                            if (!dataAggregates.get(hour).get(longitude).get(latitude).containsKey(key)) {
                                dataAggregates.get(hour).get(longitude).get(latitude).put(key,
                                        new DescriptiveStatistics());
                            }
                            try {
                                String data = message.getString(key);
                                try {
                                    final double doubleData = Double.parseDouble(data);
                                    dataAggregates.get(hour).get(longitude).get(latitude).get(key)
                                            .addValue(doubleData);
                                    wholeDataStatistics.addValue(doubleData);
                                } catch (NumberFormatException ignore) {
                                    dataAggregates.get(hour).get(longitude).get(latitude).get(key).addValue(1);
                                    wholeDataStatistics.addValue(1);
                                }
                            } catch (Exception e) {
                                LOGGER.error(e, e);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.error(e, e);
            }
        }
        final JSONObject hourlyPoints = new JSONObject();
        for (final Integer hour : dataAggregates.keySet()) {
            final JSONArray addressPoints = new JSONArray();
            for (final String longit : dataAggregates.get(hour).keySet()) {
                for (final String latit : dataAggregates.get(hour).get(longit).keySet()) {
                    LOGGER.info("{" + longit + ":" + latit + "}");
                    final JSONArray measurement = new JSONArray();
                    try {
                        measurement.put(Double.parseDouble(latit));
                        measurement.put(Double.parseDouble(longit));
                        if (locationsHeatMap.containsKey(hour) && locationsHeatMap.get(hour).containsKey(longit)
                                && locationsHeatMap.get(hour).get(longit).containsKey(latit)) {
                            measurement.put(locationsHeatMap.get(hour).get(longit).get(latit));
                        } else {
                            measurement.put(0);
                        }
                        final JSONObject data = new JSONObject();
                        measurement.put(data);
                        for (final Object key : dataAggregates.get(hour).get(longit).get(latit).keySet()) {
                            final String keyString = (String) key;
                            final String part = keyString.split("\\.")[keyString.split("\\.").length - 1];
                            double value = dataAggregates.get(hour).get(longit).get(latit).get(keyString)
                                    .getMean();
                            LOGGER.info("value: " + value);
                            if (Double.isFinite(value) && value != 1) {
                                data.put(part, value);
                            } else {
                                value = dataAggregates.get(hour).get(longit).get(latit).get(keyString)
                                        .getValues().length;
                                data.put(part, value);
                            }
                        }
                        addressPoints.put(measurement);
                    } catch (JSONException e) {
                        LOGGER.error(e, e);
                    }
                }
            }
            try {
                hourlyPoints.put(String.valueOf(hour), addressPoints);
            } catch (JSONException e) {
                LOGGER.error(e, e);
            }
        }
        LOGGER.info(hourlyPoints.toString());
        return hourlyPoints;
    } catch (Exception e) {
        LOGGER.error(e, e);
    }
    return null;

}

From source file:gr.cti.android.experimentation.controller.api.RestApiDataController.java

private JSONArray doCalculations(final Set<Result> results, final long end, final DecimalFormat df) {
    final Map<String, Map<String, Map<String, DescriptiveStatistics>>> dataAggregates = new HashMap<>();
    final DescriptiveStatistics wholeDataStatistics = new DescriptiveStatistics();
    final Map<String, Map<String, Long>> locationsHeatMap = new HashMap<>();

    for (final Result result : results) {
        try {// w  w  w  . j  av a2 s.  co m
            if (!result.getMessage().startsWith("{")) {
                continue;
            }
            if (end != 0 && result.getTimestamp() > end) {
                continue;
            }

            final JSONObject message = new JSONObject(result.getMessage());

            if (message.has(LATITUDE) && message.has(LONGITUDE)) {
                final String longitude = df.format(message.getDouble(LONGITUDE));
                final String latitude = df.format(message.getDouble(LATITUDE));
                if (!dataAggregates.containsKey(longitude)) {
                    dataAggregates.put(longitude, new HashMap<>());
                }
                if (!dataAggregates.get(longitude).containsKey(latitude)) {
                    dataAggregates.get(longitude).put(latitude, new HashMap<>());
                }

                //HeatMap
                if (!locationsHeatMap.containsKey(longitude)) {
                    locationsHeatMap.put(longitude, new HashMap<>());
                }
                if (!locationsHeatMap.get(longitude).containsKey(latitude)) {
                    locationsHeatMap.get(longitude).put(latitude, 0L);
                }
                final Long val = locationsHeatMap.get(longitude).get(latitude);
                locationsHeatMap.get(longitude).put(latitude, val + 1);

                final Iterator iterator = message.keys();
                if (longitude != null && latitude != null) {
                    while (iterator.hasNext()) {
                        final String key = (String) iterator.next();
                        if (key.equals(LATITUDE) || key.equals(LONGITUDE)) {
                            continue;
                        }

                        if (!dataAggregates.get(longitude).get(latitude).containsKey(key)) {
                            dataAggregates.get(longitude).get(latitude).put(key, new DescriptiveStatistics());
                        }
                        try {
                            String data = message.getString(key);
                            try {
                                final double doubleData = Double.parseDouble(data);
                                dataAggregates.get(longitude).get(latitude).get(key).addValue(doubleData);
                                wholeDataStatistics.addValue(doubleData);
                            } catch (NumberFormatException ignore) {
                                dataAggregates.get(longitude).get(latitude).get(key).addValue(1);
                                wholeDataStatistics.addValue(1);
                            }
                        } catch (Exception e) {
                            LOGGER.error(e, e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error(e, e);
        }
    }

    final JSONArray addressPoints = new JSONArray();
    for (final String longitude : dataAggregates.keySet()) {
        for (final String latitude : dataAggregates.get(longitude).keySet()) {
            LOGGER.info("{" + longitude + ":" + latitude + "}");
            final JSONArray measurement = new JSONArray();
            try {
                measurement.put(Double.parseDouble(latitude));
                measurement.put(Double.parseDouble(longitude));
                if (locationsHeatMap.containsKey(longitude)
                        && locationsHeatMap.get(longitude).containsKey(latitude)) {
                    measurement.put(String.valueOf(locationsHeatMap.get(longitude).get(latitude)));
                } else {
                    measurement.put(1);
                }
                final JSONObject data = new JSONObject();
                measurement.put(data);
                for (final Object key : dataAggregates.get(longitude).get(latitude).keySet()) {
                    final String keyString = (String) key;
                    final String part = keyString.split("\\.")[keyString.split("\\.").length - 1];
                    double value = dataAggregates.get(longitude).get(latitude).get(keyString).getMean();
                    LOGGER.info("value: " + value);
                    if (Double.isFinite(value) && value != 1) {
                        data.put(part, value);
                    } else {
                        value = dataAggregates.get(longitude).get(latitude).get(keyString).getValues().length;
                        data.put(part, value);
                    }
                }
                addressPoints.put(measurement);
            } catch (JSONException e) {
                LOGGER.error(e, e);
            }
        }
    }
    return addressPoints;
}

From source file:de.onelogic.android.weatherdemo.WeatherActivity.java

private void updateView(JSONObject jsonObject) {
    JSONObject main;
    try {//from w  ww  .  j  av a2s.  c  o m
        main = jsonObject.getJSONObject("main");
        JSONObject weather = jsonObject.getJSONArray("weather").getJSONObject(0);
        JSONObject wind = jsonObject.getJSONObject("wind");
        JSONObject clouds = jsonObject.getJSONObject("clouds");

        // retrieve the weather information (temperature, wind speed, etc.) from the JSON objects
        String weatherDescription = weather.getString("description");
        double temperature = main.getDouble("temp");
        int humidity = main.getInt("humidity");
        double windSpeed = wind.getDouble("speed");
        double windDegree = wind.getDouble("deg");
        int cloudiness = clouds.getInt("all");

        // set the values to the GUI
        textViewTemperature.setText(String.valueOf(Math.round(temperature)) + "C");
        textViewDescription.setText(weatherDescription);
        textViewWind.setText(String.valueOf(windSpeed + " km/h " + getWindDirection(windDegree)));
        textViewCloudiness.setText(String.valueOf(cloudiness) + " %");
        textViewHumidity.setText(String.valueOf(humidity) + " %");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:a122016.rr.com.alertme.QueryUtils.java

/**
 * Return a {@link Place} object that has been built up from
 * parsing the given JSON response./*from  ww w  . j av a 2 s .  c  om*/
 */
private static ArrayList<Place> extractFeatureFromJson(String PlacesJSON) {

    // If the JSON string is empty or null, then return early.
    if (TextUtils.isEmpty(PlacesJSON)) {
        return null;
    }

    // Create an array list of Places
    ArrayList<Place> placesList = new ArrayList<Place>();

    // Try to parse the JSON response string. If there's a problem with the way the JSON
    // is formatted, a JSONException exception object will be thrown.
    // Catch the exception so the app doesn't crash, and print the error message to the logs.
    try {

        // Create a JSONArray from the JSON response string
        JSONArray placeArray = new JSONArray(PlacesJSON);

        // For each place in the placeArray, create an {@link place} object
        for (int i = 0; i < placeArray.length(); i++) {

            // Get a single place at position i within the list of places
            JSONObject currentPlace = placeArray.getJSONObject(i);

            // Extract the value for the key called "PLACE OF ACCIDENT"
            String location = currentPlace.getString("PLACE OF ACCIDENT");

            // Extract the value for the key called "NH/SH/MDR/OTHER"
            String highwayNumber = currentPlace.getString("NH/SH/MDR/OTHER");

            // Extract the value for the key called "FATALITIES IN 2015"
            int fatalities2015 = currentPlace.getInt("FATALITIES IN 2015");

            // Extract the value for the key called "FATALITIES IN 2016"
            int fatalities2016 = currentPlace.getInt("FATALITIES IN 2016");

            // Extract the value for the key called "CAUSE OF ACCIDENT"
            String causeOfAccident = currentPlace.getString("CAUSE OF ACCIDENT");

            double latitude = currentPlace.getDouble("LATITUDE");
            double longitude = currentPlace.getDouble("LONGITUDE");

            // Create a new {@link place} object
            Place place = new Place(location, highwayNumber, fatalities2015, fatalities2016, causeOfAccident,
                    latitude, longitude);

            // Add the new {@link place} to the list of places.
            placesList.add(place);
        }

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing the Places JSON results", e);
    }

    // Return the array list
    return placesList;
}

From source file:com.saarang.samples.apps.iosched.ui.ExpertsDirectoryActivity.java

private void processJSON(String uname) {
    JSONArray theArray = null;/*  w  w w  .jav a2  s.c om*/
    try {

        JSONObject jObj;
        jObj = new JSONObject(uname);

        theArray = jObj.getJSONArray("data");

    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (true) {
        final String id[] = new String[theArray.length()];
        final double priority[] = new double[theArray.length()];
        final String tittle[] = new String[theArray.length()];

        final String logolink[] = new String[theArray.length()];

        final String link[] = new String[theArray.length()];

        try {
            for (int i = 0; i < theArray.length(); i++) {
                JSONObject jsonInside = theArray.getJSONObject(i);
                id[i] = jsonInside.getString("id");
                priority[i] = jsonInside.getDouble("priority");
                tittle[i] = jsonInside.getString("title");
                logolink[i] = jsonInside.getString("logo");
                link[i] = jsonInside.getString("sponsor_link");

            }
            int input = theArray.length();

            for (int index = 0; index < input; index++) {
                for (int index1 = 0; index1 < input - 1; index1++) {
                    if (priority[index1] > priority[index1 + 1]) {

                        double temp_prio = priority[index1];
                        String temp_logolink = logolink[index1];
                        String temp_title = tittle[index1];
                        String temp_link = link[index1];
                        priority[index1] = priority[index1 + 1];
                        logolink[index1] = logolink[index1 + 1];
                        tittle[index1] = tittle[index1 + 1];
                        link[index1] = link[index1 + 1];

                        priority[index1 + 1] = temp_prio;
                        logolink[index1 + 1] = temp_logolink;
                        tittle[index1 + 1] = temp_title;
                        link[index1 + 1] = temp_link;

                    }
                }
            }
            for (int i = 0; i < logolink.length / 2; i++) {
                String temp = logolink[i];
                logolink[i] = logolink[logolink.length - 1 - i];
                logolink[logolink.length - 1 - i] = temp;
            }
            for (int i = 0; i < tittle.length / 2; i++) {
                String temp = tittle[i];
                tittle[i] = tittle[tittle.length - 1 - i];
                tittle[tittle.length - 1 - i] = temp;
            }
            for (int i = 0; i < link.length / 2; i++) {
                String temp = link[i];
                link[i] = link[link.length - 1 - i];
                link[link.length - 1 - i] = temp;
            }

            for (int i = 0; i < input; i++) {
                Log.d("", String.valueOf(priority[i]));

            }

            SponsorsList adapter = new SponsorsList(ExpertsDirectoryActivity.this, id, tittle, logolink, link);
            ListView list = (ListView) findViewById(R.id.listview);
            list.setAdapter(adapter);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long useless_id) {

                    String url = link[position];

                    Uri webpage = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivity(intent);
                    }

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

From source file:com.facebook.internal.BundleJSONConverterTests.java

@SmallTest
public void testSimpleValues() throws JSONException {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1st");
    arrayList.add("2nd");
    arrayList.add("third");

    Bundle innerBundle1 = new Bundle();
    innerBundle1.putInt("inner", 1);

    Bundle innerBundle2 = new Bundle();
    innerBundle2.putString("inner", "2");
    innerBundle2.putStringArray("deep list", new String[] { "7", "8" });

    innerBundle1.putBundle("nested bundle", innerBundle2);

    Bundle b = new Bundle();
    b.putBoolean("boolValue", true);
    b.putInt("intValue", 7);
    b.putLong("longValue", 5000000000l);
    b.putDouble("doubleValue", 3.14);
    b.putString("stringValue", "hello world");
    b.putStringArray("stringArrayValue", new String[] { "first", "second" });
    b.putStringArrayList("stringArrayListValue", arrayList);
    b.putBundle("nested", innerBundle1);

    JSONObject json = BundleJSONConverter.convertToJSON(b);
    assertNotNull(json);//from   w w  w.  ja  va  2 s.  c o  m

    assertEquals(true, json.getBoolean("boolValue"));
    assertEquals(7, json.getInt("intValue"));
    assertEquals(5000000000l, json.getLong("longValue"));
    assertEquals(3.14, json.getDouble("doubleValue"));
    assertEquals("hello world", json.getString("stringValue"));

    JSONArray jsonArray = json.getJSONArray("stringArrayValue");
    assertEquals(2, jsonArray.length());
    assertEquals("first", jsonArray.getString(0));
    assertEquals("second", jsonArray.getString(1));

    jsonArray = json.getJSONArray("stringArrayListValue");
    assertEquals(3, jsonArray.length());
    assertEquals("1st", jsonArray.getString(0));
    assertEquals("2nd", jsonArray.getString(1));
    assertEquals("third", jsonArray.getString(2));

    JSONObject innerJson = json.getJSONObject("nested");
    assertEquals(1, innerJson.getInt("inner"));
    innerJson = innerJson.getJSONObject("nested bundle");
    assertEquals("2", innerJson.getString("inner"));

    jsonArray = innerJson.getJSONArray("deep list");
    assertEquals(2, jsonArray.length());
    assertEquals("7", jsonArray.getString(0));
    assertEquals("8", jsonArray.getString(1));

    Bundle finalBundle = BundleJSONConverter.convertToBundle(json);
    assertNotNull(finalBundle);

    assertEquals(true, finalBundle.getBoolean("boolValue"));
    assertEquals(7, finalBundle.getInt("intValue"));
    assertEquals(5000000000l, finalBundle.getLong("longValue"));
    assertEquals(3.14, finalBundle.getDouble("doubleValue"));
    assertEquals("hello world", finalBundle.getString("stringValue"));

    List<String> stringList = finalBundle.getStringArrayList("stringArrayValue");
    assertEquals(2, stringList.size());
    assertEquals("first", stringList.get(0));
    assertEquals("second", stringList.get(1));

    stringList = finalBundle.getStringArrayList("stringArrayListValue");
    assertEquals(3, stringList.size());
    assertEquals("1st", stringList.get(0));
    assertEquals("2nd", stringList.get(1));
    assertEquals("third", stringList.get(2));

    Bundle finalInnerBundle = finalBundle.getBundle("nested");
    assertEquals(1, finalInnerBundle.getInt("inner"));
    finalBundle = finalInnerBundle.getBundle("nested bundle");
    assertEquals("2", finalBundle.getString("inner"));

    stringList = finalBundle.getStringArrayList("deep list");
    assertEquals(2, stringList.size());
    assertEquals("7", stringList.get(0));
    assertEquals("8", stringList.get(1));
}

From source file:edu.usf.cutr.gtfs_realtime.bullrunner.GtfsRealtimeProviderImpl.java

/**
 * This method downloads the latest vehicle data, processes each vehicle in
 * turn, and create a GTFS-realtime feed of trip updates and vehicle
 * positions as a result.//  w w w . j a  v a 2s.co  m
 */
private void refreshTripVehicle() throws IOException, JSONException {

    Pair pair = downloadVehicleDetails();
    JSONArray stopIDsArray = pair.getArray1();
    JSONArray vehicleArray = pair.getArray2();

    if (stopIDsArray.length() == 0) {
        routeVehicleStartTimeMap.clear();
    }
    Calendar cal = Calendar.getInstance();
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
    String serviceID = _providerConfig.serviceIds[dayOfWeek];

    GtfsRealtimeFullUpdate tripUpdates = new GtfsRealtimeFullUpdate();
    GtfsRealtimeFullUpdate vehiclePositions = new GtfsRealtimeFullUpdate();

    VehicleDescriptor.Builder vehicleDescriptor = null;
    String route, trip;
    int entity = 0;
    int vehicleFeedID = 0;
    String stopId = "";
    String startTime = "";
    String stopSeq;
    long predictTime = 0;
    TripUpdate.Builder tripUpdate = null;
    TripDescriptor.Builder tripDescriptor = null;

    List<TripUpdate.Builder> tripUpdateArr = new ArrayList<>();
    List<stopTimeUpdateRecord> records = new ArrayList<stopTimeUpdateRecord>();
    routeVehiDirMap = new BiHashMap<String, String, Float>();
    tripVehicleInfoMap = new BiHashMap<String, String, vehicleInfo>();
    BiHashMap<String, String, TripUpdate.Builder> tripUpdateMap = new BiHashMap<String, String, TripUpdate.Builder>();

    for (int i = 0; i < stopIDsArray.length(); i++) {
        JSONObject obj = stopIDsArray.getJSONObject(i);
        route = obj.getString("route").substring(6);
        trip = _providerConfig.tripIDMap.get(route, serviceID);
        if (trip.equals("") || trip == null)
            _log.error("Route " + route + "dosn't exit in GTFS file");
        int stopId_int = obj.getInt("stop");
        stopId = Integer.toString(stopId_int);
        JSONArray childArray = obj.getJSONArray("Ptimes");

        for (int j = 0; j < childArray.length(); j++) {

            JSONObject child = childArray.getJSONObject(j);
            String predTimeStamp = child.getString("PredictionTime");
            predictTime = convertTime(predTimeStamp);
            String vehicleId = child.getString("VehicleId");

            if (!tripUpdateMap.containsKey(route, vehicleId)) {
                tripUpdate = TripUpdate.newBuilder();
                vehicleDescriptor = VehicleDescriptor.newBuilder();
                vehicleDescriptor.setId(vehicleId);
                tripDescriptor = TripDescriptor.newBuilder();
                tripDescriptor.setRouteId(route);
                tripDescriptor.setTripId(trip);
                tripUpdate.setVehicle(vehicleDescriptor);
                tripUpdate.setTrip(tripDescriptor);
                tripUpdateMap.put(route, vehicleId, tripUpdate);
                tripUpdateArr.add(tripUpdate);
            } else {
                tripUpdate = tripUpdateMap.get(route, vehicleId);
            }

            StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder();
            arrival.setTime(predictTime);
            StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder();
            stopTimeUpdate.setArrival(arrival);
            stopTimeUpdate.setStopId(stopId);

            stopSeq = _providerConfig.stopSeqIDMap.get(trip, stopId);
            if (stopSeq == null) {
                stopSeq = "0";
                _log.warn("Error stopID: " + stopId + " is not available in GTFS files");
                System.out.println("Error: stopID: " + stopId + " is not available in GTFS files");
            }

            if (stopSeq.equals("1")) {
                startTime = convert2FormattedTime(predTimeStamp);
                //System.out.println("stopSeq =1,  route "+ route+ ", vehicleID = "+ vehicleId);
                tripDescriptor.setStartTime(startTime);
                tripDescriptor.setScheduleRelationship(ScheduleRelationship.UNSCHEDULED);
                tripUpdate.setTrip(tripDescriptor);

                if (routeVehicleStartTimeMap.containsKeys(route, vehicleId)) {
                    StartTimes startTimes = routeVehicleStartTimeMap.get(route, vehicleId);
                    startTimes.previousStartT = startTimes.currentStartT;
                    startTimes.currentStartT = startTime;
                } else {
                    StartTimes startTInstance = new StartTimes(startTime, "0");
                    routeVehicleStartTimeMap.put(route, vehicleId, startTInstance);
                }
                //System.out.println("current starttime = "+ tripUpdate.getTrip().getStartTime());
            }
            stopTimeUpdate.setStopSequence(Integer.parseInt(stopSeq));
            records.add(new stopTimeUpdateRecord(tripUpdate, stopTimeUpdate));
            //tripUpdate.addStopTimeUpdate(stopTimeUpdate);                     
        }
    }
    Collections.sort(records);

    for (int i = 0; i < records.size(); i++) {
        records.get(i).tripUpdate.addStopTimeUpdate(records.get(i).stopTimeUpdate);
    }

    /**
     * Create a new feed entity to wrap the trip update and add it
     * to the GTFS-realtime trip updates feed.
     */

    for (int j = 0; j < tripUpdateArr.size(); j++) {
        FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder();
        tripUpdate = tripUpdateArr.get(j);
        //System.out.println("-----size of trip Updates = " + tripUpdate.getStopTimeUpdateList().size());

        int noStopTimes = tripUpdate.getStopTimeUpdateList().size();
        route = tripUpdate.getTrip().getRouteId();
        trip = tripUpdate.getTrip().getTripId();
        String vehicleId = tripUpdate.getVehicle().getId();

        if (tripUpdate.getStopTimeUpdate(0).getStopSequence() != 1) {
            StartTimes startTInstance;
            if (routeVehicleStartTimeMap.containsKeys(route, vehicleId)) {
                startTInstance = routeVehicleStartTimeMap.get(route, vehicleId);
            } else {
                //cold start
                startTInstance = new StartTimes("0", "0");
                routeVehicleStartTimeMap.put(route, vehicleId, startTInstance);
            }

            TripDescriptor.Builder newTripDescriptor = TripDescriptor.newBuilder();
            newTripDescriptor.setTripId(trip);
            newTripDescriptor.setRouteId(route);
            newTripDescriptor.setStartTime(startTInstance.currentStartT);
            newTripDescriptor.setScheduleRelationship(ScheduleRelationship.UNSCHEDULED);
            tripUpdate.setTrip(newTripDescriptor);

        }
        //         System.out.println("responseTimeStamp: "+ responseTimeStamp + "change it to unix: "+ responseTimeStamp); 
        int delay;
        long preTime = 0;
        for (int h = 0; h < noStopTimes; h++) {
            long timeStamp = tripUpdate.getStopTimeUpdate(h).getArrival().getTime();
            if (timeStamp < preTime) {
                delay = calcDelayTime(timeStamp);
                if (60 < delay) {

                    StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder();
                    arrival.setTime(timeStamp);

                    StopTimeUpdate preStopTime = tripUpdate.getStopTimeUpdate(h - 1);
                    StopTimeUpdate.Builder newStopTimeUpdate = StopTimeUpdate.newBuilder(preStopTime);
                    newStopTimeUpdate.setArrival(arrival);
                    tripUpdate.setStopTimeUpdate(h - 1, newStopTimeUpdate);
                    preTime = timeStamp;
                    //                  System.out.println("** h = "+ h+ " is "+ timeStamp+ " routeID: "+tripUpdate.getTrip().getRouteId()+ " vehicle: "+tripUpdate.getVehicle().getId());
                    //                  System.out.println("\t DELAY:"+ delay + ", stop time of h-1 change to "+ tripUpdate.getStopTimeUpdate(h-1).getArrival().getTime()+ " from "+ preTime);

                } else {
                    //                  System.out.println(" h = " + h+" routeID: "+tripUpdate.getTrip().getRouteId()+ " vehicle: "+tripUpdate.getVehicle().getId());

                    List<StopTimeUpdate> allStopUpdates = tripUpdate.getStopTimeUpdateList();
                    tripUpdate.clearStopTimeUpdate();
                    TripUpdate.Builder newTripUpdate = tripUpdate.clone();

                    // we have to send out the old tripUpdate, but before that the rest of stopTimes should be deleted from it      
                    newTripUpdate.addAllStopTimeUpdate(allStopUpdates.subList(0, h));
                    entity++;
                    tripUpdateEntity.setId(Integer.toString(entity));
                    tripUpdateEntity.setTripUpdate(newTripUpdate);
                    tripUpdates.addEntity(tripUpdateEntity.build());
                    //System.out.println("what has been sent: size = "+ newTripUpdate.getStopTimeUpdateList().size()+ " stoptime");

                    tripUpdate.addAllStopTimeUpdate(allStopUpdates.subList(h, noStopTimes));
                    //System.out.println("current tripUpdate size = "+ tripUpdate.getStopTimeUpdateList().size()+ " stoptime");
                    preTime = 0;
                    noStopTimes = noStopTimes - h;
                    h = -1;
                    StartTimes startTimes;
                    if (routeVehicleStartTimeMap.containsKeys(route, vehicleId))
                        startTimes = routeVehicleStartTimeMap.get(route, vehicleId);
                    else {
                        startTimes = new StartTimes(startTime, "0");
                        routeVehicleStartTimeMap.put(route, vehicleId, startTimes);
                    }

                    String previousStartT = startTimes.previousStartT;
                    TripDescriptor.Builder newTripDescriptor = TripDescriptor.newBuilder();
                    newTripDescriptor.setTripId(trip);
                    newTripDescriptor.setRouteId(route);
                    newTripDescriptor.setStartTime(previousStartT);
                    newTripDescriptor.setScheduleRelationship(ScheduleRelationship.UNSCHEDULED);
                    tripUpdate.setTrip(newTripDescriptor);
                    //System.out.println("second startTime = "+ tripUpdate.getTrip().getStartTime()+ "  &&&& first startTime = "+ newTripUpdate.getTrip().getStartTime());
                }
            } else
                preTime = timeStamp;
        }

        entity++;

        tripUpdateEntity.setId(Integer.toString(entity));
        tripUpdateEntity.setTripUpdate(tripUpdate);
        tripUpdates.addEntity(tripUpdateEntity.build());
    }
    _tripUpdatesSink.handleFullUpdate(tripUpdates);

    _log.info("stoIDs extracted: " + tripUpdates.getEntities().size());
    // System.out.println("stoIDs extracted: " + tripUpdates.getEntityCount());

    float bearing;
    for (int k = 0; k < vehicleArray.length(); k++) {
        JSONObject vehicleObj = vehicleArray.getJSONObject(k);
        route = vehicleObj.getString("route").substring(6);
        JSONArray vehicleLocsArray = vehicleObj.getJSONArray("VehicleLocation");

        for (int l = 0; l < vehicleLocsArray.length(); ++l) {
            JSONObject child = vehicleLocsArray.getJSONObject(l);
            double lat = child.getDouble("vehicleLat");
            double lon = child.getDouble("vehicleLong");
            /**
             * To construct our VehiclePosition, we create a position for
             * the vehicle. We add the position to a VehiclePosition
             * builder, along with the trip and vehicle descriptors.
             */
            tripDescriptor = TripDescriptor.newBuilder();
            tripDescriptor.setRouteId(route);
            Position.Builder position = Position.newBuilder();
            //position.setLatitude((float) lat);
            //position.setLongitude((float) lon);

            FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder();
            //int tripID_int = child.getInt("tripId"); 
            String vehicleId = child.getString("VehicleId");
            if (!routeVehiDirMap.containsKey(route))
                extractHeading(route);

            vehicleInfo info = tripVehicleInfoMap.get(route, vehicleId);

            //_log.info("vehicles' info: " + info); 
            bearing = info.bearing;

            //routeVehiDirMap.get(route, vehicleId);   
            position.setBearing(bearing);
            position.setLatitude(info.lat);
            position.setLongitude(info.longi);
            VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder();
            vehiclePosition.setPosition(position);
            vehiclePosition.setTrip(tripDescriptor);

            if (info.APCPercentage <= 0)
                vehiclePosition.setOccupancyStatus(VehiclePosition.OccupancyStatus.EMPTY);
            else if (info.APCPercentage >= 95)
                vehiclePosition.setOccupancyStatus(VehiclePosition.OccupancyStatus.FULL);
            else if (info.APCPercentage <= 50)
                vehiclePosition.setOccupancyStatus(VehiclePosition.OccupancyStatus.MANY_SEATS_AVAILABLE);
            else
                vehiclePosition.setOccupancyStatus(VehiclePosition.OccupancyStatus.FEW_SEATS_AVAILABLE);

            vehicleDescriptor = VehicleDescriptor.newBuilder();
            vehicleDescriptor.setId(vehicleId);

            vehicleFeedID++;

            vehiclePositionEntity.setId(Integer.toString(vehicleFeedID));
            vehiclePosition.setVehicle(vehicleDescriptor);
            vehiclePositionEntity.setVehicle(vehiclePosition);

            vehiclePositions.addEntity(vehiclePositionEntity.build());

        }
    }
    _vehiclePositionsSink.handleFullUpdate(vehiclePositions);
    _log.info("vehicles' location extracted: " + vehiclePositions.getEntities().size());
    //System.out.println("vehicles' location extracted: " + vehiclePositions.getEntityCount());
}

From source file:edu.usf.cutr.gtfs_realtime.bullrunner.GtfsRealtimeProviderImpl.java

private void extractHeading(String route) throws IOException, JSONException {
    int routeID = _providerConfig.routesMap.get(route);

    String urlStr = "" + "http://usfbullrunner.com/route/" + routeID + "/vehicles";
    JSONArray jsonVehicle = _providerConfig.downloadCofiguration(new URL(urlStr));

    for (int i = 0; i < jsonVehicle.length(); i++) {

        JSONObject child = jsonVehicle.getJSONObject(i);
        String heading = child.getString("Heading");
        float direction = getDirVal(heading);
        String vehicleID = child.getString("Name");
        routeVehiDirMap.put(route, vehicleID, direction);

        JSONObject coordinate = child.getJSONObject("Coordinate");
        vehicleInfo info = new vehicleInfo();
        info.lat = (float) coordinate.getDouble("Latitude");
        info.longi = (float) coordinate.getDouble("Longitude");
        info.bearing = direction;//from   w ww.  j  a  va2s  . com

        info.APCPercentage = child.getInt("APCPercentage");

        tripVehicleInfoMap.put(route, vehicleID, info);
    }

}

From source file:com.msrproduction.sunshine.app.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from ww  w  .  j  a v  a2 s .c  o m*/
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }
        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:edu.asu.bscs.csiebler.waypointapplication.Waypoint.java

/**
 * Constructor/*from w ww  . j a v  a2s .  co  m*/
 *
 * @param jsonObj
 */
public Waypoint(JSONObject jsonObj) {
    try {
        latitude = jsonObj.getDouble("lat");
        longitude = jsonObj.getDouble("lon");
        elevation = jsonObj.getDouble("ele");
        name = jsonObj.getString("name");
        address = jsonObj.getString("address");
        category = Category.valueOf(jsonObj.getString("category"));
    } catch (Exception ex) {
        System.out.println("Exception constructing waypoint from JSON: " + ex.getMessage());
    }
}