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:eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask.java

private String createDesignDocument(String docType) {
    String returnResult = "";
    JSONObject docTypeMap = new JSONObject();
    try {/*from  w  w w  .j  a  va2 s . co  m*/
        docTypeMap.put("map", "function (doc) { if (doc.docType.toLowerCase() === '" + docType
                + "') { filter = function (doc) { return emit(doc._id, doc); }; filter(doc); }}");

        URL urlO = getCosiUrl(docType);

        String 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
        OutputStream os = conn.getOutputStream();
        os.write(docTypeMap.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();

        if (result.contains("success")) {
            returnResult = "";
        } else {
            returnResult = result;
        }

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

    } catch (UnsupportedEncodingException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (ProtocolException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return returnResult;
}

From source file:de.joinout.criztovyl.tools.json.JSONFile.java

/**
 * Loads the JSON data from the {@link JSONObject}.
 * //w  ww . j a  v  a  2 s .com
 * @param path
 *            the path to the JSON file
 * @param json
 *            the JSON object
 */
public JSONFile(Path path, JSONObject json) {

    logger = LogManager.getLogger();

    this.path = path;
    data = json.toString();
}

From source file:de.joinout.criztovyl.tools.json.JSONFile.java

public JSONFile setData(JSONObject json) {
    data = json.toString();

    return this;
}

From source file:com.ss.android.apker.volley.toolbox.JsonArrayRequest.java

/**
 * Creates a new request./*from   ww w. j  a  v  a2s  . c o  m*/
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonArrayRequest(Context context, int method, String url, JSONObject jsonRequest,
        Listener<JSONArray> listener, ErrorListener errorListener) {
    super(context, method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private void writeFingerprintsToCache(String domain, List<String> results, long expires) {
    File file = getPoshCacheFile(domain);
    file.getParentFile().mkdirs();//from  w  ww. j av a 2  s . co m
    try {
        file.createNewFile();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expires", expires);
        jsonObject.put("fingerprints", new JSONArray(results));
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(jsonObject.toString().getBytes());
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java

/**
 * Positive test case for echo method with mandatory parameters.
 *///from www  .  j  a  va 2s .  c o m
@Test(priority = 1, groups = {
        "wso2.esb" }, description = "flickr {echo} integration test with mandatory parameters")
public void testFlickrEchoWithMandatoryParameters() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "flickr_echo.txt";
    String methodName = "flickr_echo";

    final String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String jsonString = addCredentials(rawString);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";

    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {
        JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST",
                getProxyServiceURL(methodName), jsonString);

        String httpMethod = "GET";
        String parameters = "format=json&nojsoncallback=1&method=flickr.test.echo&api_key="
                + flickrConnectorProperties.getProperty("consumerKey") + "&value=wso2-esb";
        JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(false, httpMethod, parameters,
                flickrConnectorProperties);
        Assert.assertTrue(responseConnector.toString().equals(responseDirect.toString()));
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java

/**
 * Positive test case for isLogged method with mandatory parameters.
 *//*w w w.j  a v a 2 s .  co m*/
@Test(priority = 1, groups = {
        "wso2.esb" }, description = "flickr {isLogged} integration test with mandatory parameters.")
public void testFlickrIsLoggedWithMandatoryParameters() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "flickr_isLogged.txt";
    String methodName = "flickr_isLogged";

    final String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String jsonString = addCredentials(rawString);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";

    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {
        JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST",
                getProxyServiceURL(methodName), jsonString);

        String httpMethod = "GET";
        String parameters = "format=json" + "&method=flickr.test.login" + "&nojsoncallback=1"
                + "&oauth_consumer_key=" + flickrConnectorProperties.getProperty("consumerKey")
                + "&oauth_nonce=dummynonce" + "&oauth_signature_method=HMAC-SHA1"
                + "&oauth_timestamp=dummytimestamp" + "&oauth_token="
                + flickrConnectorProperties.getProperty("accessToken") + "&oauth_version=1.0";
        JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(true, httpMethod, parameters,
                flickrConnectorProperties);
        Assert.assertTrue(responseConnector.toString().equals(responseDirect.toString()));
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java

/**
 * Positive test case for addComment method with mandatory parameters.
 *//*from   www. j a  v a2  s  .  c  o m*/
@Test(priority = 1, groups = {
        "wso2.esb" }, description = "flickr {addComment} integration test with mandatory parameters")
public void testFlickrAddCommentWithMandatoryParameters() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "flickr_addComment.txt";
    String methodName = "flickr_addComment";

    String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    rawString = rawString.replace("dummyvalue", flickrConnectorProperties.getProperty("photoId"));
    final String jsonString = addCredentials(rawString);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";

    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {
        JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST",
                getProxyServiceURL(methodName), jsonString);

        String httpMethod = "GET";
        String parameters = "format=json&nojsoncallback=1&method=flickr.photos.comments.getList&api_key="
                + flickrConnectorProperties.getProperty("consumerKey") + "&photo_id="
                + flickrConnectorProperties.getProperty("photoId");
        JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(false, httpMethod, parameters,
                flickrConnectorProperties);

        String commentIdConnector = responseConnector.getJSONObject("comment").getString("id");
        addCommentMethodCommentId = commentIdConnector; //keeping the comment id to be used in deleteComment method.
        Assert.assertTrue(responseDirect.toString().contains(commentIdConnector));
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java

/**
 * Positive test case for getCommentsList method with mandatory parameters.
 */// w w w . j  av a2 s .com
@Test(priority = 1, groups = {
        "wso2.esb" }, description = "flickr {getCommentsList} integration test with mandatory parameters")
public void testFlickrGetCommentsListWithMandatoryParameters() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "flickr_getCommentList.txt";
    String methodName = "flickr_getCommentList";

    String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    rawString = rawString.replace("dummyvalue", flickrConnectorProperties.getProperty("photoId"));
    final String jsonString = addCredentials(rawString);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";

    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {
        JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST",
                getProxyServiceURL(methodName), jsonString);

        String httpMethod = "GET";
        String parameters = "format=json&nojsoncallback=1&method=flickr.photos.comments.getList&api_key="
                + flickrConnectorProperties.getProperty("consumerKey") + "&photo_id="
                + flickrConnectorProperties.getProperty("photoId");
        JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(false, httpMethod, parameters,
                flickrConnectorProperties);
        Assert.assertTrue(responseDirect.toString().equals(responseConnector.toString()));
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java

/**
 * Positive test case for editComment method with mandatory parameters.
 *///from w w  w .  j  a v a 2s  . c  om
@Test(dependsOnMethods = { "testFlickrAddCommentWithMandatoryParameters" }, priority = 1, groups = {
        "wso2.esb" }, description = "flickr {editComment} integration test with mandatory parameters")
public void testFlickrEditCommentWithMandatoryParameters() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "flickr_editComment.txt";
    String methodName = "flickr_editComment";

    String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    rawString = rawString.replace("dummyvalue", addCommentMethodCommentId);
    String comment = flickrConnectorProperties.getProperty("comment") + System.currentTimeMillis();
    rawString = rawString.replace("dummycomment", comment);
    final String jsonString = addCredentials(rawString);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";

    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {
        JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST",
                getProxyServiceURL(methodName), jsonString);

        String httpMethod = "GET";
        String parameters = "format=json&nojsoncallback=1&method=flickr.photos.comments.getList&api_key="
                + flickrConnectorProperties.getProperty("consumerKey") + "&photo_id="
                + flickrConnectorProperties.getProperty("photoId");
        JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(false, httpMethod, parameters,
                flickrConnectorProperties);
        Assert.assertTrue(responseDirect.toString().contains(comment));
    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}