Example usage for com.google.gson JsonObject addProperty

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

Introduction

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

Prototype

public void addProperty(String property, Character value) 

Source Link

Document

Convenience method to add a char member.

Usage

From source file:com.baomidou.springwind.util.yuntongxin.CCPRestSDK.java

License:Open Source License

/**
 * ????/* ww w .  j a  v a 2  s.com*/
 * 
 * @param startNo
 *            ?? ??0
 * @param offset
 *            ?? ??1?100?
 * @return
 */
public HashMap<String, Object> getSubAccounts(String startNo, String offset) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    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, Get_SubAccounts);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            if (!(isEmpty(startNo)))
                json.addProperty("startNo", startNo);
            if (!(isEmpty(offset)))
                json.addProperty("offset", offset);
            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><SubAccount>");
            sb.append("<appId>").append(App_ID).append("</appId>");
            if (!(isEmpty(startNo)))
                sb.append("<startNo>").append(startNo).append("</startNo>");
            if (!(isEmpty(offset)))
                sb.append("<offset>").append(offset).append("</offset>");
            sb.append("</SubAccount>").toString();
            requsetbody = sb.toString();
        }
        logger.info("GetSubAccounts Request body =  " + requsetbody);
        System.out.println("" + 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);
        status = response.getStatusLine().getStatusCode();
        System.out.println("Https??" + status);

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

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }
    logger.info("getSubAccounts result " + 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.baomidou.springwind.util.yuntongxin.CCPRestSDK.java

License:Open Source License

/**
 * ???//from  w  w  w. j a  v  a  2  s . c om
 * 
 * @param friendlyName
 *            ? ?????????????????
 * @return
 */
public HashMap<String, Object> createSubAccount(String friendlyName) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if (isEmpty(friendlyName)) {
        logger.debug("?: ????? ");
        throw new IllegalArgumentException("?: ????? ");
    }

    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        logger.error(e1.getMessage());
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, Create_SubAccount);
        String requsetbody = "";

        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("friendlyName", friendlyName);
            requsetbody = json.toString();
        } else {
            requsetbody = "<?xml version='1.0' encoding='utf-8'?><SubAccount>" + "<appId>" + App_ID + "</appId>"
                    + "<friendlyName>" + friendlyName + "</friendlyName>" + "</SubAccount>";
        }
        logger.info("CreateSubAccount Request body =  " + requsetbody);
        System.out.println("" + 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);
        status = response.getStatusLine().getStatusCode();

        System.out.println("Https??" + status);

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }
    logger.info("createSubAccount 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.baomidou.springwind.util.yuntongxin.CCPRestSDK.java

License:Open Source License

/**
 * ?//  ww  w.ja  v  a  2 s  . co m
 * 
 * @param templateId
 *            ?? ?Id????
 * @return
 */
public HashMap<String, Object> QuerySMSTemplate(String templateId) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;

    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        logger.error(e1.getMessage());
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, Query_SMSTemplate);
        String requsetbody = "";

        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("templateId", templateId);
            requsetbody = json.toString();
        } else {
            requsetbody = "<?xml version='1.0' encoding='utf-8'?><Request>" + "<appId>" + App_ID + "</appId>"
                    + "<templateId>" + templateId + "</templateId>" + "</Request>";
        }
        logger.info("QuerySMSTemplate Request body =  " + requsetbody);
        //?
        System.out.println("" + 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);

        //???

        status = response.getStatusLine().getStatusCode();

        System.out.println("Https??" + status);

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }
    logger.info("QuerySMSTemplate 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.baomidou.springwind.util.yuntongxin.CCPRestSDK.java

License:Open Source License

/**
 * ??/* www  .j a  v a  2 s.co m*/
 * 
 * @param callid
 *            ? ?Id
 * @param action
 *            ?? url?
 * @return
 */
public HashMap<String, Object> QueryCallState(String callid, String action) {

    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if ((isEmpty(callid))) {
        logger.debug("?: callid  ");
        throw new IllegalArgumentException("?: callid ");
    }
    Callsid = callid;
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        logger.error(e1.getMessage());
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, queryCallState);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            JsonObject json2 = new JsonObject();
            json.addProperty("Appid", App_ID);
            json2.addProperty("callid", callid);
            if (!(isEmpty(action)))
                json2.addProperty("action", action);
            json.addProperty("QueryCallState", json2.toString());
            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><Request>");
            sb.append("<Appid>").append(App_ID).append("</Appid>").append("<QueryCallState callid=")
                    .append("\"").append(callid).append("\"");
            if (action != null) {
                sb.append(" action=").append("\"").append(action).append("\"").append("/");
            }

            sb.append("></Request>").toString();
            requsetbody = sb.toString();
        }
        logger.info("queryCallState Request body = : " + requsetbody);
        System.out.println("" + 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);
        status = response.getStatusLine().getStatusCode();
        System.out.println("Https??" + status);

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

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }
    logger.info("billRecords 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.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public JsonObject createUser(String fullname, String emailAddress) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not Supported on AWS S3");

    JsonObject result = null;/*  w w  w  .ja  v a  2 s .c  o  m*/

    try {
        JsonObject postData = new JsonObject();
        postData.addProperty("email", emailAddress);
        postData.addProperty("name", fullname);

        InputStream dataInputStream = new ByteArrayInputStream(postData.toString().getBytes("UTF-8"));

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Content-Length", String.valueOf(dataInputStream.available()));

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl("", "user", EMPTY_STRING_MAP);
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.POST, url,
                dataInputStream, headers);
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");

        result = new JsonParser().parse(inputStreamReader).getAsJsonObject();

    } catch (Exception e) {
        throw new RiakCSException(e);
    }

    return result;
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

private void enableDisableUser(String key_id, boolean enable) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not Supported on AWS S3");

    try {//from  ww w . j av a2 s  . c o  m
        JsonObject postData = new JsonObject();
        if (enable)
            postData.addProperty("status", "enabled");
        else
            postData.addProperty("status", "disabled");

        InputStream dataInputStream = new ByteArrayInputStream(postData.toString().getBytes("UTF-8"));

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Content-Length", String.valueOf(dataInputStream.available()));

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl("/riak-cs/user/" + key_id);
        comLayer.makeCall(CommunicationLayer.HttpMethod.PUT, url, dataInputStream, headers);

    } catch (Exception e) {
        throw new RiakCSException(e);
    }
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public JsonObject listBuckets() throws RiakCSException {
    CommunicationLayer comLayer = getCommunicationLayer();

    JsonObject bucketList = null;//  w  ww .  jav a 2s  .  co  m

    try {
        URL url = comLayer.generateCSUrl("", "", EMPTY_STRING_MAP);
        HttpURLConnection conn = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url);
        Document xmlDoc = XMLUtils.parseToDocument(conn.getInputStream(), debugModeEnabled);

        bucketList = new JsonObject();
        JsonArray buckets = new JsonArray();
        for (Node node : XMLUtils.xpathToNodeList("//Buckets/Bucket", xmlDoc)) {
            JsonObject bucket = new JsonObject();
            bucket.addProperty("name", XMLUtils.xpathToContent("Name", node));
            bucket.addProperty("creationDate", XMLUtils.xpathToContent("CreationDate", node));
            buckets.add(bucket);
        }

        bucketList.add("bucketList", buckets);
        JsonObject owner = new JsonObject();
        owner.addProperty("id", XMLUtils.xpathToContent("//Owner/ID", xmlDoc));
        owner.addProperty("displayName", XMLUtils.xpathToContent("//Owner/DisplayName", xmlDoc));

        bucketList.add("owner", owner);

    } catch (Exception e) {
        throw new RiakCSException(e);
    }

    return bucketList;
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public JsonObject getObject(String bucketName, String objectKey, OutputStream dataOutputStream)
        throws RiakCSException {
    JsonObject object = null;

    try {/*w w w. ja  va 2  s.  co  m*/
        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl(bucketName, objectKey, EMPTY_STRING_MAP);
        HttpURLConnection conn = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null,
                EMPTY_STRING_MAP);

        object = extractMetaInfoForObject(objectKey, conn);

        // Download data
        if (dataOutputStream != null) {
            InputStream inputStream = conn.getInputStream();
            byte[] buffer = new byte[8192];
            int count = -1;
            while ((count = inputStream.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, count);
            }
            dataOutputStream.close();
            inputStream.close();
        } else {
            object.addProperty("body", getInputStreamAsString(conn.getInputStream()));
        }

    } catch (Exception e) {
        throw new RiakCSException(e);
    }

    return object;
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

private JsonObject extractMetaInfoForObject(String objectKey, HttpURLConnection conn) {
    Map<String, String> responseHeaders = new HashMap<String, String>();
    JsonObject metadata = new JsonObject();

    for (String headerName : conn.getHeaderFields().keySet()) {
        if (headerName == null)
            continue;

        if (headerName.startsWith("x-amz-meta")) {
            metadata.addProperty(headerName.substring(11), conn.getHeaderFields().get(headerName).get(0));
        } else {//from ww  w.  j ava 2s. co  m
            responseHeaders.put(headerName, conn.getHeaderFields().get(headerName).get(0));
        }
    }

    JsonObject object = new JsonObject();
    object.addProperty("key", objectKey);
    object.addProperty("etag", responseHeaders.get("ETag"));
    object.addProperty("lastModified", responseHeaders.get("Last-Modified"));
    object.addProperty("size", responseHeaders.get("Content-Length"));
    object.addProperty("contenttype", responseHeaders.get("Content-Type"));
    object.add("metadata", metadata);
    return object;
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public JsonObject listObjects(String bucketName, boolean extendedList) throws RiakCSException {
    //TODO switch to more streaming type of mode
    JsonObject result = new JsonObject();

    try {//  w  ww . j a  va  2 s  . c om
        result.addProperty("bucketName", bucketName);

        boolean isTruncated = true;
        while (isTruncated) {
            CommunicationLayer comLayer = getCommunicationLayer();

            URL url = comLayer.generateCSUrl(bucketName, "", EMPTY_STRING_MAP);
            HttpURLConnection conn = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url);

            JsonArray objectList = new JsonArray();

            Document xmlDoc = XMLUtils.parseToDocument(conn.getInputStream(), debugModeEnabled);
            List<Node> nodeList = XMLUtils.xpathToNodeList("//Contents", xmlDoc);
            for (Node node : nodeList) {
                JsonObject object = new JsonObject();
                object.addProperty("key", XMLUtils.xpathToContent("Key", node));
                if (extendedList) {
                    object.addProperty("size", XMLUtils.xpathToContent("Size", node));
                    object.addProperty("lastModified", XMLUtils.xpathToContent("LastModified", node));
                    object.addProperty("etag", XMLUtils.xpathToContent("ETag", node));

                    JsonObject owner = new JsonObject();
                    owner.addProperty("id", XMLUtils.xpathToContent("Owner/ID", node));
                    owner.addProperty("displayName", XMLUtils.xpathToContent("Owner/DisplayName", node));
                    object.add("owner", owner);
                }

                objectList.add(object);
            }

            result.add("objectList", objectList);
            isTruncated = "true".equals(XMLUtils.xpathToContent("//IsTruncated", xmlDoc));
        }

    } catch (Exception e) {
        throw new RiakCSException(e);
    }

    return result;
}