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:com.apptentive.android.sdk.tests.model.ExtendedDataTests.java

public void testLocationExtendedData() {
    Log.e("testLocationExtendedData()");
    try {//from  w  w  w .ja v  a 2 s.c  o m
        JSONObject expected = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testLocationExtendedData.json"));

        LocationExtendedData actual = new LocationExtendedData(-122.34569190000002d, 47.6288591d);

        assertEquals(expected.toString(), actual.toString());
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.apptentive.android.sdk.tests.model.ExtendedDataTests.java

public void testTimeExtendedData() {
    Log.e("testTimeExtendedData()");
    try {/*from  w  w w . j a  va 2s . co m*/
        JSONObject expected = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testTimeExtendedData.json"));

        TimeExtendedData millis = new TimeExtendedData(1406251926165l);
        assertEquals(expected.toString(), millis.toString());

        TimeExtendedData seconds = new TimeExtendedData(1406251926.165);
        assertEquals(expected.toString(), seconds.toString());

        TimeExtendedData date = new TimeExtendedData(new Date(1406251926165l));
        assertEquals(expected.toString(), date.toString());
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.intel.iotkitlib.LibModules.AggregatedReportInterface.java

public String createBodyForAggregatedReportInterface() throws JSONException {
    JSONObject reportInterfaceJson = new JSONObject();
    if (this.msgType == null) {
        reportInterfaceJson.put("msgType", "aggregatedReportRequest");
    } else {/*from w w  w  .j  a va 2s. co m*/
        reportInterfaceJson.put("msgType", this.msgType);
    }
    reportInterfaceJson.put("offset", this.offset);
    reportInterfaceJson.put("limit", this.limit);
    if (this.countOnly) {
        reportInterfaceJson.put("countOnly", this.countOnly);
    }
    if (this.outputType != null) {
        reportInterfaceJson.put("outputType", this.outputType);
    }
    if (this.aggregationMethods != null) {
        JSONArray aggregationArray = new JSONArray();
        for (String aggregationMethod : this.aggregationMethods) {
            aggregationArray.put(aggregationMethod);
        }
        reportInterfaceJson.put("aggregationMethods", aggregationArray);
    }
    if (this.dimensions != null) {
        JSONArray dimensionArray = new JSONArray();
        for (String dimension : this.dimensions) {
            dimensionArray.put(dimension);
        }
        reportInterfaceJson.put("dimensions", dimensionArray);
    }
    if (this.gatewayIds != null) {
        JSONArray gatewayArray = new JSONArray();
        for (String gatewayId : this.gatewayIds) {
            gatewayArray.put(gatewayId);
        }
        reportInterfaceJson.put("gatewayIds", gatewayArray);
    }
    if (this.deviceIds != null) {
        JSONArray deviceIdArray = new JSONArray();
        for (String deviceId : this.deviceIds) {
            deviceIdArray.put(deviceId);
        }
        reportInterfaceJson.put("deviceIds", deviceIdArray);
    }
    if (this.componentIds != null) {
        JSONArray componentIdArray = new JSONArray();
        for (String componentId : this.componentIds) {
            componentIdArray.put(componentId);
        }
        reportInterfaceJson.put("componentIds", componentIdArray);
    }
    reportInterfaceJson.put("startTimestamp", this.startTimestamp);
    reportInterfaceJson.put("endTimestamp", this.endTimestamp);
    //sort
    if (this.sort != null) {
        JSONArray sortArray = new JSONArray();
        for (NameValuePair nameValuePair : this.sort) {
            JSONObject nameValueJson = new JSONObject();
            nameValueJson.put(nameValuePair.getName(), nameValuePair.getValue());
            sortArray.put(nameValueJson);
        }
        reportInterfaceJson.put("sort", sortArray);
    }
    if (this.filters != null) {
        JSONObject filterJson = new JSONObject();
        for (AttributeFilter attributeFilter : this.filters.filterData) {
            JSONArray filterValuesArray = new JSONArray();
            for (String filterValue : attributeFilter.filterValues) {
                filterValuesArray.put(filterValue);
            }
            filterJson.put(attributeFilter.filterName, filterValuesArray);
        }
        reportInterfaceJson.put("filters", filterJson);
    }
    return reportInterfaceJson.toString();
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process Get claims request/* w  ww. j  ava 2s  . c o m*/
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetClaimsRequest(Channel channel, JSONObject requestObj) throws UserStoreException {

    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get claims for user: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME));
    }

    String username = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME);
    String claims = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_CLAIMS);
    String[] claimArray = claims.split(CommonConstants.ATTRIBUTE_LIST_SEPERATOR);
    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();

    Map<String, String> propertyMap = userStoreManager.getUserClaimValues(username, claimArray);
    JSONObject returnObject = new JSONObject(propertyMap);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Claims retrieval completed. User: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME) + " claims: "
                + propertyMap.toString());
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            returnObject.toString());
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process get user roles request/*  ww  w  . j ava 2 s  . co  m*/
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetUserRolesRequest(Channel channel, JSONObject requestObj) throws UserStoreException {
    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get user roles for user: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME));
    }
    String username = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME);

    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();
    String[] roles = userStoreManager.doGetExternalRoleListOfUser(username);
    JSONObject jsonObject = new JSONObject();
    JSONArray usernameArray = new JSONArray(roles);
    jsonObject.put("groups", usernameArray);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("User roles retrieval completed. User: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME) + " roles: "
                + Arrays.toString(roles));
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            jsonObject.toString());
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process get roles request//from ww w  .  j  a v a2s.  c  o m
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetRolesRequest(Channel channel, JSONObject requestObj) throws UserStoreException {
    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get roles.");
    }
    int limit = requestData.getInt(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_ROLE_LIMIT);

    if (limit == 0) {
        limit = CommonConstants.MAX_USER_LIST;
    }
    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();
    String[] roleNames = userStoreManager.doGetRoleNames("*", limit);
    JSONObject returnObject = new JSONObject();
    JSONArray usernameArray = new JSONArray(roleNames);
    returnObject.put("groups", usernameArray);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Roles retrieval completed.");
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            returnObject.toString());
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process get roles request//w ww  .j ava 2 s .c o  m
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetUsersListRequest(Channel channel, JSONObject requestObj) throws UserStoreException {
    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get users");
    }

    int limit = requestData.getInt(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_USER_LIMIT);
    String filter = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_USER_FILTER);

    if (limit == 0) {
        limit = CommonConstants.MAX_USER_LIST;
    }
    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();
    String[] roleNames = userStoreManager.doListUsers(filter, limit);
    JSONObject returnObject = new JSONObject();
    JSONArray usernameArray = new JSONArray(roleNames);
    returnObject.put("usernames", usernameArray);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Users list retrieval completed.");
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            returnObject.toString());
}

From source file:jcan2.TrackOrganiser.java

/**
 * Prepares a String containing all the data.
 * @return JSONString/*  w w  w  .j a v  a2  s.  c  om*/
 * @throws JSONException 
 */
public JSONObject prepareJSONtoExport() throws JSONException {

    //this will be the object that contains all the data layers.
    JSONObject trackArr = new JSONObject();

    //loop through all data layers and add them into a JSONArray
    Iterator<Data> it = trackList.iterator();
    while (it.hasNext()) {
        if (TRACK_DEBUG)
            BeMapEditor.mainWindow.append("\nNew Layer");
        Data d = it.next();
        //don't export the global layer
        if (d.getID() != 0) {
            trackArr.put(d.getLayerName(), d.exportJSONList());
        }
    }

    JSONObject usrObj = new JSONObject();
    usrObj.put(BeMapEditor.mainWindow.getUsrString(), trackArr);
    if (TRACK_DEBUG)
        BeMapEditor.mainWindow.append(usrObj.toString());
    return usrObj;
}

From source file:jcan2.TrackOrganiser.java

/**
 * Prepares a String containing all the data, for export to server (only 
 * data from the public layer)/*from  w  ww. j ava 2  s  .c o m*/
 * @return JSONString
 * @throws JSONException 
 */
public JSONObject JSONExportPublic() throws JSONException {

    //this will be the object that contains all the data layers.
    JSONObject trackArr = new JSONObject();

    Data layer = trackList.get(PUBLIC);
    trackArr.put(layer.getLayerName(), layer.exportJSONListServer());

    JSONObject usrObj = new JSONObject();
    usrObj.put(BeMapEditor.mainWindow.getUsrString(), trackArr);
    if (TRACK_DEBUG)
        BeMapEditor.mainWindow.append(usrObj.toString());
    return usrObj;
}

From source file:com.facebook.share.ShareApi.java

private void stageOpenGraphObject(final ShareOpenGraphObject object,
        final CollectionMapper.OnMapValueCompleteListener onOpenGraphObjectStagedListener) {
    String type = object.getString("type");
    if (type == null) {
        type = object.getString("og:type");
    }//from   ww  w  .  j ava 2  s  . c  om

    if (type == null) {
        onOpenGraphObjectStagedListener
                .onError(new FacebookException("Open Graph objects must contain a type value."));
        return;
    }
    final JSONObject stagedObject = new JSONObject();
    final CollectionMapper.Collection<String> collection = new CollectionMapper.Collection<String>() {
        @Override
        public Iterator<String> keyIterator() {
            return object.keySet().iterator();
        }

        @Override
        public Object get(String key) {
            return object.get(key);
        }

        @Override
        public void set(String key, Object value, CollectionMapper.OnErrorListener onErrorListener) {
            try {
                stagedObject.put(key, value);
            } catch (final JSONException ex) {
                String message = ex.getLocalizedMessage();
                if (message == null) {
                    message = "Error staging object.";
                }
                onErrorListener.onError(new FacebookException(message));
            }
        }
    };
    final GraphRequest.Callback requestCallback = new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            final FacebookRequestError error = response.getError();
            if (error != null) {
                String message = error.getErrorMessage();
                if (message == null) {
                    message = "Error staging Open Graph object.";
                }
                onOpenGraphObjectStagedListener.onError(new FacebookGraphResponseException(response, message));
                return;
            }
            final JSONObject data = response.getJSONObject();
            if (data == null) {
                onOpenGraphObjectStagedListener.onError(
                        new FacebookGraphResponseException(response, "Error staging Open Graph object."));
                return;
            }
            final String stagedObjectId = data.optString("id");
            if (stagedObjectId == null) {
                onOpenGraphObjectStagedListener.onError(
                        new FacebookGraphResponseException(response, "Error staging Open Graph object."));
                return;
            }
            onOpenGraphObjectStagedListener.onComplete(stagedObjectId);
        }
    };
    final String ogType = type;
    final CollectionMapper.OnMapperCompleteListener onMapperCompleteListener = new CollectionMapper.OnMapperCompleteListener() {
        @Override
        public void onComplete() {
            final String objectString = stagedObject.toString();
            final Bundle parameters = new Bundle();
            parameters.putString("object", objectString);
            try {
                new GraphRequest(AccessToken.getCurrentAccessToken(),
                        getGraphPath("objects/" + URLEncoder.encode(ogType, DEFAULT_CHARSET)), parameters,
                        HttpMethod.POST, requestCallback).executeAsync();
            } catch (final UnsupportedEncodingException ex) {
                String message = ex.getLocalizedMessage();
                if (message == null) {
                    message = "Error staging Open Graph object.";
                }
                onOpenGraphObjectStagedListener.onError(new FacebookException(message));
            }
        }

        @Override
        public void onError(FacebookException exception) {
            onOpenGraphObjectStagedListener.onError(exception);
        }
    };
    stageCollectionValues(collection, onMapperCompleteListener);
}