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:co.com.konrad.interbolsa.ws.ValorAccionFacadeREST.java

@POST
@Override//from  ww w . java 2 s.  com
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String create(ValorAccion entity) throws Exception {
    //VAriable json
    JsonObject res = new JsonObject();
    try {
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");
        super.create(entity);
    } catch (Throwable ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Erro guardando entidad", ex);
        res.addProperty("codigo", 400);
        res.addProperty("mensaje", "operacion fallida");
    }
    return res.toString();
}

From source file:com.aapkatrade.buyer.seller.registration.SellerRegistrationActivity.java

private void callWebServiceForSellerRegistration() {
    String URL = getResources().getString(R.string.webservice_base_url) + "/sellerregister";

    if (docFile.getAbsolutePath().equals("/")) {
        Log.e("reach", "NUL_______DOCCCCCCCLICENCE");
        showmessage("Please Upload Company Document");

    } else {//w  w w  . j av  a 2 s. c o  m
        if (formSellerData.getBusinessType().contains("1"))

        {
            Log.e("work1", "work1");

            if (compIncorpFile.getAbsolutePath().equals("/")) {
                Log.e("reach", "NUL_______compDOCCCCCCCLiCENSE");
                showmessage("Please Upload Company Incorporation ( PDF Only )");

            } else {
                progressBarHandler.show();

                Ion.with(SellerRegistrationActivity.this).load(URL)
                        .setHeader("authorization", "xvfdbgfdhbfdhtrh54654h54ygdgerwer3")
                        .progress(new ProgressCallback() {
                            @Override
                            public void onProgress(long downloaded, long total) {
                                Log.e("status", downloaded + "  * " + total);
                            }
                        }).setMultipartFile("personal_doc", "image*//*", docFile)
                        //.setMultipartFile("personal_doc", "image*//*", docFile)
                        .setMultipartFile("comp_incorporation", "image*//*", compIncorpFile)
                        .setMultipartParameter("authorization", "xvfdbgfdhbfdhtrh54654h54ygdgerwer3")
                        .setMultipartParameter("business_type", formSellerData.getBusinessType())
                        .setMultipartParameter("business_id", business_id)
                        .setMultipartParameter("companyname", formSellerData.getCompanyName())
                        .setMultipartParameter("name", formSellerData.getFirstName())
                        .setMultipartParameter("lastname", formSellerData.getLastName())
                        .setMultipartParameter("dob", formSellerData.getDOB())
                        .setMultipartParameter("mobile", formSellerData.getMobile())
                        .setMultipartParameter("email", formSellerData.getEmail())
                        .setMultipartParameter("password", formSellerData.getPassword())
                        .setMultipartParameter("country_id", formSellerData.getCountryId())
                        .setMultipartParameter("state_id", formSellerData.getStateId())
                        .setMultipartParameter("city_id", formSellerData.getCityId())
                        .setMultipartParameter("client_id", formSellerData.getClientId())
                        .setMultipartParameter("shopname", formSellerData.getShopName())
                        .setMultipartParameter("tin_number", "521651")
                        .setMultipartParameter("tan_number", "13546848").setMultipartParameter("tc", "fdssd")
                        .setMultipartParameter("platform", "Android")
                        .setMultipartParameter("device_id", AppConfig.getCurrentDeviceId(context))
                        .asJsonObject().setCallback(new FutureCallback<JsonObject>() {
                            @Override
                            public void onCompleted(Exception e, JsonObject result) {
                                progressBarHandler.hide();
                                AndroidUtils.showErrorLog(context, "work1 response" + result);

                                if (result != null) {
                                    Log.e("registration_seller", result.toString());
                                    if (result.get("error").getAsString().equals("false")) {

                                        Log.e("registration_seller", "done");
                                        AndroidUtils.showSnackBar(registrationLayout,
                                                result.get("message").getAsString());

                                        if (ConnetivityCheck.isNetworkAvailable(context))

                                {
                                            Intent call_to_startactivity = new Intent(
                                                    SellerRegistrationActivity.this, ActivityOTPVerify.class);
                                            call_to_startactivity.putExtra("class_name",
                                                    "SellerRegistrationActivity");
                                            startActivity(call_to_startactivity);
                                        } else {

                                            AndroidUtils.showToast(context,
                                                    "!Internet not available. Check your internet connection.");
                                        }

                                    } else {
                                        AndroidUtils.showSnackBar(registrationLayout,
                                                result.get("message").getAsString());
                                    }
                                } else {
                                    Log.e("result_seller_error", e.toString());
                                    showmessage(e.toString());
                                }

                            }

                        });

            }
        } else {
            Log.e("work2", "work2");
            progressBarHandler.show();

            Ion.with(SellerRegistrationActivity.this).load(URL)
                    .setHeader("authorization", "xvfdbgfdhbfdhtrh54654h54ygdgerwer3")
                    .progress(new ProgressCallback() {
                        @Override
                        public void onProgress(long downloaded, long total) {
                            Log.e("status", downloaded + "  * " + total);
                        }
                    })
                    //.setMultipartFile("company_doc", "image*//*", docFile)
                    .setMultipartFile("personal_doc", "image*//*", docFile)

                    .setMultipartParameter("authorization", "xvfdbgfdhbfdhtrh54654h54ygdgerwer3")
                    .setMultipartParameter("business_type", formSellerData.getBusinessType())
                    .setMultipartParameter("business_id", business_id)
                    .setMultipartParameter("companyname", formSellerData.getCompanyName())
                    .setMultipartParameter("name", formSellerData.getFirstName())
                    .setMultipartParameter("lastname", formSellerData.getLastName())
                    .setMultipartParameter("dob", formSellerData.getDOB())
                    .setMultipartParameter("mobile", formSellerData.getMobile())
                    .setMultipartParameter("email", formSellerData.getEmail())
                    .setMultipartParameter("password", formSellerData.getPassword())
                    .setMultipartParameter("country_id", formSellerData.getCountryId())
                    .setMultipartParameter("state_id", formSellerData.getStateId())
                    .setMultipartParameter("city_id", formSellerData.getCityId())
                    .setMultipartParameter("client_id", formSellerData.getClientId())
                    .setMultipartParameter("shopname", formSellerData.getShopName())
                    .setMultipartParameter("tin_number", "521651")
                    .setMultipartParameter("tan_number", "13546848").setMultipartParameter("tc", "fdssd")
                    .setMultipartParameter("platform", "Android")
                    .setMultipartParameter("device_id", AppConfig.getCurrentDeviceId(context)).asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {
                            progressBarHandler.hide();

                            if (result != null) {
                                Log.e("registration_seller", result.toString());
                                if (result.get("error").getAsString().equals("false")) {
                                    AndroidUtils.showSnackBar(registrationLayout,
                                            result.get("message").getAsString());
                                    Log.e("registration_seller", "done");
                                    Intent call_to_startactivity = new Intent(SellerRegistrationActivity.this,
                                            ActivityOTPVerify.class);
                                    call_to_startactivity.putExtra("class_name", "SellerRegistrationActivity");
                                    startActivity(call_to_startactivity);
                                } else {

                                    AndroidUtils.showSnackBar(registrationLayout,
                                            result.get("message").getAsString());
                                }

                            } else {
                                Log.e("result_seller_error", e.toString());
                                showmessage(e.toString());
                            }

                        }

                    });

        }
    }
}

From source file:com.adeebnqo.Thula.mmssms.Transaction.java

License:Apache License

private void sendRnrSe(String authToken, String rnrse, String number, String text) throws Exception {
    JsonObject json = Ion.with(context).load("https://www.google.com/voice/sms/send/")
            .setHeader("Authorization", "GoogleLogin auth=" + authToken).setBodyParameter("phoneNumber", number)
            .setBodyParameter("sendErrorSms", "0").setBodyParameter("text", text)
            .setBodyParameter("_rnr_se", rnrse).asJsonObject().get();

    if (!json.get("ok").getAsBoolean())
        throw new Exception(json.toString());
}

From source file:com.adobe.acs.commons.adobeio.service.impl.AdobeioHealthcheck.java

License:Apache License

private void execute(final FormattingResultLog resultLog, EndpointService endpoint) {
    resultLog.info("Checking Adobe I/O endpoint {}", endpoint.getId());
    if ("GET".equalsIgnoreCase(endpoint.getMethod())) {
        resultLog.debug("Executing Adobe I/O call to {}", endpoint.getUrl());
        JsonObject json = endpoint.performIO_Action();
        if (json != null) {
            resultLog.debug("JSON-response {}", json.toString());
            if (StringUtils.contains(json.toString(), "error")) {
                resultLog.critical("Error returned from the API-call");
            }/*from   w  ww  .ja va  2s. co m*/
        }
    } else {
        resultLog.debug("Method != GET, but {}", endpoint.getMethod());
    }
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

License:Apache License

private JsonObject processPost(@NotNull final URI uri, @NotNull final JsonObject payload, String[] headers)
        throws IOException {
    HttpPost post = new HttpPost(uri);
    return (payload != null) && isNotBlank(payload.toString()) ? processRequestWithBody(post, payload, headers)
            : new JsonObject();
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

License:Apache License

private JsonObject processPatch(@NotNull final URI uri, @NotNull final JsonObject payload, String[] headers)
        throws IOException {
    HttpPatch patch = new HttpPatch(uri);
    return (payload != null) && isNotBlank(payload.toString()) ? processRequestWithBody(patch, payload, headers)
            : new JsonObject();
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

License:Apache License

private JsonObject processRequestWithBody(@NotNull final HttpEntityEnclosingRequestBase base,
        @NotNull final JsonObject payload, String[] headers) throws IOException {

    StopWatch stopWatch = new StopWatch();
    LOGGER.debug("STARTING STOPWATCH processRequestWithBody");
    stopWatch.start();/*  w  ww. j  av  a 2s. c om*/

    base.setHeader(AUTHORIZATION, BEARER + integrationService.getAccessToken());
    base.setHeader(CACHE_CONTRL, NO_CACHE);
    base.setHeader(X_API_KEY, integrationService.getApiKey());
    base.setHeader(CONTENT_TYPE, CONTENT_TYPE_APPLICATION_JSON);
    if (headers == null || headers.length == 0) {
        addHeaders(base, specificServiceHeaders);
    } else {
        addHeaders(base, convertServiceSpecificHeaders(headers));
    }

    StringEntity input = new StringEntity(payload.toString());
    input.setContentType(CONTENT_TYPE_APPLICATION_JSON);

    if (!base.getClass().isInstance(HttpGet.class)) {
        base.setEntity(input);
    }

    LOGGER.debug("Process call. uri = {}. payload = {}", base.getURI().toString(), payload);

    try (CloseableHttpClient httpClient = helper.getHttpClient(integrationService.getTimeoutinMilliSeconds())) {
        CloseableHttpResponse response = httpClient.execute(base);
        final JsonObject result = responseAsJson(response);

        LOGGER.debug("STOPPING STOPWATCH processRequestWithBody");
        stopWatch.stop();
        LOGGER.debug("Stopwatch time processRequestWithBody: {}", stopWatch);
        stopWatch.reset();
        return result;
    }
}

From source file:com.adobe.acs.commons.audit_log_search.impl.AuditLogSearchServlet.java

License:Apache License

@Override
@SuppressWarnings("squid:S1141")
protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    log.trace("doGet");

    AuditLogSearchRequest req = null;/*from   w w  w .  j a  v a 2s .  c om*/

    JsonObject result = new JsonObject();
    boolean succeeded = true;
    try {
        req = new AuditLogSearchRequest(request);
        log.debug("Loaded search request: {}", req);

        JsonArray results = new JsonArray();
        long count = 0;
        String whereClause = req.getQueryParameters();
        StringBuilder queryBuilder = new StringBuilder("SELECT * FROM [cq:AuditEvent] AS s");
        if (StringUtils.isNotEmpty(whereClause)) {
            queryBuilder.append(" WHERE ").append(whereClause);
        }
        String queryStr = queryBuilder.toString();
        log.debug("Finding audit events with: {}", queryStr);
        ResourceResolver resolver = request.getResourceResolver();
        QueryManager queryManager = resolver.adaptTo(Session.class).getWorkspace().getQueryManager();
        Query query = queryManager.createQuery(queryStr, Query.JCR_SQL2);

        int limit = -1;
        if (StringUtils.isNotEmpty(request.getParameter("limit"))) {
            limit = Integer.parseInt(request.getParameter("limit"), 10);
            if (limit > 0) {
                log.debug("Limiting to {} results", limit);
                query.setLimit(limit);
            }
        }

        NodeIterator nodes = query.execute().getNodes();
        log.debug("Query execution complete!");
        while (nodes.hasNext()) {
            results.add(serializeAuditEvent(resolver.getResource(nodes.nextNode().getPath()), req));
            count++;
        }
        result.addProperty("count", count);
        result.add("events", results);
        log.debug("Found {} audit events", count);
    } catch (ParseException e) {
        log.warn("Encountered exception parsing start / end date", e);
        succeeded = false;
    } catch (RepositoryException e) {
        log.warn("Encountered respository exception attempting to retrieve audit events", e);
        succeeded = false;
    } catch (ClassNotFoundException e) {
        log.warn("Encountered exception deserializing attributes", e);
        succeeded = false;
    }

    result.addProperty("succeeded", succeeded);

    response.setContentType("application/json");
    response.getWriter().write(result.toString());
}

From source file:com.adobe.acs.commons.exporters.impl.users.UsersInitServlet.java

License:Apache License

/**
 * Returns a JSON containing the options available to the form, and any prior saved data that should pre-populate the form.
 * @param request the Sling HTTP Request object
 * @param response the Sling HTTP Response object
 * @throws IOException/*from   w w  w. j a v  a  2  s.c om*/
 * @throws ServletException
 */
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    final JsonObject json = new JsonObject();
    final JsonObject existing = new JsonObject();
    final JsonObject options = new JsonObject();

    try {
        options.add(GROUPS, getGroupOptions(request.getResourceResolver()));
        options.add(GROUP_FILTERS, getGroupFilterOptions());

        final Parameters parameters = new Parameters(request.getResource());
        existing.addProperty(GROUP_FILTER, parameters.getGroupFilter());
        existing.add(GROUPS, new Gson().toJsonTree(Arrays.asList(parameters.getGroups())));
        existing.add(CUSTOM_PROPERTIES, parameters.getCustomPropertiesAsJSON());

        json.add("options", options);
        json.add("form", existing);

    } catch (RepositoryException e) {
        throw new ServletException(e);
    }

    response.getWriter().write(json.toString());
    response.getWriter().flush();
}

From source file:com.adobe.acs.commons.forms.helpers.impl.PostRedirectGetFormHelperImpl.java

License:Apache License

protected final String getQueryParameterValue(Form form) {
    boolean hasData = false;
    final JsonObject jsonData = new JsonObject();

    form = this.clean(form);

    jsonData.addProperty(KEY_FORM_NAME, form.getName());

    Gson gson = new Gson();

    if (form.hasData()) {
        final JsonObject jsonForm = (JsonObject) gson.toJsonTree(form.getData());
        jsonData.add(KEY_FORM, jsonForm);
        hasData = true;//from  ww  w .jav a2  s . c  o m
    }

    if (form.hasErrors()) {
        final JsonObject jsonError = (JsonObject) gson.toJsonTree(form.getErrors());
        jsonData.add(KEY_ERRORS, jsonError);
        hasData = true;
    }

    return hasData ? this.encode(jsonData.toString()) : "";

}