Example usage for com.google.gson JsonObject toString

List of usage examples for com.google.gson JsonObject toString

Introduction

In this page you can find the example usage for com.google.gson JsonObject toString.

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.claresco.tinman.json.XapiJsonControl.java

License:Open Source License

public String createKeySecretJson(XapiKeySecret theKeySecret) {
    JsonObject theKeySecretJson = new JsonObject();

    // Send client's login and password as a JSON
    theKeySecretJson.addProperty("login", theKeySecret.getKey());
    theKeySecretJson.addProperty("password", theKeySecret.getSecret());

    return theKeySecretJson.toString();
}

From source file:com.cloopen.rest.sdk.CCPRestSDK.java

License:Open Source License

/**
 * ???//from  w  w w.  j ava2s . c om
 * 
 * @param verifyCode
 *            ? ?????4-8?
 * @param to
 *            ? ??
 * @param displayNum
 *            ?? ??????
 * @param playTimes
 *            ?? 1?31
 * @param respUrl
 *            ?? ??????Url????
 * @param lang
 *            ?? 
 * @param userData
 *            ?? ??
 * @param welcomePrompt
 *            ?? ??????wav           
 * @param playVerifyCode
 *            ?? ??
 * @return
 */
public HashMap<String, Object> voiceVerify(String verifyCode, String to, String displayNum, String playTimes,
        String respUrl, String lang, String userData, String welcomePrompt, String playVerifyCode) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if ((isEmpty(verifyCode)) || (isEmpty(to)))
        throw new IllegalArgumentException("?:" + (isEmpty(verifyCode) ? " ?? " : "")
                + (isEmpty(to) ? " ?? " : "") + "");
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, VoiceVerify);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("verifyCode", verifyCode);
            json.addProperty("to", to);
            if (!(isEmpty(displayNum)))
                json.addProperty("displayNum", displayNum);

            if (!(isEmpty(playTimes)))
                json.addProperty("playTimes", playTimes);

            if (!(isEmpty(respUrl)))
                json.addProperty("respUrl", respUrl);
            if (!(isEmpty(lang)))
                json.addProperty("lang", lang);
            if (!(isEmpty(userData)))
                json.addProperty("userData", userData);
            if (!(isEmpty(welcomePrompt)))
                json.addProperty("welcomePrompt", welcomePrompt);
            if (!(isEmpty(playVerifyCode)))
                json.addProperty("playVerifyCode", playVerifyCode);

            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><VoiceVerify>");
            sb.append("<appId>").append(App_ID).append("</appId>").append("<verifyCode>").append(verifyCode)
                    .append("</verifyCode>").append("<to>").append(to).append("</to>");
            if (!(isEmpty(displayNum)))
                sb.append("<displayNum>").append(displayNum).append("</displayNum>");

            if (!(isEmpty(playTimes)))
                sb.append("<playTimes>").append(playTimes).append("</playTimes>");

            if (!(isEmpty(respUrl)))
                sb.append("<respUrl>").append(respUrl).append("</respUrl>");
            if (!(isEmpty(lang)))
                sb.append("<lang>").append(lang).append("</lang>");
            if (!(isEmpty(userData)))
                sb.append("<userData>").append(userData).append("</userData>");
            if (!(isEmpty(welcomePrompt)))
                sb.append("<welcomePrompt>").append(welcomePrompt).append("</welcomePrompt>");
            if (!(isEmpty(playVerifyCode)))
                sb.append("<playVerifyCode>").append(playVerifyCode).append("</playVerifyCode>");

            sb.append("</VoiceVerify>").toString();
            requsetbody = sb.toString();
        }

        LoggerUtil.info("voiceVerify Request body = : " + requsetbody);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8")));
        requestBody.setContentLength(requsetbody.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            result = EntityUtils.toString(entity, "UTF-8");

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }

    LoggerUtil.info("voiceVerify response body = " + result);

    try {
        if (BODY_TYPE == BodyType.Type_JSON) {
            return jsonToMap(result);
        } else {
            return xmlToMap(result);
        }
    } catch (Exception e) {

        return getMyError("172003", "");
    }
}

From source file:com.cloudant.client.api.CloudantClient.java

License:Open Source License

Response put(URI uri, Object object, boolean newEntity, int writeQuorum, Gson gson) {
    assertNotEmpty(object, "object");
    HttpResponse response = null;/* w w w .  j  ava 2  s.  c o m*/
    try {
        final JsonObject json = gson.toJsonTree(object).getAsJsonObject();
        String id = CouchDbUtil.getAsString(json, "_id");
        String rev = CouchDbUtil.getAsString(json, "_rev");
        if (newEntity) { // save
            CouchDbUtil.assertNull(rev, "rev");
            id = (id == null) ? CouchDbUtil.generateUUID() : id;
        } else { // update
            assertNotEmpty(id, "id");
            assertNotEmpty(rev, "rev");
        }
        final HttpPut put = new HttpPut(buildUri(uri).pathToEncode(id).query("w", writeQuorum).buildEncoded());
        CouchDbUtil.setEntity(put, json.toString(), "application/json");
        response = client.executeRequest(put);
        return CouchDbUtil.getResponse(response, Response.class, gson);
    } finally {
        close(response);
    }
}

From source file:com.cloudant.client.api.DatabaseImpl.java

License:Open Source License

@Override
public void createIndex(String indexName, String designDocName, String indexType, IndexField[] fields) {
    JsonObject indexDefn = getIndexDefinition(indexName, designDocName, indexType, fields);
    createIndex(indexDefn.toString());
}

From source file:com.cloudant.client.api.DatabaseImpl.java

License:Open Source License

@Override
public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT, FindByIndexOptions options) {
    assertNotEmpty(selectorJson, "selectorJson");
    assertNotEmpty(options, "options");

    URI uri = new DatabaseURIHelper(db.getDBUri()).path("_find").build();
    JsonObject body = getFindByIndexBody(selectorJson, options);
    InputStream stream = null;//ww  w  .  ja v a2s  .c om
    try {
        stream = client.couchDbClient
                .executeToInputStream(createPost(uri, body.toString(), "application/json"));
        Reader reader = new InputStreamReader(stream, "UTF-8");
        JsonArray jsonArray = new JsonParser().parse(reader).getAsJsonObject().getAsJsonArray("docs");
        List<T> list = new ArrayList<T>();
        for (JsonElement jsonElem : jsonArray) {
            JsonElement elem = jsonElem.getAsJsonObject();
            T t = client.getGson().fromJson(elem, classOfT);
            list.add(t);
        }
        return list;
    } catch (UnsupportedEncodingException e) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(stream);
    }
}

From source file:com.cloudant.client.internal.views.ViewMultipleRequester.java

License:Open Source License

public List<ViewResponse<K, V>> getViewResponses() throws IOException {
    //build the queries array of data to POST
    JsonArray queries = new JsonArray();
    ViewQueryParameters<K, V> viewQueryParameters = null;
    for (ViewQueryParameters<K, V> params : requestParameters) {
        if (viewQueryParameters == null) {
            viewQueryParameters = params;
        }//w  w w .  jav  a 2s . com
        queries.add(params.asJson());
    }
    JsonObject queryJson = new JsonObject();
    queryJson.add("queries", queries);
    //construct and execute the POST request
    HttpPost post = new HttpPost(viewQueryParameters.getViewURIBuilder().buildEncoded());
    StringEntity entity = new StringEntity(queryJson.toString(), "UTF-8");
    entity.setContentType("application/json");
    post.setEntity(entity);
    JsonObject jsonResponse = ViewRequester.executeRequestWithResponseAsJson(viewQueryParameters, post);
    //loop the returned array creating the ViewResponse objects
    List<ViewResponse<K, V>> responses = new ArrayList<ViewResponse<K, V>>();
    JsonArray jsonResponses = jsonResponse.getAsJsonArray("results");
    if (jsonResponses != null) {
        int index = 0;
        for (ViewQueryParameters<K, V> params : requestParameters) {
            JsonObject response = jsonResponses.get(index).getAsJsonObject();
            responses.add(new ViewResponseImpl<K, V>(params, response));
            index++;
        }
        return responses;
    } else {
        return Collections.emptyList();
    }
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClient.java

License:Open Source License

/**
 * Performs a HTTP PUT request, saves or updates a document.
 *
 * @param object    Object for updating request
 * @param newEntity If true, saves a new document. Else, updates an existing one.
 * @return {@link Response}/* w  w  w  .  j  av  a  2s.  com*/
 */
public Response put(URI uri, Object object, boolean newEntity, int writeQuorum) {
    assertNotEmpty(object, "object");
    final JsonObject json = getGson().toJsonTree(object).getAsJsonObject();
    String id = getAsString(json, "_id");
    String rev = getAsString(json, "_rev");
    if (newEntity) { // save
        assertNull(rev, "rev");
        id = (id == null) ? generateUUID() : id;
    } else { // update
        assertNotEmpty(id, "id");
        assertNotEmpty(rev, "rev");
    }
    URI httpUri = null;
    if (writeQuorum > -1) {
        httpUri = new DatabaseURIHelper(uri).documentUri(id, "w", writeQuorum);
    } else {
        httpUri = new DatabaseURIHelper(uri).documentUri(id);
    }
    HttpConnection connection = Http.PUT(httpUri, "application/json");
    connection.setRequestBody(json.toString());

    return executeToResponse(connection);
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientBase.java

License:Open Source License

/**
 * Performs a HTTP PUT request, saves or updates a document.
 *
 * @return {@link Response}//from w  ww .j  a  v a 2s  . c o  m
 */
Response put(URI uri, Object object, boolean newEntity) {
    assertNotEmpty(object, "object");
    HttpResponse response = null;
    try {
        final JsonObject json = getGson().toJsonTree(object).getAsJsonObject();
        String id = getAsString(json, "_id");
        String rev = getAsString(json, "_rev");
        if (newEntity) { // save
            assertNull(rev, "rev");
            id = (id == null) ? generateUUID() : id;
        } else { // update
            assertNotEmpty(id, "id");
            assertNotEmpty(rev, "rev");
        }
        final HttpPut put = new HttpPut(buildUri(uri).pathToEncode(id).buildEncoded());
        setEntity(put, json.toString());
        response = executeRequest(put);
        return getResponse(response, Response.class, getGson());
    } finally {
        close(response);
    }
}

From source file:com.cloudant.client.org.lightcouch.Replication.java

License:Open Source License

/**
 * Triggers a replication request./*from w ww .  ja  v a  2  s .  c o  m*/
 */
public ReplicationResult trigger() {
    assertNotEmpty(source, "Source");
    assertNotEmpty(target, "Target");
    HttpResponse response = null;
    try {
        JsonObject json = createJson();
        if (log.isDebugEnabled()) {
            log.debug(json);
        }
        final URI uri = buildUri(client.getBaseUri()).path("_replicate").build();
        response = client.post(uri, json.toString());
        final InputStreamReader reader = new InputStreamReader(getStream(response), "UTF-8");
        return client.getGson().fromJson(reader, ReplicationResult.class);
    } catch (UnsupportedEncodingException e) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(response);
    }
}

From source file:com.collaide.fileuploader.models.repositorty.RepoFolder.java

@Override
public String toJson() {
    JsonObject repoFolderJson = new JsonObject();
    repoFolderJson.add("repo_folder", gson.toJsonTree(this));
    return repoFolderJson.toString();
}