Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.baidu.rigel.biplatform.ac.model.callback.CallbackServiceInvoker.java

License:Open Source License

/**
 * callback?CallbackResponse404?cache??/* w w w .j a  v a  2 s . c o  m*/
 * @param responseStr
 * @param type
 * @return CallbackResponse
 */
private static CallbackResponse convertStrToResponse(String responseStr, CallbackType type) {
    LOG.info("[INFO] --- --- message received from callback server  is {}", responseStr);
    CallbackResponse rs = new CallbackResponse();
    long begin = System.currentTimeMillis();
    if (StringUtils.isEmpty(responseStr)) {
        throw new RuntimeException("???");
    }
    JsonObject json = new JsonParser().parse(responseStr).getAsJsonObject();
    int status = json.get("status").getAsInt();
    String message = json.get("message") == null || json.get("message") == JsonNull.INSTANCE ? "unknown"
            : json.get("message").getAsString();
    String provider = json.get("provider") == null || json.get("provider") == JsonNull.INSTANCE ? "unknown"
            : json.get("provider").getAsString();
    String cost = json.get("cost") == null || json.get("cost") == JsonNull.INSTANCE ? ""
            : json.get("cost").getAsString();
    String version = json.get("version") == null || json.get("version") == JsonNull.INSTANCE ? "unknown"
            : json.get("version").getAsString();
    LOG.info("[INFO] ------------------------------callback response desc -----------------------------------");
    LOG.info("[INFO] --- --- status : {}", status);
    LOG.info("[INFO] --- --- message : {}", message);
    LOG.info("[INFO] --- --- provider : {}", provider);
    LOG.info("[INFO] --- --- cost : {}", cost);
    LOG.info("[INFO] --- --- callback version : {}", version);
    LOG.info("[INFO] -----------------------------end print response desc -----------------------------------");
    LOG.info("[INFO] --- --- package result to CallbackResponse cost {} ms",
            (System.currentTimeMillis() - begin));
    rs.setCost(Integer.valueOf(StringUtils.isEmpty(cost) ? "0" : cost));
    rs.setStatus(getStatus(status));
    rs.setProvider(provider);
    rs.setVersion(version);
    rs.setMessage(getNlsMessage(status));
    if (ResponseStatus.SUCCESS.getValue() == status) {
        rs.setData(getCallbackValue(json.get("data").toString(), type));
    }
    return rs;
}

From source file:com.balajeetm.mystique.util.gson.GsonFactory.java

License:Open Source License

/**
 * Gets the json parser.// ww  w . j  a  v  a  2  s  .c  o m
 *
 * @return the json parser
 */
public JsonParser getJsonParser() {
    if (null == jsonParser) {
        jsonParser = new JsonParser();
    }
    return jsonParser;
}

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

License:Open Source License

/**
 * ???//from   w  w  w  .j  a v a 2 s.co m
 * 
 * @param to
 *            ? ??????????100
 * @param templateId
 *            ? ?Id
 * @param datas
 *            ?? ???{??}
 * @return
 */
public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId)))
        throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "")
                + (isEmpty(templateId) ? " ?Id " : "") + "");
    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, TemplateSMS);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("to", to);
            json.addProperty("templateId", templateId);
            if (datas != null) {
                StringBuilder sb = new StringBuilder("[");
                for (String s : datas) {
                    sb.append("\"" + s + "\"" + ",");
                }
                sb.replace(sb.length() - 1, sb.length(), "]");
                JsonParser parser = new JsonParser();
                JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray();
                json.add("datas", Jarray);
            }
            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>");
            sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>")
                    .append("<templateId>").append(templateId).append("</templateId>");
            if (datas != null) {
                sb.append("<datas>");
                for (String s : datas) {
                    sb.append("<data>").append(s).append("</data>");
                }
                sb.append("</datas>");
            }
            sb.append("</TemplateSMS>").toString();
            requsetbody = sb.toString();
        }
        //?
        System.out.println("" + requsetbody);
        logger.info("sendTemplateSMS 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);

        //???

        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", "" + "Https?" + status);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }

    logger.info("sendTemplateSMS 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

private HashMap<String, Object> jsonToMap(String result) {
    HashMap<String, Object> hashMap = new HashMap<String, Object>();
    JsonParser parser = new JsonParser();
    JsonObject asJsonObject = parser.parse(result).getAsJsonObject();
    Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
    HashMap<String, Object> hashMap2 = new HashMap<String, Object>();

    for (Entry<String, JsonElement> m : entrySet) {
        if ("statusCode".equals(m.getKey()) || "statusMsg".equals(m.getKey()))
            hashMap.put(m.getKey(), m.getValue().getAsString());
        else {/*from   w  ww.j  a v  a 2  s.co m*/
            if ("SubAccount".equals(m.getKey()) || "totalCount".equals(m.getKey())
                    || "smsTemplateList".equals(m.getKey()) || "token".equals(m.getKey())
                    || "callSid".equals(m.getKey()) || "state".equals(m.getKey())
                    || "downUrl".equals(m.getKey())) {
                if (!"SubAccount".equals(m.getKey()) && !"smsTemplateList".equals(m.getKey()))
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                else {
                    try {
                        if ((m.getValue().toString().trim().length() <= 2)
                                && !m.getValue().toString().contains("[")) {
                            hashMap2.put(m.getKey(), m.getValue().getAsString());
                            hashMap.put("data", hashMap2);
                            break;
                        }
                        if (m.getValue().toString().contains("[]")) {
                            hashMap2.put(m.getKey(), new JsonArray());
                            hashMap.put("data", hashMap2);
                            continue;
                        }
                        JsonArray asJsonArray = parser.parse(m.getValue().toString()).getAsJsonArray();
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        for (JsonElement j : asJsonArray) {
                            Set<Entry<String, JsonElement>> entrySet2 = j.getAsJsonObject().entrySet();
                            HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                            for (Entry<String, JsonElement> m2 : entrySet2) {
                                hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                            }
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put(m.getKey(), arrayList);
                    } catch (Exception e) {
                        JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                        Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Entry<String, JsonElement> m2 : entrySet2) {
                            hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                        }
                        hashMap2.put(m.getKey(), hashMap3);
                        hashMap.put("data", hashMap2);
                    }

                }
                hashMap.put("data", hashMap2);
            } else {

                JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                for (Entry<String, JsonElement> m2 : entrySet2) {
                    hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                }
                if (hashMap3.size() != 0) {
                    hashMap2.put(m.getKey(), hashMap3);
                } else {
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                }
                hashMap.put("data", hashMap2);
            }
        }
    }
    return hashMap;
}

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;/* ww  w. j a v a 2s .co 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

public JsonObject listUsers(UserListMode listMode) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not Supported on AWS S3");

    JsonObject result = null;//from  ww  w.  j av a  2 s .  c om

    try {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "application/json");

        String filterArgument = "";
        if (listMode == UserListMode.ENABLED_ONLY)
            filterArgument = "?status=enabled";
        else if (listMode == UserListMode.DISABLED_ONLY)
            filterArgument = "?status=disabled";

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl("/riak-cs/users" + filterArgument);
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null, headers);
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");

        JsonArray userList = new JsonArray();

        BufferedReader reader = new BufferedReader(inputStreamReader);
        for (String line; (line = reader.readLine()) != null;) {
            if (line.startsWith("[")) {
                JsonArray aUserlist = new JsonParser().parse(line).getAsJsonArray();
                userList.addAll(aUserlist);
            }
        }

        result = new JsonObject();
        result.add("userlist", userList);

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

    return result;
}

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

License:Open Source License

public JsonObject getUserInfo(String key_id) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not Supported on AWS S3");

    JsonObject result = null;// www.  ja  v a2  s  .  c  om

    try {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "application/json");

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl("/riak-cs/user/" + key_id);
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null, 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

public JsonObject getMyUserInfo() throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not Supported on AWS S3");

    JsonObject result = null;/*from ww  w  .  ja  va2s . c om*/

    try {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "application/json");

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl("/riak-cs/user");
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null, 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

public JsonObject getAccessStatistic(String keyForUser, int howManyHrsBack) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not supported by AWS S3");

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

    try {
        iso8601DateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));

        Date endTime = new Date(System.currentTimeMillis());
        Date startTime = new Date(System.currentTimeMillis() - (howManyHrsBack * 60 * 60 * 1000));

        StringBuilder path = new StringBuilder();
        path.append("/usage");
        path.append("/");
        path.append(keyForUser);
        path.append("/aj");
        path.append("/");
        path.append(iso8601DateFormat.format(startTime));
        path.append("/");
        path.append(iso8601DateFormat.format(endTime));

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl(path.toString());
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null,
                EMPTY_STRING_MAP);

        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");
        result = new JsonParser().parse(inputStreamReader).getAsJsonObject();
        result = result.getAsJsonObject("Access");

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

    return result;
}

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

License:Open Source License

public JsonObject getStorageStatistic(String keyForUser, int howManyHrsBack) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not supported by AWS S3");

    JsonObject result = null;/* w  ww . j  a va2  s  .c om*/

    try {
        iso8601DateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));

        Date endTime = new Date(System.currentTimeMillis());
        Date startTime = new Date(System.currentTimeMillis() - (howManyHrsBack * 60 * 60 * 1000));

        StringBuilder path = new StringBuilder();
        path.append("/usage");
        path.append("/");
        path.append(keyForUser);
        path.append("/bj");
        path.append("/");
        path.append(iso8601DateFormat.format(startTime));
        path.append("/");
        path.append(iso8601DateFormat.format(endTime));

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl(path.toString());
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null,
                EMPTY_STRING_MAP);

        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");
        result = new JsonParser().parse(inputStreamReader).getAsJsonObject();
        result = result.getAsJsonObject("Storage");

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

    return result;
}