Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java

License:Apache License

/**
 * Create port-forward rule./*from ww  w.  j  a v a 2s .com*/
 * <p/>
 * like jclouds version, but takes the networkId which is mandatory for VPCs.
 * <p/>
 * Does <em>NOT</em> open any firewall.
 *
 * @return job id.
 */
public String createPortForwardRule(String networkId, String ipAddressId, Protocol protocol, int publicPort,
        String targetVmId, int privatePort) {
    // needed because jclouds doesn't support supplying tier ID (for VPC's)
    Multimap<String, String> params = ArrayListMultimap.create();
    params.put("command", "createPortForwardingRule");

    params.put("networkid", networkId);
    params.put("ipaddressid", ipAddressId);
    params.put("protocol", protocol.toString());
    params.put("publicport", "" + publicPort);
    params.put("virtualmachineid", targetVmId);
    params.put("privateport", "" + privatePort);
    //        params.put("openfirewall", "" + false);

    params.put("apiKey", this.apiKey);
    params.put("response", "json");

    LOG.debug("createPortForwardingRule GET " + params);

    HttpRequest request = HttpRequest.builder().method("GET").endpoint(this.endpoint).addQueryParams(params)
            .addHeader("Accept", "application/json").build();

    request = getQuerySigner().filter(request);

    HttpToolResponse response = HttpUtil.invoke(request);
    // TODO does non-2xx response need to be handled separately ?

    JsonElement jr = json(response);
    LOG.debug("createPortForwardingRule GOT " + jr);

    try {
        JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject();
        return jobfields.get("jobid").getAsString();
    } catch (NullPointerException | NoSuchElementException | IllegalStateException e) {
        // TODO Not good using exceptions for normal control flow; but easiest way to handle
        // problems in unexpected json structure.
        throw new IllegalStateException(
                "Problem executing createPortForwardingRule(" + params + ")" + ": " + jr.toString());
    }
}

From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java

License:Apache License

/**
 * Create port-forward rule for a VM.//from  w  w  w  .j  ava2s. c om
 * <p/>
 * Does <em>NOT</em> open any firewall.
 */
public String createPortForwardRuleForVm(String publicIpId, Protocol protocol, int publicPort,
        String targetVmId, int privatePort) {
    // needed because jclouds doesn't support CIDR
    //        return cloudstackClient.getCloudstackGlobalClient().getFirewallClient().
    //                createPortForwardingRuleForVirtualMachine(
    //                        publicIpId, PortForwardingRule.Protocol.TCP, publicPort, targetVmId, privatePort).
    //                getJobId();

    Multimap<String, String> params = ArrayListMultimap.create();
    params.put("command", "createPortForwardingRule");

    params.put("ipaddressid", publicIpId);
    params.put("protocol", protocol.toString());
    params.put("publicport", "" + publicPort);
    params.put("virtualmachineid", targetVmId);
    params.put("privateport", "" + privatePort);
    //        params.put("openfirewall", "" + false);

    params.put("apiKey", this.apiKey);
    params.put("response", "json");

    LOG.debug("createPortForwardingRule GET " + params);

    HttpRequest request = HttpRequest.builder().method("GET").endpoint(this.endpoint).addQueryParams(params)
            .addHeader("Accept", "application/json").build();

    request = getQuerySigner().filter(request);

    request.getEndpoint().toString().replace("+", "%2B");
    //request = request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).query(decodedParams).build()).build();

    HttpToolResponse response = HttpUtil.invoke(request);
    // TODO does non-2xx response need to be handled separately ?

    JsonElement jr = json(response);
    LOG.debug("createPortForwardingRule GOT " + jr);

    try {
        JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject();
        return jobfields.get("jobid").getAsString();
    } catch (NullPointerException | NoSuchElementException | IllegalStateException e) {
        // TODO Not good using exceptions for normal control flow; but easiest way to handle
        // problems in unexpected json structure.
        throw new IllegalStateException(
                "Problem executing createPortForwardingRule(" + params + ")" + ": " + jr.toString());
    }
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonElement cloneJSON(JsonElement toClone) {
    return JSON_PARSER.parse(toClone.toString());
}

From source file:cf.adriantodt.David.modules.db.I18nModule.java

License:LGPL

private static void loadCommand(String lang, String name, JsonElement src, JsonObject metadata,
        List<Exception> post) {
    logger().trace(lang + " - " + name + " - " + src.toString());
    if (!src.isJsonObject())
        return;//from  w  w  w.  j a va  2 s .c  om
    JsonObject cmd = src.getAsJsonObject();
    try {
        if (cmd.has("desc") || cmd.has("params") || cmd.has("info")) {
            String desc = cmd.has("desc") ? cmd.get("desc").getAsString()
                    : metadata.get("noDesc").getAsString();
            String params = cmd.has("params") ? cmd.get("params").getAsString()
                    : metadata.get("noParams").getAsString();
            String info = cmd.has("info") ? "\n  " + cmd.get("info").getAsString().replace("\n", "\n  ") : "";
            localize(lang, name + ".usage",
                    desc + "\n" + metadata.get("params").getAsString() + ": " + params + info);
        }
    } catch (Exception e) {
        post.add(e);
    }

    try {
        if (cmd.has("translations")) {
            loadTranslation(lang, name + ".", cmd.get("translations"), post);
        }
    } catch (Exception e) {
        post.add(e);
    }

    try {
        if (cmd.has("subs") && cmd.get("subs").isJsonObject()) {
            cmd.get("subs").getAsJsonObject().entrySet().forEach(
                    entry -> loadCommand(lang, name + "." + entry.getKey(), entry.getValue(), metadata, post));
        }
    } catch (Exception e) {
        post.add(e);
    }
}

From source file:classes.analysis.Analysis.java

License:Open Source License

private String getJsonElementAsString(JsonElement element) {
    String value = "";
    if (element == null) {
        return "-";
    } else if (element.isJsonArray()) {
        JsonArray array = element.getAsJsonArray();
        for (JsonElement subelement : array) {
            value = this.getJsonElementAsString(subelement);
        }/*from  ww w. ja  v a2  s . c  o m*/
    } else if (element.isJsonObject()) {
        JsonObject object = element.getAsJsonObject();

        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            value += entry.getKey() + ":" + this.getJsonElementAsString(entry.getValue());
        }
    } else if (element.isJsonPrimitive()) {
        value += element.toString().replaceAll("\"", "") + "\n";
    }
    return value;
}

From source file:cocacola.cocacola.controller.MemberController.java

License:Apache License

public void testarRestCoca() {

    try {/*from  w  w  w  .  jav a2 s  . co m*/

        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        CocaCola c = new CocaCola(cal, "asdasdasdasd", "url1", "Paul", Status.RECEBIDA);

        c.setCor(cocaCola.getCor());
        c.setNome(cocaCola.getNome());
        c.setSexo(cocaCola.getSexo());
        System.out.println(cocaCola.toString());

        VideoGerado vg = new VideoGerado();
        VideoManager vm = new VideoManager();

        ClientRequest request = new ClientRequest(
                "http://festivaldomeujeito.com.br/server/index.php/festival/user/format/json");

        ClientResponse<String> response = request.get(String.class);

        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray jArray = parser.parse(response.getEntity()).getAsJsonArray();

        for (JsonElement obj : jArray) {

            System.out.println(obj.toString());

            JsonElement jelem = gson.fromJson(obj, JsonElement.class);
            JsonObject jobj = jelem.getAsJsonObject();
            System.out.println(jobj.get("mon_pergunta_1"));
            ClasseJsonCoca coca = gson.fromJson(obj, ClasseJsonCoca.class);
            System.out.println(coca.getMonPergunta1());
            c.setJsonCoca(coca);
            vg.setCocaCola(c);
            System.out.println(vg.getUrlCena2());
            System.out.println(vg.getUrlCena3());
            System.out.println(vg.getUrlCena4());
            System.out.println(vg.getUrlCena5());
            System.out.println(vg.getUrlCena6());

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.adssets.ejb.DataAccess.java

@Override
public String buildFeedForMarket(String marketId, String lazyLoad) {
    JsonArray jsonArray = new JsonArray();
    JsonParser parser = new JsonParser();

    //        Feed feed = feedFacade.find(marketId);
    Market market = marketFacade.find(Integer.valueOf(marketId));

    List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", market)
            .getResultList();//from  w w w .  j a  v a 2  s . c  o  m
    if (feeds.size() > 0) {
        for (Feed feed : feeds) {
            JsonObject obj = new JsonObject();
            obj.addProperty("id", feed.getId());
            obj.addProperty("marketId", feed.getIdmarket().getId());
            obj.addProperty("json", feed.getJson());
            jsonArray.add(obj);
        }

        JsonObject obj = jsonArray.get(0).getAsJsonObject();
        String objArray = obj.get("json").getAsString();

        JsonArray objArrayParsed = parser.parse(objArray).getAsJsonArray();
        JsonArray objData = new JsonArray();

        for (JsonElement objId : objArrayParsed) {
            JsonObject objElmParsed = parser.parse(objId.toString()).getAsJsonObject();
            System.out.println(objElmParsed);
            //            try{
            //            isInteger(objId.getAsString());
            String value = objElmParsed.get("type").getAsString();
            System.out.println(value);
            //CHANGE ADPICTURE TO THE PICTURE STORED IN THE DATABASE
            if (value.equals("object")) {
                String result = scout24.getApartments(objElmParsed.get("objectid").getAsString());
                if (!result.equals("{\"error\":1}")) {
                    JsonObject resultObj = parser.parse(result).getAsJsonObject();
                    String link = "{\"link\": \"https://www.immobilienscout24.de/expose/"
                            + objElmParsed.get("objectid").getAsInt() + "?referrer=\"}";
                    JsonObject clickLink = parser.parse(link).getAsJsonObject();
                    resultObj.add("clickLink", clickLink);
                    resultObj.add("objectId", objElmParsed.get("objectid"));
                    resultObj.add("marketId", parser.parse(marketId));
                    // Use the selected image as ad image
                    JsonObject objHref = new JsonObject();
                    objHref.add("href", objElmParsed.get("url"));
                    resultObj.add("adpicture", objHref);
                    //If lazyLoad = yes dont return "allpictures" LazyLoad=yes is the parameter the ad will send so it does not get unneccesary data
                    if (lazyLoad.equals("yes")) {
                        resultObj.remove("allpictures");
                    }

                    objData.add(resultObj);
                }

            } else {
                objData.add(objId);
            }
            //            }catch(UnsupportedOperationException ex){
            //            objData.add(objId);
            //            }

        }
        return objData.toString();
    } else {
        return new JsonArray().toString();
    }

}

From source file:com.arangodb.BaseArangoDriver.java

License:Apache License

/**
 * Gets the raw JSON string with results, from the Http response
 * @param res the response of the database
 * @return A valid JSON string with the results
 * @throws ArangoException//from   ww  w .j  av  a2s  .  c o m
 */
protected String getJSONResponseText(HttpResponseEntity res) throws ArangoException {
    if (res == null) {
        return null;
    }

    checkServerErrors(res);

    // no errors, return results as a JSON string
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(res.getText());
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonElement result = jsonObject.get("result");
    return result.toString();
}

From source file:com.arangodb.impl.InternalGraphDriverImpl.java

License:Apache License

private String convertToString(EdgeDefinitionEntity edgeDefinition) {
    JsonObject rawEdgeDefinition = (JsonObject) EntityFactory
            .toJsonElement(new MapBuilder().put("edgeDefinition", edgeDefinition).get(), false);
    JsonElement edgeDefinitionJson = rawEdgeDefinition.get("edgeDefinition");
    return edgeDefinitionJson.toString();
}

From source file:com.azure.webapi.MobileServiceClient.java

License:Open Source License

/**
 * Invokes a custom API/*  www. java 2  s  . c  om*/
 * 
 * @param apiName
 *            The API name
 * @param body
 *            The json element to send as the request body
 * @param httpMethod
 *            The HTTP Method used to invoke the API
 * @param parameters
 *            The query string parameters sent in the request
 * @param callback
 *            The callback to invoke after the API execution
 */
public void invokeApi(String apiName, JsonElement body, String httpMethod,
        List<Pair<String, String>> parameters, final ApiJsonOperationCallback callback) {

    byte[] content = null;
    if (body != null) {
        try {
            content = body.toString().getBytes(UTF8_ENCODING);
        } catch (UnsupportedEncodingException e) {
            if (callback != null) {
                callback.onCompleted(null, e, null);
            }
            return;
        }
    }

    List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();
    if (body != null) {
        requestHeaders
                .add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE));
    }

    invokeApi(apiName, content, httpMethod, requestHeaders, parameters, new ServiceFilterResponseCallback() {

        @Override
        public void onResponse(ServiceFilterResponse response, Exception exception) {
            if (callback != null) {
                if (exception == null) {
                    String content = response.getContent();
                    JsonElement json = new JsonParser().parse(content);

                    callback.onCompleted(json, null, response);
                } else {
                    callback.onCompleted(null, exception, response);
                }
            }
        }
    });
}