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:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;//w ww .  ja va 2s  .co m
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:com.brennasoft.facebookdashclockextension.fbclient.NotificationsRequest.java

private NotificationsResponse parseResponse(Response response) {
    NotificationsResponse notificationsResponse = new NotificationsResponse();
    GraphObject graphObject = response.getGraphObject();
    try {/*from w w  w. jav  a  2s.c  om*/
        JSONArray data = graphObject.getInnerJSONObject().getJSONArray("data");
        notificationsResponse.count = data.length();
        for (int i = 0; i < data.length(); i++) {
            JSONObject object = data.getJSONObject(i);
            notificationsResponse.addNotification(object.getString("notification_id"),
                    object.getLong("updated_time"), object.getString("title_text"));
        }
        notificationsResponse.success = true;
    } catch (JSONException e) {
        Crashlytics.logException(e);
    }
    return notificationsResponse;
}

From source file:com.liferay.mobile.android.auth.SignIn.java

public static void signIn(final Session session, final JSONObjectCallback callback, final SignInMethod method) {

    GroupService groupService = new GroupService(session);

    session.setCallback(new JSONArrayCallback() {

        @Override/*from  ww w.  j  ava  2s. c o m*/
        public void onSuccess(JSONArray sites) {
            if (sites.length() == 0) {
                onFailure(new Exception("User doesn't belong to any site"));
            }

            try {
                JSONObject site = sites.getJSONObject(0);
                long companyId = site.getLong("companyId");

                Session userSession = new SessionImpl(session);
                userSession.setCallback(callback);

                UserService userService = new UserService(userSession);

                String username = getUsername(session);

                if (method == SignInMethod.EMAIL) {
                    userService.getUserByEmailAddress(companyId, username);
                } else if (method == SignInMethod.USER_ID) {
                    userService.getUserById(Long.parseLong(username));
                } else {
                    userService.getUserByScreenName(companyId, username);
                }
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            callback.onFailure(exception);
        }

    });

    try {
        groupService.getUserSitesGroups();
    } catch (Exception e) {
        callback.onFailure(e);
    }
}

From source file:com.ichi2.libanki.importer.Anki2Importer.java

/** Decks */

/* Given did in src col, return local id */
private long _did(long did) {
    try {/* ww w .ja  va 2  s .  c  o  m*/
        // already converted?
        if (mDecks.containsKey(did)) {
            return mDecks.get(did);
        }
        // get the name in src
        JSONObject g = mSrc.getDecks().get(did);
        String name = g.getString("name");
        // if there's a prefix, replace the top level deck
        if (mDeckPrefix != null) {
            String[] tmpname = name.split("::", -1);
            name = mDeckPrefix;
            if (tmpname.length > 1) {
                for (int i = 0; i < tmpname.length - 2; i++) {
                    name += "::" + tmpname[i + 1];
                }
            }
        }
        // Manually create any parents so we can pull in descriptions
        String head = "";
        String[] parents = name.split("::", -1);
        for (int i = 0; i < parents.length - 1; ++i) {
            if (head.length() > 0) {
                head = head.concat("::");
            }
            head = head.concat(parents[i]);
            long idInSrc = mSrc.getDecks().id(head);
            _did(idInSrc);
        }
        // create in local
        long newid = mDst.getDecks().id(name);
        // pull conf over
        if (g.has("conf") && g.getLong("conf") != 1) {
            JSONObject conf = mSrc.getDecks().getConf(g.getLong("conf"));
            mDst.getDecks().save(conf);
            mDst.getDecks().updateConf(conf);
            JSONObject g2 = mDst.getDecks().get(newid);
            g2.put("conf", g.getLong("conf"));
            mDst.getDecks().save(g2);
        }
        // save desc
        JSONObject deck = mDst.getDecks().get(newid);
        deck.put("desc", g.getString("desc"));
        mDst.getDecks().save(deck);
        // add to deck map and return
        mDecks.put(did, newid);
        return newid;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.asd.littleprincesbeauty.data.TaskList.java

@Override
public void setContentByRemoteJSON(JSONObject js) {
    if (js != null) {
        try {//  w w w  .j a v a2s. com
            // id
            if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
                setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
            }

            // last_modified
            if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
                setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
            }

            // name
            if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
                setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
            }

        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("fail to get tasklist content from jsonobject");
        }
    }
}

From source file:com.asd.littleprincesbeauty.data.TaskList.java

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }//from   w  w  w  .  jav a 2 s. c  o m

    try {
        JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);

        if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            String name = folder.getString(NoteColumns.SNIPPET);
            setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
        } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
            else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE);
            else
                Log.e(TAG, "invalid system folder");
        } else {
            Log.e(TAG, "error type");
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

From source file:com.citruspay.mobile.payment.oauth2.OAuth2Token.java

public static OAuth2Token create(JSONObject json) {
    // enhance object w/ expiry date
    JSONObject jtoken = json;/*from w  w  w.  j ava 2  s . c o  m*/
    if (!json.has("expiry")) {
        // copy input
        jtoken = new JSONObject();
        for (Iterator<?> keys = json.keys(); keys.hasNext();) {
            String key = (String) keys.next();
            try {
                jtoken.put(key, json.get(key));
            } catch (JSONException jx) {
                throw new RuntimeException(jx);
            }
        }

        // add expiry date
        long expiry = new Date().getTime() / 1000l;
        try {
            expiry += json.getLong("expires_in");
        } catch (JSONException jx) {
            /* ignore => expires now ! */
        }
        try {
            jtoken.put("expiry", expiry);
        } catch (JSONException jx) {
            throw new RuntimeException(jx);
        }
    }

    // create token
    return new OAuth2Token(jtoken);
}

From source file:com.marlonjones.voidlauncher.InstallShortcutReceiver.java

private static PendingInstallShortcutInfo decode(String encoded, Context context) {
    try {/*from ww w.  ja  va  2s.  co m*/
        JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue();
        Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);

        if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) {
            // The is an internal launcher target shortcut.
            UserHandleCompat user = UserManagerCompat.getInstance(context)
                    .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY));
            if (user == null) {
                return null;
            }

            LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context)
                    .resolveActivity(launcherIntent, user);
            return info == null ? null : new PendingInstallShortcutInfo(info, context);
        }

        Intent data = new Intent();
        data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY));

        String iconBase64 = object.optString(ICON_KEY);
        String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
        String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
        if (iconBase64 != null && !iconBase64.isEmpty()) {
            byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
            Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
        } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
            Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
            iconResource.resourceName = iconResourceName;
            iconResource.packageName = iconResourcePackageName;
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
        }

        return new PendingInstallShortcutInfo(data, context);
    } catch (JSONException | URISyntaxException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    }
    return null;
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

public void sendChangesToCozy() {
    List<Expense> unSyncedExpenses = Expense.getAllUnsynced();
    int i = 0;/*from w w  w . java2 s  .c  o m*/
    for (Expense expense : unSyncedExpenses) {
        URL urlO = null;
        try {
            JSONObject jsonObject = expense.toJsonObject();
            mBuilder.setProgress(unSyncedExpenses.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new ExpenseSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_expense_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                expense.setRemoteId(result);
                expense.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:face4j.response.LimitsResponseImpl.java

public LimitsResponseImpl(final String json) throws FaceClientException {
    super(json);//from w w w  . ja v a2s  .c o  m

    try {
        // usage stats
        final JSONObject usage = response.getJSONObject("usage");
        namespaceRemaining = optInt(usage, "namespace_remaining");
        namespaceUsed = optInt(usage, "namespace_used");
        namespaceLimit = optInt(usage, "namespace_limit");
        restTimeString = usage.getString("reset_time_text");
        resetDate = new Date(usage.getLong("reset_time"));
        remaining = usage.getInt("remaining");
        used = usage.getInt("used");
        limit = usage.getInt("limit");
    }

    catch (JSONException jex) {
        logger.error("Error: ", jex);
        throw new FaceClientException(jex);
    }
}