Example usage for org.json JSONArray toString

List of usage examples for org.json JSONArray toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONArray.

Usage

From source file:com.facebook.stetho.inspector.ChromeDiscoveryHandler.java

private void handlePageList(HttpResponse response) throws JSONException, UnsupportedEncodingException {
    if (mPageListResponse == null) {
        JSONArray reply = new JSONArray();
        JSONObject page = new JSONObject();
        page.put("type", "app");
        page.put("title", makeTitle());
        page.put("id", PAGE_ID);
        page.put("description", "");

        page.put("webSocketDebuggerUrl", "ws://" + mInspectorPath);
        Uri chromeFrontendUrl = new Uri.Builder().scheme("http")
                .authority("chrome-devtools-frontend.appspot.com").appendEncodedPath("serve_rev")
                .appendEncodedPath(WEBKIT_REV).appendEncodedPath("devtools.html")
                .appendQueryParameter("ws", mInspectorPath).build();
        page.put("devtoolsFrontendUrl", chromeFrontendUrl.toString());

        reply.put(page);//  w ww.ja v a2 s.  c om
        mPageListResponse = createStringEntity("application/json", reply.toString());
    }
    setSuccessfulResponse(response, mPageListResponse);
}

From source file:se.altrusoft.alfplay.node.NodeFreeTextQueryPost.java

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {

    // Read query string from JSON request body...
    JSONReader requestReader = new JSONReader();
    Object jsonRequest = requestReader.read(req);
    JSONObject jsonObjectRequest = (JSONObject) jsonRequest;
    String queryString = null;/*from w  w w.j  a  v a 2s  . c o  m*/
    String queryPath = null;
    try {
        queryString = (String) jsonObjectRequest.get("queryString");
        queryPath = (String) jsonObjectRequest.get("queryPath");
    } catch (JSONException e1) {
        throw new WebScriptException("Unable to find someParam in JSON body");
    }

    // Free text search follows...
    if (queryString != null) {
        SearchParameters sp = new SearchParameters();
        sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(
                "+ALL:\"" + queryString + "\"" + ((queryPath == null) ? "" : " +PATH:\"" + queryPath + "\""));

        ResultSet results = null;
        try {
            results = serviceRegistry.getSearchService().query(sp);

            // Put search result into JSON result structure...
            JSONArray jSONResult = new JSONArray();
            for (ResultSetRow row : results) {
                NodeRef currentNodeRef = row.getNodeRef();
                jSONResult.put(currentNodeRef.getId());
            }
            String jsonString = jSONResult.toString();
            res.getWriter().write(jsonString);
        } finally {
            if (results != null) {
                results.close();
            }
        }
    }
}

From source file:org.wso2.iot.agent.proxy.APIController.java

private void sendJsonArrayRequest(final APIResultCallBack callBack, final EndPointInfo apiUtilities,
        final boolean isSecured) {
    RequestQueue queue = null;/*from   w  ww. j  a v  a2 s  .co m*/
    try {
        queue = ServerUtilities.getCertifiedHttpClient();
    } catch (IDPTokenManagerException e) {
        Log.e(TAG, "Failed to retrieve HTTP client", e);
    }

    JsonArrayRequest request = null;
    try {
        request = new JsonArrayRequest(requestMethod, apiUtilities.getEndPoint(),
                (apiUtilities.getRequestParams() != null) ? new JSONArray(apiUtilities.getRequestParams())
                        : null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, error.toString());
                    }
                })

        {
            @Override
            protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
                String result = new String(response.data);
                if (Constants.DEBUG_ENABLED) {
                    if (result != null && !result.isEmpty()) {
                        Log.d(TAG, "Result :" + result);
                    }
                }
                Map<String, String> responseParams = new HashMap<>();
                responseParams.put(Constants.SERVER_RESPONSE_BODY, result);
                responseParams.put(Constants.SERVER_RESPONSE_STATUS, String.valueOf(response.statusCode));
                callBack.onReceiveAPIResult(responseParams, IdentityProxy.getInstance().getRequestCode());
                return super.parseNetworkResponse(response);
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Accept", "*/*");
                headers.put("User-Agent", "Mozilla/5.0 ( compatible ), Android");
                if (!isSecured) {
                    String accessToken = getToken().getAccessToken();
                    headers.put("Authorization", "Bearer " + accessToken);
                }
                ServerUtilities.addHeaders(headers);
                return headers;
            }
        };
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse request JSON", e);
    }

    request.setRetryPolicy(new DefaultRetryPolicy(Constants.HttpClient.DEFAULT_TIME_OUT,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(request);
}

From source file:utils.tour.Tour.java

/**
 * Get the steps as a json array.//  w  w  w  . j a v a  2  s.c  o  m
 */
public String renderSteps() {

    JSONArray json = new JSONArray();

    Integer index = 0;
    for (Step step : steps) {
        Step previous = index != 0 ? steps.get(index - 1) : null;
        Step next = index != steps.size() - 1 ? steps.get(index + 1) : null;
        json.put(step.render(this.uid, index, previous, next));
        index++;
    }

    // remove the quotes for anonymous functions
    String r = json.toString();
    r = r.replaceAll("\"onNext\":\"(.*?)\"", "\"onNext\":$1");
    r = r.replaceAll("\"onPrev\":\"(.*?)\"", "\"onPrev\":$1");

    return r;

}

From source file:com.pimp.companionforband.fragments.cloud.ProfileFragment.java

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    profileTV = (TextView) view.findViewById(R.id.profile_textview);
    devicesTV = (TextView) view.findViewById(R.id.devices_textview);

    RequestQueue queue = Volley.newRequestQueue(getContext());

    JsonObjectRequest profileRequest = new JsonObjectRequest(Request.Method.GET,
            CloudConstants.BASE_URL + CloudConstants.Profile_URL, null, new Response.Listener<JSONObject>() {
                @Override/* www  .  j a  v a 2s . c o m*/
                public void onResponse(JSONObject response) {
                    JsonFlattener parser = new JsonFlattener();
                    CSVWriter writer = new CSVWriter();
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                    try {
                        List<LinkedHashMap<String, String>> flatJson = parser.parseJson(response.toString());
                        writer.writeAsCSV(flatJson,
                                path + File.separator + "CompanionForBand" + File.separator + "profile.csv");
                    } catch (Exception e) {
                        Log.e("profileFragParseJson", e.toString());
                    }

                    Iterator<String> stringIterator = response.keys();
                    while (stringIterator.hasNext()) {
                        try {
                            String key = stringIterator.next();
                            profileTV.append(UIUtils.splitCamelCase(key) + " : ");
                            profileTV.append(response.get(key).toString() + "\n\n");
                        } catch (Exception e) {
                            profileTV.append(e.toString());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    profileTV.setText(error.getMessage());
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization",
                    "Bearer " + MainActivity.sharedPreferences.getString("access_token", "hi"));

            return headers;
        }
    };

    JsonObjectRequest devicesRequest = new JsonObjectRequest(Request.Method.GET,
            CloudConstants.BASE_URL + CloudConstants.Devices_URL, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Iterator<String> stringIterator = response.keys();
                    while (stringIterator.hasNext()) {
                        try {
                            String key = stringIterator.next();
                            if (key.equals("deviceProfiles")) {
                                JSONArray jsonArray = response.getJSONArray("deviceProfiles");

                                JsonFlattener parser = new JsonFlattener();
                                CSVWriter writer = new CSVWriter();
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                                try {
                                    List<LinkedHashMap<String, String>> flatJson = parser
                                            .parseJson(jsonArray.toString());
                                    writer.writeAsCSV(flatJson, path + File.separator + "CompanionForBand"
                                            + File.separator + "devices.csv");
                                } catch (Exception e) {
                                    Log.e("profileDevicesParseJson", e.toString());
                                }

                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject device = jsonArray.getJSONObject(i);
                                    Iterator<String> iterator = device.keys();
                                    while (iterator.hasNext()) {
                                        key = iterator.next();
                                        devicesTV.append(UIUtils.splitCamelCase(key) + " : ");
                                        devicesTV.append(device.get(key).toString() + "\n");
                                    }
                                    devicesTV.append("\n\n");
                                }
                            } else {
                                devicesTV.append(UIUtils.splitCamelCase(key) + " : ");
                                devicesTV.append(response.get(key).toString() + "\n\n");
                            }
                        } catch (Exception e) {
                            devicesTV.append(e.toString());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    devicesTV.setText(error.getMessage());
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization",
                    "Bearer " + MainActivity.sharedPreferences.getString("access_token", "hi"));

            return headers;
        }
    };

    queue.add(profileRequest);
    queue.add(devicesRequest);
}

From source file:net.zorgblub.typhon.Configuration.java

public void storeCustomOPDSSites(List<CustomOPDSSite> sites) {

    try {/*from  www.  j  a  v a2s  . c o m*/
        JSONArray array = new JSONArray();
        for (CustomOPDSSite site : sites) {
            array.put(site.toJSON());
        }

        updateValue(KEY_OPDS_SITES, array.toString());
    } catch (JSONException js) {
        LOG.error("Error storing custom sites", js);
    }
}

From source file:de.kp.ames.web.function.domain.model.JsonProductor.java

public void set(RegistryObjectImpl ro, Locale locale) throws JSONException, JAXRException {

    /*/*from   w w w. j  a  v a2 s. c o  m*/
     * Convert registry object
     */
    super.set(ro, locale);

    /*
     * Convert productor specific information
     */
    ServiceImpl productor = (ServiceImpl) ro;

    /*
     * Convert specifications
     */
    JSONArray jArray = getSpecifications(productor);
    put(JaxrConstants.RIM_SPEC, jArray.toString());

    /*
     * Convert icon
     */
    put(JaxrConstants.RIM_ICON, IconConstants.SERVICE);

}

From source file:com.ecml.ChooseSongActivity.java

/** Save the given FileUri into the "recentFiles" preferences.
 *  Save a maximum of 10 recent files.//ww  w .  j  ava2s .  c o m
 */
public void updateRecentFile(FileUri recentfile) {
    try {
        SharedPreferences settings = getSharedPreferences("midisheetmusic.recentFiles", 0);
        SharedPreferences.Editor editor = settings.edit();
        JSONArray prevRecentFiles = null;
        String recentFilesString = settings.getString("recentFiles", null);
        if (recentFilesString != null) {
            prevRecentFiles = new JSONArray(recentFilesString);
        } else {
            prevRecentFiles = new JSONArray();
        }
        JSONArray recentFiles = new JSONArray();
        JSONObject recentFileJson = recentfile.toJson();
        recentFiles.put(recentFileJson);
        for (int i = 0; i < prevRecentFiles.length(); i++) {
            if (i >= 10) {
                break; // only store the 10 most recent files
            }
            JSONObject file = prevRecentFiles.getJSONObject(i);
            if (!FileUri.equalJson(recentFileJson, file)) {
                recentFiles.put(file);
            }
        }
        editor.putString("recentFiles", recentFiles.toString());
        editor.commit();
    } catch (Exception e) {
    }
}

From source file:com.fabernovel.alertevoirie.webservice.AVService.java

public void postJSON(JSONArray json, RequestListener listener) {
    this.listener = listener;
    Log.d("AlerteVoirie_PM", "request : " + json);
    cancelTask();//  w ww.  j a  v  a  2 s.co m
    currentTask = new QueryTask().execute(json.toString(), AV_URL);
}

From source file:org.ohmage.request.mobility.MobilityUploadRequest.java

/**
 * Creates a Mobility upload request./*w  w  w . j av a2s .c  o  m*/
 * 
 * @param httpRequest A HttpServletRequest that contains the parameters for
 *                  this request.
 * 
 * @throws InvalidRequestException Thrown if the parameters cannot be 
 *                            parsed.
 * 
 * @throws IOException There was an error reading from the request.
 */
public MobilityUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException {
    super(httpRequest, null);

    LOGGER.info("Creating a Mobility upload request.");

    validIds = new LinkedList<String>();
    invalidPointsMap = new HashMap<Integer, String>();
    invalidPointsJson = new LinkedList<JSONObject>();

    StreamUploadRequest tStreamUploadRequest = null;

    if (!isFailed()) {
        try {
            String[] dataArray = getParameterValues(InputKeys.DATA);
            if (dataArray.length == 0) {
                throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                        "The upload data is missing: " + ErrorCode.MOBILITY_INVALID_DATA);
            } else if (dataArray.length > 1) {
                throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                        "Multiple data parameters were given: " + ErrorCode.MOBILITY_INVALID_DATA);
            } else {
                JSONArray jsonDataArray;
                try {
                    jsonDataArray = new JSONArray(dataArray[0]);
                } catch (JSONException e) {
                    throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                            "The data is not well formed.", e);
                }

                JSONArray resultDataArray = new JSONArray();
                for (int i = 0; i < jsonDataArray.length(); i++) {
                    JSONObject pointJson;
                    try {
                        pointJson = jsonDataArray.getJSONObject(i);
                    } catch (JSONException e) {
                        throw new ValidationException(ErrorCode.MOBILITY_INVALID_DATA,
                                "A Mobility data point was not a JSON object.", e);
                    }

                    MobilityPoint point;
                    try {
                        point = new MobilityPoint(pointJson, MobilityPoint.PrivacyState.PRIVATE);
                    } catch (DomainException e) {
                        invalidPointsMap.put(i, e.getMessage());
                        invalidPointsJson.add(pointJson);
                        continue;
                    }

                    validIds.add(point.getId().toString());

                    try {
                        JSONObject jsonPoint = new JSONObject();
                        if (MobilityPoint.Mode.ERROR.equals(point.getMode())) {
                            jsonPoint.put("stream_id", "error");

                            // Create the error object.
                            JSONObject errorObject = new JSONObject();
                            errorObject.put("mode", MobilityPoint.Mode.ERROR.toString().toLowerCase());

                            jsonPoint.put("data", errorObject);
                            jsonPoint.put("stream_version", 2012061300);
                        } else if (MobilityPoint.SubType.MODE_ONLY.equals(point.getSubType())) {
                            jsonPoint.put("stream_id", "mode_only");

                            // Create the mode object.
                            JSONObject modeObject = new JSONObject();
                            modeObject.put("mode", point.getMode().toString());

                            jsonPoint.put("data", modeObject);
                            jsonPoint.put("stream_version", 2012050700);
                        } else {
                            jsonPoint.put("stream_id", "extended");

                            // Add the sensor data and rename it to "data".
                            Collection<ColumnKey> columns = new LinkedList<ColumnKey>();
                            columns.add(MobilityColumnKey.SENSOR_DATA);
                            JSONObject mobilityJson;
                            try {
                                mobilityJson = point.toJson(false, columns);
                            } catch (DomainException e) {
                                throw new ValidationException(
                                        "The point could not be converted back to a JSON object.", e);
                            }
                            jsonPoint.put("data", mobilityJson.getJSONObject("sensor_data"));
                            jsonPoint.put("stream_version", 2012050700);
                        }

                        JSONObject metadata = new JSONObject();
                        metadata.put("id", point.getId().toString());
                        metadata.put("time", point.getTime());
                        metadata.put("timezone", point.getTimezone().getID());

                        Location location = point.getLocation();
                        if (location != null) {
                            try {
                                metadata.put("location", location.toJson(false, LocationColumnKey.ALL_COLUMNS));
                            } catch (DomainException e) {
                                throw new ValidationException(
                                        "The location could not be converted back to a JSON object.", e);
                            }
                        }
                        jsonPoint.put("metadata", metadata);

                        resultDataArray.put(jsonPoint);
                    } catch (JSONException e) {
                        throw new ValidationException("The stream information could not be built.", e);
                    }
                }

                tStreamUploadRequest = new StreamUploadRequest(httpRequest, getParameterMap(), OBSERVER_ID,
                        OBSERVER_VERSION, resultDataArray.toString(), false);
            }
        } catch (ValidationException e) {
            e.failRequest(this);
            e.logException(LOGGER);
        }
    }

    streamUploadRequest = tStreamUploadRequest;
}