Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

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

@Override
protected Long handleInternally(JSONObject content) {
    final long id = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(id))
        return id;

    JSONObject userJson = content.getJSONObject("user");
    final long userId = userJson.getLong("id");
    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, userId, () -> {
            handle(responseNumber, allContent);
        });//from  ww  w . ja v  a2s  .c  o  m
        EventCache.LOG.debug("Got GuildMember update but JDA currently does not have the Guild cached. "
                + content.toString());
        return null;
    }

    MemberImpl member = (MemberImpl) guild.getMembersMap().get(userId);
    if (member == null) {
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> {
            handle(responseNumber, allContent);
        });
        EventCache.LOG.debug(
                "Got GuildMember update but Member is not currently present in Guild. " + content.toString());
        return null;
    }

    Set<Role> currentRoles = member.getRoleSet();
    List<Role> newRoles = toRolesList(guild, content.getJSONArray("roles"));

    //If newRoles is null that means that we didn't find a role that was in the array and was cached this event
    if (newRoles == null)
        return null;

    //Find the roles removed.
    List<Role> removedRoles = new LinkedList<>();
    each: for (Role role : currentRoles) {
        for (Iterator<Role> it = newRoles.iterator(); it.hasNext();) {
            Role r = it.next();
            if (role.equals(r)) {
                it.remove();
                continue each;
            }
        }
        removedRoles.add(role);
    }

    if (removedRoles.size() > 0)
        currentRoles.removeAll(removedRoles);
    if (newRoles.size() > 0)
        currentRoles.addAll(newRoles);

    if (removedRoles.size() > 0) {
        api.getEventManager()
                .handle(new GuildMemberRoleRemoveEvent(api, responseNumber, guild, member, removedRoles));
    }
    if (newRoles.size() > 0) {
        api.getEventManager().handle(new GuildMemberRoleAddEvent(api, responseNumber, guild, member, newRoles));
    }
    if (content.has("nick")) {
        String prevNick = member.getNickname();
        String newNick = content.isNull("nick") ? null : content.getString("nick");
        if (!Objects.equals(prevNick, newNick)) {
            member.setNickname(newNick);
            api.getEventManager().handle(
                    new GuildMemberNickChangeEvent(api, responseNumber, guild, member, prevNick, newNick));
        }
    }
    return null;
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

protected void handleGetMetadata(HttpServletRequest request, HttpServletResponse response,
        Writer responseWriter, IFileStore file)
        throws IOException, NoSuchAlgorithmException, JSONException, CoreException {
    JSONObject result = ServletFileStoreHandler.toJSON(file, file.fetchInfo(EFS.NONE, null), getURI(request));
    String etag = generateFileETag(file);
    result.put(ProtocolConstants.KEY_ETAG, etag);
    response.setHeader(ProtocolConstants.KEY_ETAG, etag);
    response.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
    OrionServlet.decorateResponse(request, result, JsonURIUnqualificationStrategy.ALL);
    responseWriter.append(result.toString());
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader,
        HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
    JSONObject changes = OrionServlet.readJSONRequest(request);
    //read file to memory
    Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
    StringWriter oldFile = new StringWriter();
    IOUtilities.pipe(fileReader, oldFile, true, false);
    StringBuffer oldContents = oldFile.getBuffer();

    JSONArray changeList = changes.getJSONArray("diff");
    for (int i = 0; i < changeList.length(); i++) {
        JSONObject change = changeList.getJSONObject(i);
        long start = change.getLong("start");
        long end = change.getLong("end");
        String text = change.getString("text");
        oldContents.replace((int) start, (int) end, text);
    }//  ww w . jav a  2  s  . c  o m

    String newContents = oldContents.toString();
    boolean failed = false;
    if (changes.has("contents")) {
        String contents = changes.getString("contents");
        if (!newContents.equals(contents)) {
            failed = true;
            newContents = contents;
        }
    }
    Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
    IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
    if (failed) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0    "
                                + changes.toString(),
                        null));
        return;
    }

    // return metadata with the new Etag
    handleGetMetadata(request, response, response.getWriter(), file);
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device.//from  ww  w  .  jav  a 2s .c  o  m
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.certificate.DefaultJSONSigner.java

@Override
public String sign(KeyPair keyPair, JSONObject json) throws Exception {

    if (keyPair == null || json == null) {
        throw new IllegalArgumentException("parameter cannot be null");
    }/* w  w  w. ja v a2 s  .c  om*/

    RSAPublicKey publicKey = ((RSAPublicKey) keyPair.getPublic());
    PrivateKey privateKey = keyPair.getPrivate();

    // create CSR Header (based on public key)
    JSONObject jwsHeaderJson = new JSONObject();
    jwsHeaderJson.put(ALG, "RS256");

    JSONObject publicKeyDataJson = new JSONObject();
    publicKeyDataJson.put(ALG, "RSA");

    String mod = encodeUrlSafe(publicKey.getModulus().toByteArray());
    publicKeyDataJson.put("mod", mod);

    String exp = encodeUrlSafe(publicKey.getPublicExponent().toByteArray());
    publicKeyDataJson.put("exp", exp);

    jwsHeaderJson.put("jpk", publicKeyDataJson);

    String jwsHeader = jwsHeaderJson.toString();
    String payload = json.toString();

    // concatenate JWS Header and payload.
    String csrHeaderAndPayload = encodeUrlSafe(jwsHeader.getBytes()) + "." + encodeUrlSafe(payload.getBytes());

    // create CSR Signature
    String jwsSignature = encodeUrlSafe(signCsrData(csrHeaderAndPayload, privateKey));

    // Concatenate them all, and return the result.
    return csrHeaderAndPayload + "." + jwsSignature;
}

From source file:org.eclipse.orion.server.authentication.formopenid.FormOpenIdAuthenticationService.java

private void setNotAuthenticated(HttpServletRequest req, HttpServletResponse resp, Properties properties)
        throws IOException {
    resp.setHeader("WWW-Authenticate", HttpServletRequest.FORM_AUTH); //$NON-NLS-1$
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    // redirection from FormAuthenticationService.setNotAuthenticated
    String versionString = req.getHeader("Orion-Version"); //$NON-NLS-1$
    Version version = versionString == null ? null : new Version(versionString);

    // TODO: This is a workaround for calls
    // that does not include the WebEclipse version header
    String xRequestedWith = req.getHeader("X-Requested-With"); //$NON-NLS-1$

    if (version == null && !"XMLHttpRequest".equals(xRequestedWith)) { //$NON-NLS-1$
        resp.sendRedirect(/*from   www. j  a v  a2 s  .c  om*/
                req.getContextPath() + "/mixloginstatic/LoginWindow.html?redirect=" + req.getRequestURL());
    } else {
        resp.setContentType(ProtocolConstants.CONTENT_TYPE_JSON);
        JSONObject result = new JSONObject();
        try {
            result.put("SignInLocation", req.getContextPath() + "/mixloginstatic/LoginWindow.html");
            result.put("label", "Orion workspace server");
            result.put("SignInKey", "FORMOpenIdUser");
        } catch (JSONException e) {
            LogHelper.log(new Status(IStatus.ERROR, Activator.PI_AUTHENTICATION_SERVLETS, 1,
                    "An error occured during authenitcation", e));
        }
        resp.getWriter().print(result.toString());
    }
}

From source file:com.marpies.ane.facebook.accountkit.functions.SetPreferenceFunction.java

@Override
public FREObject call(FREContext context, FREObject[] args) {
    super.call(context, args);

    AIR.log("AccountKit::setPreference");
    final int callbackId = FREObjectUtils.getInt(args[2]);

    /* User is not logged in, cannot set preference */
    if (AccountKit.getCurrentAccessToken() == null) {
        dispatchError(callbackId, "User is not logged in, cannot set preference.");
        return null;
    }//from   w  w w .  j  a v  a2  s .  c  om

    String prefKey = FREObjectUtils.getString(args[0]);
    String prefValue = FREObjectUtils.getString(args[1]);

    AccountKit.getAccountPreferences().setPreference(prefKey, prefValue,
            new AccountPreferences.OnSetPreferenceListener() {
                @Override
                public void onSetPreference(String key, String value,
                        @Nullable AccountKitError accountKitError) {
                    if (accountKitError != null) {
                        dispatchError(callbackId, accountKitError.getErrorType().getMessage());
                    } else {
                        AIR.log("AccountKit | successfully set preference");
                        JSONObject response = new JSONObject();
                        JSONUtils.addToJSON(response, "callbackId", callbackId);
                        JSONUtils.addToJSON(response, "key", key);
                        JSONUtils.addToJSON(response, "value", value);
                        AIR.dispatchEvent(AccountKitEvent.SET_PREFERENCE, response.toString());
                    }
                }
            });

    return null;
}

From source file:com.microsoft.sharepointservices.ListClient.java

/**
 * Insert list item./*from   w ww  .  java  2s .com*/
 *
 * @param listItem the list item
 * @param list the list
 * @return the office future
 */
public ListenableFuture<Void> insertListItem(final SPListItem listItem, final SPList list) {
    final SettableFuture<Void> result = SettableFuture.create();

    String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/Items";
    getListUrl = String.format(getListUrl, urlEncode(list.getTitle()));

    try {
        JSONObject payload = new JSONObject();
        JSONObject metadata = new JSONObject();
        metadata.put("type", list.getListItemEntityTypeFullName());
        payload.put("__metadata", metadata);

        for (String key : listItem.getValues().keySet()) {

            Object object = listItem.getValues().get(key);
            // we assume you're trying to store a value on a linked
            // sharepoint list
            if (object instanceof JSONArray) {
                JSONObject container = new JSONObject();
                container.put("results", object);
                payload.put(key + "Id", container);
            } else {
                payload.put(key, object);
            }
        }

        ListenableFuture<JSONObject> request = executeRequestJsonWithDigest(getListUrl, "POST", null,
                getBytes(payload.toString()));

        Futures.addCallback(request, new FutureCallback<JSONObject>() {
            @Override
            public void onFailure(Throwable t) {
                result.setException(t);
            }

            @Override
            public void onSuccess(JSONObject json) {
                result.set(null);
            }
        });
    } catch (Throwable t) {
        result.setException(t);
    }

    return result;
}

From source file:com.microsoft.sharepointservices.ListClient.java

/**
 * Update list item.//w w w  .  java2  s.  c  om
 *
 * @param listItem the list item
 * @param list the list
 * @return the office future
 */
public ListenableFuture<Void> updateListItem(final SPListItem listItem, final SPList list) {
    final SettableFuture<Void> result = SettableFuture.create();

    String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/items(" + listItem.getId() + ")";
    getListUrl = String.format(getListUrl, urlEncode(list.getTitle()));

    try {
        JSONObject payload = new JSONObject();
        JSONObject metadata = new JSONObject();
        metadata.put("type", list.getListItemEntityTypeFullName());
        payload.put("__metadata", metadata);

        for (String key : listItem.getValues().keySet()) {
            Object object = listItem.getValues().get(key);
            // we assume you're trying to store a value on a linked
            // sharepoint list
            if (object instanceof JSONArray) {
                JSONObject container = new JSONObject();
                container.put("results", object);
                payload.put(key + "Id", container);
            } else {
                payload.put(key, object);
            }
        }

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("X-HTTP-Method", "MERGE");
        headers.put("If-Match", "*");

        ListenableFuture<JSONObject> request = executeRequestJsonWithDigest(getListUrl, "POST", headers,
                getBytes(payload.toString()));

        Futures.addCallback(request, new FutureCallback<JSONObject>() {
            @Override
            public void onFailure(Throwable t) {
                result.setException(t);
            }

            @Override
            public void onSuccess(JSONObject json) {
                result.set(null);
            }
        });
    } catch (JSONException e) {
        result.setException(e);
    }
    return result;
}

From source file:com.microsoft.sharepointservices.ListClient.java

/**
 * Gets user properties./*from www.j  a  va 2  s . c  o  m*/
 *
 * @return the user properties
 */
public ListenableFuture<String> getUserProperties() {
    final SettableFuture<String> result = SettableFuture.create();

    String url = getSiteUrl() + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";

    ListenableFuture<JSONObject> request = executeRequestJson(url, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            result.set(json.toString());
        }
    });
    return result;
}