Example usage for org.json JSONObject getLong

List of usage examples for org.json JSONObject getLong

Introduction

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

Prototype

public long getLong(String key) throws JSONException 

Source Link

Document

Get the long value associated with a key.

Usage

From source file:org.openmhealth.dpu.mobilityclassifier.example.Example.java

public static void main(String[] args) throws IOException, JSONException {

    BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("example.json")));
    String line = in.readLine();/*from  w ww.jav  a 2 s . co  m*/
    StringBuilder jsonStringBuilder = new StringBuilder();

    while (line != null) {
        jsonStringBuilder.append(line);
        line = in.readLine();
    }

    in.close();

    JSONArray array = new JSONArray(jsonStringBuilder.toString());
    List<SensorDataPoint> sensorDataPoints = new ArrayList<SensorDataPoint>();

    int length = array.length();
    for (int i = 0; i < length; i++) {
        JSONObject object = array.getJSONObject(i);

        List<Sample> samples = new ArrayList<Sample>();
        double speed = 0.0D;
        long time = 0;
        DateTimeZone timezone = null;
        List<AccessPoint> accessPoints = new ArrayList<AccessPoint>();

        JSONArray accelDataArray = object.getJSONArray("accel_data");
        int numberOfAccelPoints = accelDataArray.length();

        for (int j = 0; j < numberOfAccelPoints; j++) {
            samples.add(new Sample(accelDataArray.getJSONObject(j).getDouble("x"),
                    accelDataArray.getJSONObject(j).getDouble("y"),
                    accelDataArray.getJSONObject(j).getDouble("z")));
        }

        speed = object.getDouble("speed");
        JSONObject wifiObject = object.getJSONObject("wifi_data");
        timezone = DateTimeZone.forID(wifiObject.getString("timezone"));
        time = wifiObject.getLong("time");
        JSONArray scanArray = wifiObject.getJSONArray("scan");
        int numberOfScans = scanArray.length();

        for (int k = 0; k < numberOfScans; k++) {
            accessPoints.add(new AccessPoint(scanArray.getJSONObject(k).getString("ssid"),
                    scanArray.getJSONObject(k).getInt("strength")));
        }

        SensorDataPoint point = new SensorDataPoint(UUID.randomUUID(), speed, timezone,
                new WifiScan(time, accessPoints), samples);
        sensorDataPoints.add(point);
    }

    List<ClassifiedPoint> classifiedPointList = ClassificationService.classify(sensorDataPoints);

    for (ClassifiedPoint cp : classifiedPointList) {
        System.out.println(cp);
    }
}

From source file:ded.model.Inheritance.java

public Inheritance(JSONObject o, ArrayList<Entity> integerToEntity) throws JSONException {
    this.parent = Entity.fromJSONRef(integerToEntity, o.getLong("parentRef"));
    this.open = o.getBoolean("open");
    this.pt = AWTJSONUtil.pointFromJSON(o.getJSONObject("pt"));
}

From source file:com.github.dfa.diaspora_android.data.PodAspect.java

public PodAspect(JSONObject json) throws JSONException {
    if (json.has("id")) {
        id = json.getLong("id");
    }/*from w w  w  . j  a  v a2 s  . co m*/
    if (json.has("name")) {
        name = json.getString("name");
    }
    if (json.has("selected")) {
        selected = json.getBoolean("selected");
    }
}

From source file:ded.model.RelationEndpoint.java

public RelationEndpoint(JSONObject o, ArrayList<Entity> integerToEntity,
        ArrayList<Inheritance> integerToInheritance, ArrowStyle defaultArrowStyle, int version)
        throws JSONException {
    this.entity = null;
    this.inheritance = null;
    this.pt = null;

    if (version >= 9 && o.has("arrowStyle")) {
        this.arrowStyle = ArrowStyle.valueOf(ArrowStyle.class, o.getString("arrowStyle"));
    } else {//from ww w.ja  va2 s  .  c om
        this.arrowStyle = defaultArrowStyle;
    }

    if (o.has("entityRef")) {
        this.entity = Entity.fromJSONRef(integerToEntity, o.getLong("entityRef"));
        return;
    }

    if (o.has("inheritanceRef")) {
        this.inheritance = Inheritance.fromJSONRef(integerToInheritance, o.getLong("inheritanceRef"));
        return;
    }

    this.pt = AWTJSONUtil.pointFromJSON(o.getJSONObject("pt"));
}

From source file:net.dv8tion.jda.core.handle.GuildMembersChunkHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long guildId = content.getLong("guild_id");
    List<JSONArray> memberChunks = memberChunksCache.get(guildId);
    int expectMemberCount = expectedGuildMembers.get(guildId);

    JSONArray members = content.getJSONArray("members");
    JDAImpl.LOG.debug("GUILD_MEMBER_CHUNK for: " + guildId + " \tMembers: " + members.length());
    memberChunks.add(members);/* ww w .j  av a  2  s  . com*/

    int currentTotal = 0;
    for (JSONArray arr : memberChunks) {
        currentTotal += arr.length();
    }

    if (currentTotal >= expectMemberCount) {
        JDAImpl.LOG.debug("Finished chunking for: " + guildId);
        api.getEntityBuilder().createGuildSecondPass(guildId, memberChunks);
        memberChunksCache.remove(guildId);
        expectedGuildMembers.remove(guildId);
    }
    return null;
}

From source file:org.zaizi.alfresco.redlink.service.search.solr.SensefySolrJSONResultSet.java

/**
 * Detached result set based on that provided
 * /*from   ww  w. java 2 s  . co m*/
 * @param resultSet
 */
@SuppressWarnings("rawtypes")
public SensefySolrJSONResultSet(JSONObject json, SearchParameters searchParameters, NodeService nodeService,
        NodeDAO nodeDao, LimitBy limitBy, int maxResults) {
    // Note all properties are returned as multi-valued from the WildcardField "*" definition in the SOLR schema.xml
    this.nodeService = nodeService;
    this.nodeDao = nodeDao;
    try {
        JSONObject responseHeader = json.getJSONObject("header");
        status = responseHeader.getLong("status");
        queryTime = responseHeader.getLong("qtime");

        JSONObject response = json.getJSONObject("response");
        numberFound = response.getLong("numFound");
        start = response.getLong("start");
        // maxScore = Float.valueOf(response.getString("maxScore"));

        JSONArray docs = response.getJSONArray("docs");

        int numDocs = docs.length();

        ArrayList<Long> rawDbids = new ArrayList<Long>(numDocs);
        ArrayList<Float> rawScores = new ArrayList<Float>(numDocs);
        for (int i = 0; i < numDocs; i++) {
            JSONObject doc = docs.getJSONObject(i);
            Long dbid = doc.getLong("DBID");
            Float score = Float.valueOf(doc.getString("score"));

            rawDbids.add(dbid);
            rawScores.add(score);
        }

        // bulk load

        nodeDao.cacheNodesById(rawDbids);

        // filter out rubbish

        page = new ArrayList<Pair<Long, Float>>(numDocs);
        refs = new ArrayList<NodeRef>(numDocs);
        for (int i = 0; i < numDocs; i++) {
            Long dbid = rawDbids.get(i);
            NodeRef nodeRef = nodeService.getNodeRef(dbid);

            if (nodeRef != null) {
                page.add(new Pair<Long, Float>(dbid, rawScores.get(i)));
                refs.add(nodeRef);
            }
        }

        if (json.has("facets")) {
            JSONObject facets = json.getJSONObject("facets");
            Iterator it = facets.keys();
            while (it.hasNext()) {
                String facetName = (String) it.next();
                JSONObject facetJSON = facets.getJSONObject(facetName);
                ArrayList<Pair<String, Integer>> facetValues = new ArrayList<Pair<String, Integer>>(
                        facetJSON.length());
                Iterator it2 = facetJSON.keys();
                while (it2.hasNext()) {
                    String facetEntryValue = (String) it2.next();
                    int facetEntryCount = facetJSON.getInt(facetEntryValue);
                    Pair<String, Integer> pair = new Pair<String, Integer>(facetEntryValue, facetEntryCount);
                    facetValues.add(pair);
                }
                fieldFacets.put(facetName, facetValues);
            }
        }

    } catch (JSONException e) {

    }
    // We'll say we were unlimited if we got a number less than the limit
    this.resultSetMetaData = new SimpleResultSetMetaData(
            maxResults > 0 && numberFound < maxResults ? LimitBy.UNLIMITED : limitBy,
            PermissionEvaluationMode.EAGER, searchParameters);
}

From source file:ceruleanotter.github.com.sunshine.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  av  a2  s.co m*/
 */
private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // 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";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

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

    final String OWM_DATETIME = "dt";
    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";

    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 coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getLong(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getLong(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    // The function referenced here is not yet implemented, so we've commented it out for now.
    long locationID = insertLocationInDatabase(locationSetting, cityName, cityLatitude, cityLongitude);

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

    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);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        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_DATETEXT,
                WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
        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);

    }

    if (cVVector.size() > 0) {
        ContentValues[] cvArray = new ContentValues[cVVector.size()];
        cVVector.toArray(cvArray);
        int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data");
    }

}

From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP0708xxDataImpl.java

public static EEP0708xxDataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP0708xxDataImpl(Float.MIN_VALUE, -1, Float.MIN_VALUE, PIRStatus.UNKNOWN, null, null);

    try {/* w  w  w . ja  v  a 2s.c o m*/
        float supplyVoltage = (float) lastKnownData.getDouble("supplyVoltage");
        int illumination = lastKnownData.getInt("illumination");
        float temperature = (float) lastKnownData.getDouble("temperature");
        PIRStatus pirStatus = PIRStatus.valueOf(lastKnownData.getString("pirStatus"));
        long LOPBDate = lastKnownData.optLong("LOPBDate");
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP0708xxDataImpl(supplyVoltage, illumination, temperature, pirStatus,
                (LOPBDate == 0) ? null : new Date(LOPBDate), date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP0708xxDataImpl(Float.MIN_VALUE, -1, Float.MIN_VALUE, PIRStatus.UNKNOWN, null, null);
    }
}

From source file:com.tassadar.multirommgr.installfragment.UbuntuFile.java

public UbuntuFile(JSONObject file) throws JSONException {
    checksum = file.getString("checksum");
    order = file.getInt("order");
    path = file.getString("path");
    signature = file.getString("signature");
    size = file.getLong("size");
}

From source file:com.f16gaming.pathofexilestatistics.PoeEntry.java

public static PoeEntry[] getEntriesFromJSONString(String jsonData) throws JSONException {
    JSONObject root = (JSONObject) new JSONTokener(jsonData).nextValue();
    JSONObject ladder = root.getJSONObject("ladder");
    JSONArray entries = ladder.getJSONArray("entries");
    int length = entries.length();
    PoeEntry[] result = new PoeEntry[length];
    for (int i = 0; i < length; i++) {
        JSONObject entry = entries.getJSONObject(i);
        String account = entry.getJSONObject("account").getString("name");
        int rank = entry.getInt("rank");
        JSONObject character = entry.getJSONObject("character");
        String name = character.getString("name");
        int level = character.getInt("level");
        boolean online = entry.getBoolean("online");
        String className = character.getString("class");
        long experience = character.getLong("experience");
        PoeEntry poeEntry = new PoeEntry(account, rank, name, level, online, className, experience);
        result[i] = poeEntry;/*w  ww  . ja  va 2s .c o m*/
    }
    return result;
}