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.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java

License:Open Source License

/**
 * ???/*from  www. jav a2 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();
        }

        LoggerUtil.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);

        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("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.blackducksoftware.integration.email.extension.config.ExtensionConfigManager.java

License:Apache License

public String createJSonString(final Reader reader) {
    final JsonElement element = parser.parse(reader);
    final JsonArray array = element.getAsJsonArray();
    final JsonObject object = new JsonObject();
    object.addProperty("totalCount", array.size());
    object.add("items", array);
    return object.toString();
}

From source file:com.blackducksoftware.integration.hub.fod.service.FoDRestConnectionService.java

License:Apache License

public String getFoDImportSessionId(final String releaseId, final long fileLength, final String reportName,
        final String reportNotes) {
    final RestTemplate restTemplate = new RestTemplate();

    final HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + this.getToken());
    headers.setContentType(MediaType.APPLICATION_JSON);

    final JsonObject requestJson = new JsonObject();

    requestJson.addProperty("releaseId", Integer.parseInt(releaseId));
    requestJson.addProperty("fileLength", fileLength);
    requestJson.addProperty("fileExtension", ".pdf");
    requestJson.addProperty("reportName", reportName);
    requestJson.addProperty("reportNotes", reportNotes);

    logger.debug("Requesting Session ID to FoD:" + requestJson.toString());

    final HttpEntity<String> request = new HttpEntity<>(requestJson.toString(), headers);

    // Get the Session ID
    final ResponseEntity<String> response = restTemplate.exchange(
            appProps.getFodAPIBaseURL() + FOD_API_URL_VERSION + REPORT_IMPORT_SESSIONID, HttpMethod.POST,
            request, String.class);

    final JsonParser parser = new JsonParser();
    final JsonObject obj = parser.parse(response.getBody()).getAsJsonObject();

    return obj.get("importReportSessionId").getAsString();
}

From source file:com.broadlink.control.api.BroadlinkAPI.java

/**
 * Execute a Broadlink API with the given parameters
 *///from   w  w  w .j a  va2s  .  c  o  m
private JsonObject broadlinkExecuteCommand(JsonObject params) {
    if (mBlNetwork == null) {
        Log.e(this.getClass().getSimpleName(), "mBlNetwork is uninitialized, check app permissions");
        return null;
    }
    String responseString = mBlNetwork.requestDispatch(params.toString());
    JsonObject responseJsonObject = new JsonParser().parse(responseString).getAsJsonObject();
    Log.d(this.getClass().getSimpleName(), responseString);
    return responseJsonObject;
}

From source file:com.ca.dvs.utilities.lisamar.JDBCUtil.java

License:Open Source License

@SuppressWarnings("unchecked")
/**// w ww .j a  va 2 s. c  om
 * Get the seed data of the specified entity set from Raml mode of OData Service
 * @param tagName - the name of entity set 
 * @return - the list of Map<String, Object>
 */
private List<Map<String, Object>> getSampleObjects(final String tagName) {

    /* Sample data:
      "/books": {                  "/<EntitySetName>"
        "schema": "books",            "<EntitySetName>"
        "example": {
    "size": 2,
    "books": [               "<EntitySetName>"
      {
        "id": 1,
        "name": "The Hobbit; or, There and Back Again",
        "isbn": "054792822X",
        "author_id": 1
      },
      {
        "id": 2,
        "name": "The Fellowship of the Ring",
        "isbn": "B007978NPG",
        "author_id": 1
      }
    ]
        }
      }         
    */

    Object dataObject = null;
    Object curObject = null;

    if (sampleData.size() == 0)
        return null;

    if (tagName == null || tagName.isEmpty())
        return null;

    curObject = sampleData.get("/" + tagName); //looking for /<EmtotySetName>
    if (curObject != null) {
        Map<String, Object> mapObjectList = null;
        mapObjectList = (Map<String, Object>) curObject;
        Object schemaObject = mapObjectList.get("schema");
        String schemaValue = schemaObject.toString();
        if (schemaObject instanceof JsonPrimitive) {
            JsonPrimitive sObject = (JsonPrimitive) schemaObject;
            schemaValue = sObject.getAsString();
        }
        if (schemaValue.equals(tagName)) {
            curObject = mapObjectList.get("example");
            if (curObject != null) {
                HashMap<String, Object> exampleObject = null;
                if (curObject instanceof JsonObject) {
                    JsonObject jsonObj = (JsonObject) curObject;
                    try {
                        exampleObject = convertJsonToMap(jsonObj.toString());
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Map<String, Object> err = new LinkedHashMap<String, Object>();
                        err.put("entitySet", tagName);
                        err.put("record", jsonObj.toString());
                        err.put("warning", e.getMessage());
                        insertDataErrors.add(err);
                        return null;
                    }
                } else if (curObject instanceof LinkedHashMap) {
                    exampleObject = (HashMap<String, Object>) curObject;
                } else if (curObject instanceof HashMap) {
                    exampleObject = (HashMap<String, Object>) curObject;
                }

                if (exampleObject == null)
                    return null;

                dataObject = exampleObject.get(tagName);
            }
        }
    }

    // no sample data for the specified entity
    if (dataObject == null)
        return null;

    List<Map<String, Object>> samples = (List<Map<String, Object>>) dataObject;
    return samples;

}

From source file:com.canoo.dolphin.impl.codec.OptimizedJsonCodec.java

License:Apache License

@Override
public List<Command> decode(String transmitted) {
    Assert.requireNonNull(transmitted, "transmitted");
    LOG.trace("Decoding message: {}", transmitted);
    try {//w  ww . ja va2  s .co  m
        final List<Command> commands = new ArrayList<>();
        final JsonArray array = (JsonArray) new JsonParser().parse(transmitted);

        for (final JsonElement jsonElement : array) {
            final JsonObject command = (JsonObject) jsonElement;
            JsonPrimitive idPrimitive = command.getAsJsonPrimitive("id");

            String id = null;
            if (idPrimitive != null) {
                id = idPrimitive.getAsString();
            }
            LOG.trace("Decoding command: {}", id);
            CommandEncoder<?> encoder = null;
            if (id != null) {
                encoder = DECODERS.get(id);
            }
            if (encoder != null) {
                commands.add(encoder.decode(command));
            } else {
                commands.addAll(fallBack.decode("[" + command.toString() + "]"));
            }
        }
        LOG.trace("Decoded command list with {} commands", commands.size());
        return commands;
    } catch (ClassCastException | NullPointerException ex) {
        throw new JsonParseException("Illegal JSON detected", ex);
    }
}

From source file:com.ccc.crest.core.cache.crest.schema.endpoint.EndpointCollection.java

License:Open Source License

@Override
public EndpointCollection deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject topObj = (JsonObject) json;
    Set<Entry<String, JsonElement>> topSet = topObj.entrySet();
    Iterator<Entry<String, JsonElement>> topIter = topSet.iterator();
    do {//from   w w  w  .  j a v a 2  s  . co  m
        if (!topIter.hasNext())
            break;
        Entry<String, JsonElement> topEntry = topIter.next();
        String topKey = topEntry.getKey();
        JsonElement topElement = topEntry.getValue();
        if (topKey.equals(UserCountKey)) {
            userCount = Long.parseLong(topElement.getAsString());
            continue;
        }
        if (topKey.equals(UserCountStrKey))
            continue;
        if (topKey.equals(ServerVersionKey)) {
            serverVersion = topElement.getAsString();
            continue;
        }
        if (topKey.equals(ServerNameKey)) {
            serverName = topElement.getAsString();
            continue;
        }
        if (topKey.equals(ServerStatusKey)) {
            serviceStatus = topElement.getAsString();
            continue;
        }
        // if its not a top object level known variable from above list, it must be a group object
        if (topElement.isJsonPrimitive()) {
            log.warn("unexpected key: " + topKey + " = " + topObj.toString());
            continue;
        }
        if (!topElement.isJsonObject()) {
            log.warn("expected an object: " + topKey + " = " + topObj.toString());
            continue;
        }
        // first pass you should have a group in the topElement
        String groupName = topKey;
        EndpointGroup endpointGroup = new EndpointGroup(groupName);
        callGroups.add(endpointGroup);
        Set<Entry<String, JsonElement>> groupSet = topElement.getAsJsonObject().entrySet();
        Iterator<Entry<String, JsonElement>> groupIter = groupSet.iterator();
        do {
            if (!groupIter.hasNext())
                break;
            Entry<String, JsonElement> groupEntry = groupIter.next();
            // expecting a primitive href here
            String endpointName = groupEntry.getKey();
            JsonElement hrefElement = groupEntry.getValue();
            if (hrefElement.isJsonObject()) {
                JsonObject groupChildObj = (JsonObject) hrefElement;
                Set<Entry<String, JsonElement>> groupChildSet = groupChildObj.entrySet();
                Iterator<Entry<String, JsonElement>> groupChildIter = groupChildSet.iterator();
                if (!groupChildIter.hasNext())
                    break;
                Entry<String, JsonElement> groupChildEntry = groupChildIter.next();
                String groupChildKey = groupChildEntry.getKey();
                JsonElement groupChildElement = groupChildEntry.getValue();
                endpointGroup.addEndpoint(new CrestEndpoint(endpointName, groupChildElement.getAsString()));
                continue;
            }
            // expect an object with href in it
            if (!hrefElement.isJsonPrimitive()) {
                log.warn("expected a primitive after group: " + groupName + " = " + hrefElement.toString());
                continue;
            }
            endpointGroup.addEndpoint(new CrestEndpoint(endpointName, hrefElement.getAsString()));
            break;
        } while (true);
    } while (true);
    return this;
}

From source file:com.ccreanga.bitbucket.rest.client.http.BitBucketClient.java

License:Apache License

protected Optional<JsonElement> execute(String requestUrl, HttpMethod method, JsonObject requestJson) {

    String requestData = requestJson != null ? requestJson.toString() : null;
    return execute(requestUrl, method, requestData);
}

From source file:com.cinchapi.concourse.server.http.HttpServer.java

License:Apache License

/**
 * Initialize a {@link EndpointContainer container} by registering all of
 * its/*from   www .j a  v  a  2s  .  c om*/
 * endpoints.
 * 
 * @param container the {@link EndpointContainer} to initialize
 */
private static void initialize(EndpointContainer container) {
    for (final Endpoint endpoint : container.endpoints()) {
        String action = endpoint.getAction();
        Route route = new Route(endpoint.getPath()) {

            @Override
            public Object handle(Request request, Response response) {
                response.type(endpoint.getContentType().toString());
                // The HttpRequests preprocessor assigns attributes to the
                // request in order for the Endpoint to make calls into
                // ConcourseServer.
                AccessToken creds = (AccessToken) request.attribute(GlobalState.HTTP_ACCESS_TOKEN_ATTRIBUTE);
                String environment = MoreObjects.firstNonNull(
                        (String) request.attribute(GlobalState.HTTP_ENVIRONMENT_ATTRIBUTE),
                        GlobalState.DEFAULT_ENVIRONMENT);
                String fingerprint = (String) request.attribute(GlobalState.HTTP_FINGERPRINT_ATTRIBUTE);

                // Check basic authentication: is an AccessToken present and
                // does the fingerprint match?
                if ((boolean) request.attribute(GlobalState.HTTP_REQUIRE_AUTH_ATTRIBUTE) && creds == null) {
                    halt(401);
                }
                if (!Strings.isNullOrEmpty(fingerprint)
                        && !fingerprint.equals(HttpRequests.getFingerprint(request))) {
                    Logger.warn("Request made with mismatching fingerprint. Expecting {} but got {}",
                            HttpRequests.getFingerprint(request), fingerprint);
                    halt(401);
                }
                TransactionToken transaction = null;
                try {
                    Long timestamp = Longs
                            .tryParse((String) request.attribute(GlobalState.HTTP_TRANSACTION_TOKEN_ATTRIBUTE));
                    transaction = creds != null && timestamp != null ? new TransactionToken(creds, timestamp)
                            : transaction;
                } catch (NullPointerException e) {
                }
                try {
                    return endpoint.serve(request, response, creds, transaction, environment);
                } catch (Exception e) {
                    if (e instanceof HttpError) {
                        response.status(((HttpError) e).getCode());
                    } else if (e instanceof SecurityException || e instanceof java.lang.SecurityException) {
                        response.removeCookie(GlobalState.HTTP_AUTH_TOKEN_COOKIE);
                        response.status(401);
                    } else if (e instanceof IllegalArgumentException) {
                        response.status(400);
                    } else {
                        response.status(500);
                        Logger.error("", e);
                    }
                    JsonObject json = new JsonObject();
                    json.addProperty("error", e.getMessage());
                    return json.toString();
                }
            }

        };
        if (action.equals("get")) {
            Spark.get(route);
        } else if (action.equals("post")) {
            Spark.post(route);
        } else if (action.equals("put")) {
            Spark.put(route);
        } else if (action.equals("delete")) {
            Spark.delete(route);
        } else if (action.equals("upsert")) {
            Spark.post(route);
            Spark.put(route);
        } else if (action.equals("options")) {
            Spark.options(route);
        }
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductsController.java

@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody/*from   w w  w  .ja v a  2s . c  om*/
public String editProductLogo(@ModelAttribute("productLogoForm") ProductLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### edit product logo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                new Object[] { fileSize }, request.getLocale()));
        return error.toString();
    }

    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        Product product = form.getProduct();
        ProductLogoFormValidator validator = new ProductLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            setPage(map, Page.PRODUCTS);
            JsonObject error = new JsonObject();
            error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                    null, request.getLocale()));
            return error.toString();
        } else {
            try {
                product = productService.editProductLogo(product, form.getLogo());
            } catch (FileUploadException e) {
                logger.debug("###IO Exception in writing custom image file", e);
                result.rejectValue("logo", "error.uploading.file");
                JsonObject error = new JsonObject();
                error.addProperty("errormessage", messageSource
                        .getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
                return error.toString();
            }
        }
        String response = null;
        try {
            response = JSONUtils.toJSONString(product);
        } catch (JsonGenerationException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (JsonMappingException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (IOException e) {
            logger.debug("###IO Exception in writing custom image file");
        }
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        setPage(map, Page.PRODUCTS);
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        return error.toString();
    }
}