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:com.ibm.iot.auto.bluemix.samples.ui.DriverService.java

public List<DriverBehaviorDetail> getAllDriverBehaviorDetails(String tripUuId)
        throws IOException, JSONException {
    JSONObject jsonObject = connection.getJSONObject("/drbresult/trip", "trip_uuid=" + tripUuId);
    JSONArray ctxSubTrips = jsonObject.getJSONArray("ctx_sub_trips");
    List<DriverBehaviorDetail> driverBehaviorDetails = new ArrayList<DriverBehaviorDetail>();
    for (int i = 0; i < ctxSubTrips.length(); i++) {
        JSONObject ctxSubTrip = ctxSubTrips.getJSONObject(i);
        JSONArray features = ctxSubTrip.getJSONArray("ctx_features");
        List<ContextFeature> contextFeatures = new ArrayList<ContextFeature>();
        for (int j = 0; j < features.length(); j++) {
            JSONObject feature = features.getJSONObject(j);
            String category = feature.getString("context_category");
            String name = feature.getString("context_name");
            ContextFeature contextFeature = new ContextFeature(category, name);
            contextFeatures.add(contextFeature);
        }//from  w  ww  . j a  v a  2 s.c o m
        JSONArray details = ctxSubTrip.getJSONArray("driving_behavior_details");
        for (int k = 0; k < details.length(); k++) {
            JSONObject detail = details.getJSONObject(k);
            DriverBehaviorDetail driverBehaviorDetail = new DriverBehaviorDetail(contextFeatures,
                    detail.getString("behavior_name"), String.valueOf(detail.getDouble("start_latitude")),
                    String.valueOf(detail.getDouble("start_longitude")),
                    String.valueOf(detail.getDouble("end_latitude")),
                    String.valueOf(detail.getDouble("end_longitude")),
                    String.valueOf(detail.getLong("start_time")), String.valueOf(detail.getLong("end_time")));
            driverBehaviorDetails.add(driverBehaviorDetail);
        }
    }
    return driverBehaviorDetails;
}

From source file:net.olejon.mdapp.MessageIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final Context mContext = this;

    final MyTools mTools = new MyTools(mContext);

    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    int projectVersionCode = mTools.getProjectVersionCode();

    String device = mTools.getDevice();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            getString(R.string.project_website_uri) + "api/1/message/?version_code=" + projectVersionCode
                    + "&device=" + device,
            new Response.Listener<JSONObject>() {
                @SuppressLint("InlinedApi")
                @Override/*  www .j a v a 2  s  .  c  o  m*/
                public void onResponse(JSONObject response) {
                    try {
                        final long id = response.getLong("id");
                        final String title = response.getString("title");
                        final String message = response.getString("message");
                        final String bigMessage = response.getString("big_message");
                        final String button = response.getString("button");
                        final String uri = response.getString("uri");

                        final long lastId = mTools.getSharedPreferencesLong("MESSAGE_LAST_ID");

                        mTools.setSharedPreferencesLong("MESSAGE_LAST_ID", id);

                        if (lastId != 0 && id != lastId) {
                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                    R.drawable.ic_launcher);

                            NotificationManagerCompat notificationManager = NotificationManagerCompat
                                    .from(mContext);
                            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                    mContext);

                            notificationBuilder.setWhen(mTools.getCurrentTime()).setAutoCancel(true)
                                    .setPriority(Notification.PRIORITY_HIGH)
                                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                                    .setCategory(Notification.CATEGORY_MESSAGE).setLargeIcon(bitmap)
                                    .setSmallIcon(R.drawable.ic_local_hospital_white_24dp)
                                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                    .setLights(Color.BLUE, 1000, 2000).setTicker(message).setContentTitle(title)
                                    .setContentText(message)
                                    .setStyle(new NotificationCompat.BigTextStyle().bigText(bigMessage));

                            if (!uri.equals("")) {
                                Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                PendingIntent launchPendingIntent = PendingIntent.getActivity(mContext, 0,
                                        launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                                notificationBuilder.setContentIntent(launchPendingIntent).addAction(
                                        R.drawable.ic_local_hospital_white_24dp, button, launchPendingIntent);
                            }

                            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
                        }
                    } catch (Exception e) {
                        Log.e("MessageIntentService", Log.getStackTraceString(e));
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("MessageIntentService", error.toString());
                }
            });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(jsonObjectRequest);
}

From source file:net.micode.notes.gtask.remote.GTaskClient.java

private boolean loginGtask(String authToken) {
    int timeoutConnection = 10000;
    int timeoutSocket = 15000;
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    mHttpClient = new DefaultHttpClient(httpParameters);
    BasicCookieStore localBasicCookieStore = new BasicCookieStore();
    mHttpClient.setCookieStore(localBasicCookieStore);
    HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);

    // login gtask
    try {/*from  ww  w .j a va  2  s.c  o m*/
        String loginUrl = mGetUrl + "?auth=" + authToken;
        HttpGet httpGet = new HttpGet(loginUrl);
        HttpResponse response = null;
        response = mHttpClient.execute(httpGet);

        // get the cookie now
        List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
        boolean hasAuthCookie = false;
        for (Cookie cookie : cookies) {
            if (cookie.getName().contains("GTL")) {
                hasAuthCookie = true;
            }
        }
        if (!hasAuthCookie) {
            Log.w(TAG, "it seems that there is no auth cookie");
        }

        // get the client version
        String resString = getResponseContent(response.getEntity());
        String jsBegin = "_setup(";
        String jsEnd = ")}</script>";
        int begin = resString.indexOf(jsBegin);
        int end = resString.lastIndexOf(jsEnd);
        String jsString = null;
        if (begin != -1 && end != -1 && begin < end) {
            jsString = resString.substring(begin + jsBegin.length(), end);
        }
        JSONObject js = new JSONObject(jsString);
        mClientVersion = js.getLong("v");
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        // simply catch all exceptions
        Log.e(TAG, "httpget gtask_url failed");
        return false;
    }

    return true;
}

From source file:org.schedulesdirect.grabber.Auditor.java

private void auditScheds() throws IOException, JSONException, ParseException {
    final Map<String, JSONObject> stations = getStationMap();
    final SimpleDateFormat FMT = Config.get().getDateTimeFormat();
    final Path scheds = vfs.getPath("schedules");
    if (Files.isDirectory(scheds)) {
        Files.walkFileTree(scheds, new FileVisitor<Path>() {

            @Override//from  w  ww.j a va2 s.  c om
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return dir.equals(scheds) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                boolean failed = false;
                String id = getStationIdFromFileName(file.getFileName().toString());
                JSONObject station = stations.get(id);
                StringBuilder msg = new StringBuilder(String.format("Inspecting %s (%s)... ",
                        station != null ? station.getString("callsign") : String.format("[UNKNOWN: %s]", id),
                        id));
                String input;
                try (InputStream ins = Files.newInputStream(file)) {
                    input = IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString());
                }
                ObjectMapper mapper = Config.get().getObjectMapper();
                JSONArray jarr = mapper.readValue(
                        mapper.readValue(input, JSONObject.class).getJSONArray("programs").toString(),
                        JSONArray.class);
                for (int i = 1; i < jarr.length(); ++i) {
                    long start, prevStart;
                    JSONObject prev;
                    try {
                        start = FMT.parse(jarr.getJSONObject(i).getString("airDateTime")).getTime();
                        prev = jarr.getJSONObject(i - 1);
                        prevStart = FMT.parse(prev.getString("airDateTime")).getTime()
                                + 1000L * prev.getLong("duration");
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    if (prevStart != start) {
                        msg.append(String.format("FAILED! [%s]", prev.getString("airDateTime")));
                        LOG.error(msg);
                        failed = true;
                        Auditor.this.failed = true;
                        break;
                    }
                }
                if (!failed) {
                    msg.append("PASSED!");
                    LOG.info(msg);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                LOG.error(String.format("Unable to process schedule file '%s'", file), exc);
                Auditor.this.failed = true;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    }
}

From source file:drusy.ui.panels.InternetStatePanel.java

private void updateUptimeInformation() {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_XDSL, output,
            "Fetching xdsl state", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override// w  w w  .  ja v a  2 s. co m
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONObject result = obj.getJSONObject("result");
                JSONObject status = result.getJSONObject("status");
                long uptime = status.getLong("uptime");

                uptimeContentLabel.setText(formatInterval(uptime));
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox xdsl State", msg);
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox xdsl State", ex.getMessage());
        }
    });
}

From source file:ded.model.Diagram.java

/** Deserialize from 'o'. */
public Diagram(JSONObject o) throws JSONException {
    String type = o.getString("type");
    if (!type.equals(jsonType)) {
        throw new JSONException("unexpected file type: \"" + type + "\"");
    }/*from w  ww  . ja  v  a2 s.  c o  m*/

    int ver = (int) o.getLong("version");
    if (ver < 1) {
        throw new JSONException("Invalid file version: " + ver + ".  Valid version "
                + "numbers are and will always be positive.");
    } else if (ver > currentFileVersion) {
        throw new JSONException("The file has version " + ver
                + " but the largest version this program is capable of " + "reading is " + currentFileVersion
                + ".  You need to get " + "a later version of the program in order to read " + "this file.");
    }

    this.windowSize = AWTJSONUtil.dimensionFromJSON(o.getJSONObject("windowSize"));
    this.namedColors = makeDefaultColors();

    if (ver >= 3) {
        this.drawFileName = o.getBoolean("drawFileName");
    } else {
        this.drawFileName = true;
    }

    // Make the lists now; this is particularly useful for handling
    // older file formats.
    this.entities = new ArrayList<Entity>();
    this.inheritances = new ArrayList<Inheritance>();
    this.relations = new ArrayList<Relation>();

    // Map from serialized position to deserialized Entity.
    ArrayList<Entity> integerToEntity = new ArrayList<Entity>();

    // Entities.
    JSONArray a = o.getJSONArray("entities");
    for (int i = 0; i < a.length(); i++) {
        Entity e = new Entity(a.getJSONObject(i), ver);
        this.entities.add(e);
        integerToEntity.add(e);
    }

    if (ver >= 2) {
        // Map from serialized position to deserialized Inheritance.
        ArrayList<Inheritance> integerToInheritance = new ArrayList<Inheritance>();

        // Inheritances.
        a = o.getJSONArray("inheritances");
        for (int i = 0; i < a.length(); i++) {
            Inheritance inh = new Inheritance(a.getJSONObject(i), integerToEntity);
            this.inheritances.add(inh);
            integerToInheritance.add(inh);
        }

        // Relations.
        a = o.getJSONArray("relations");
        for (int i = 0; i < a.length(); i++) {
            Relation rel = new Relation(a.getJSONObject(i), integerToEntity, integerToInheritance, ver);
            this.relations.add(rel);
        }
    }
}

From source file:com.ofalvai.bpinfo.api.bkkinfo.BkkInfoClient.java

/**
 * Parses alert details found in the alert list API response
 * This structure is different than the alert detail API response
 */// www.j a v  a  2  s . c  o m
@NonNull
private Alert parseAlert(JSONObject alertNode) throws JSONException {
    String id = alertNode.getString("id");

    long start = 0;
    if (!alertNode.isNull("kezd")) {
        JSONObject beginNode = alertNode.getJSONObject("kezd");
        start = beginNode.getLong("epoch");
    }

    long end = 0;
    if (!alertNode.isNull("vege")) {
        JSONObject endNode = alertNode.getJSONObject("vege");
        end = endNode.getLong("epoch");
    }

    long timestamp;
    JSONObject modifiedNode = alertNode.getJSONObject("modositva");
    timestamp = modifiedNode.getLong("epoch");

    String url = getUrl(id);

    String header = Utils.capitalizeString(alertNode.getString("elnevezes"));

    List<Route> affectedRoutes;
    JSONArray routesArray = alertNode.getJSONArray("jaratokByFajta");
    affectedRoutes = parseAffectedRoutes(routesArray);

    return new Alert(id, start, end, timestamp, url, header, null, affectedRoutes, true);
}

From source file:com.ofalvai.bpinfo.api.bkkinfo.BkkInfoClient.java

/**
 * Parses alert details found in the alert detail API response
 * This structure is different than the alert list API response
 *///from   w w  w.  java  2 s.co  m
private Alert parseAlertDetail(JSONObject response) throws JSONException {
    String id = response.getString("id");

    long start = 0;
    if (!response.isNull("kezdEpoch")) {
        start = response.getLong("kezdEpoch");
    }

    long end = 0;
    if (!response.isNull("vegeEpoch")) {
        end = response.getLong("vegeEpoch");
    }

    long timestamp = 0;
    if (!response.isNull("modEpoch")) {
        timestamp = response.getLong("modEpoch");
    }

    String url = getUrl(id);

    String header;
    // The API returns a header of 3 parts separated by "|" characters. We need the last part.
    String rawHeader = response.getString("targy");
    String[] rawHeaderParts = rawHeader.split("\\|");
    header = Utils.capitalizeString(rawHeaderParts[2].trim());

    String description;
    StringBuilder descriptionBuilder = new StringBuilder();
    descriptionBuilder.append(response.getString("feed"));

    JSONArray routesArray = Utils.jsonObjectToArray(response.getJSONObject("jaratok"));
    for (int i = 0; i < routesArray.length(); i++) {
        JSONObject routeNode = routesArray.getJSONObject(i);
        JSONObject optionsNode = routeNode.getJSONObject("opciok");

        if (!optionsNode.isNull("szabad_szoveg")) {
            JSONArray routeTextArray = optionsNode.getJSONArray("szabad_szoveg");
            for (int j = 0; j < routeTextArray.length(); j++) {
                descriptionBuilder.append("<br />");
                descriptionBuilder.append(routeTextArray.getString(j));
            }
        }
    }
    description = descriptionBuilder.toString();

    List<Route> affectedRoutes;
    JSONObject routeDetailsNode = response.getJSONObject("jarat_adatok");
    Iterator<String> affectedRouteIds = response.getJSONObject("jaratok").keys();
    // Some routes in routeDetailsNode are not affected by the alert, but alternative
    // recommended routes. The real affected routes' IDs are in "jaratok"
    affectedRoutes = parseDetailedAffectedRoutes(routeDetailsNode, affectedRouteIds);

    return new Alert(id, start, end, timestamp, url, header, description, affectedRoutes, false);
}

From source file:damian.hashmap.MyActivity.java

public void generateLicenses() throws JSONException {

    JSONArray obj = new JSONArray(loadJSONFromAsset());
    for (int i = 0; i < obj.length(); i++) {
        JSONObject obj2 = obj.getJSONObject(i);
        String name = obj2.getString("name");
        int dni = obj2.getInt("dni");
        JSONObject license = obj2.getJSONObject("license");
        License license1 = new License();
        if (license.length() > 0) {
            license1.setName(name);//w w  w.j a v  a2 s. c  o m
            long since = license.getLong("since");
            long until = license.getLong("until");
            license1.setSince(since);
            license1.setUntil(until);
        }
        Person person = new Person();
        person.setDni(dni);
        person.setName(name);
        if (license.length() > 0) {
            licences.put(person, license1);
        } else {
            licences.put(person, null);
        }
    }
}

From source file:com.github.koraktor.steamcondenser.community.GameItem.java

/**
 * Creates a new instance of a GameItem with the given data
 *
 * @param inventory The inventory this item is contained in
 * @param itemData The data specifying this item
 * @throws WebApiException on Web API errors
 *///  w ww  .j  av  a 2  s. co  m
public GameItem(GameInventory inventory, JSONObject itemData) throws SteamCondenserException {
    this.inventory = inventory;

    try {
        this.defindex = itemData.getInt("defindex");
        this.backpackPosition = (int) itemData.getLong("inventory") & 0xffff;
        this.count = itemData.getInt("quantity");
        this.craftable = !itemData.optBoolean("flag_cannot_craft");
        this.id = itemData.getInt("id");
        this.itemClass = this.getSchemaData().getString("item_class");
        this.itemSet = this.inventory.getItemSchema().getItemSets()
                .get(this.getSchemaData().optString("item_set"));
        this.level = itemData.getInt("level");
        this.name = this.getSchemaData().getString("item_name");
        this.preliminary = (itemData.getLong("inventory") & 0x40000000) != 0;
        this.originalId = itemData.getInt("original_id");
        this.quality = this.inventory.getItemSchema().getQualities().get(itemData.getInt("quality"));
        this.tradeable = !itemData.optBoolean("flag_cannot_trade");
        this.type = this.getSchemaData().getString("item_type_name");

        if (itemData.has("origin")) {
            this.origin = this.inventory.getItemSchema().getOrigins().get(itemData.getInt("origin"));
        }

        JSONArray attributesData = this.getSchemaData().optJSONArray("attributes");
        if (attributesData == null) {
            attributesData = new JSONArray();
        }
        if (itemData.has("attributes")) {
            JSONArray itemAttributes = itemData.getJSONArray("attributes");
            for (int i = 0; i < itemAttributes.length(); i++) {
                attributesData.put(itemAttributes.get(i));
            }
        }

        this.attributes = new ArrayList<JSONObject>();
        for (int i = 0; i < attributesData.length(); i++) {
            JSONObject attributeData = attributesData.getJSONObject(i);
            Object attributeKey = attributeData.opt("defindex");
            if (attributeKey == null) {
                attributeKey = attributeData.opt("name");
            }

            if (attributeKey != null) {
                JSONObject schemaAttributeData = inventory.getItemSchema().getAttributes().get(attributeKey);
                for (String key : JSONObject.getNames(schemaAttributeData)) {
                    attributeData.put(key, schemaAttributeData.get(key));
                }
                this.attributes.add(attributeData);
            }
        }
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}