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:club.jmint.mifty.example.ExaClient.java

License:Apache License

public static void main(String[] args) {

    try {/*w  w  w. j  a  v  a  2  s . co m*/
        TTransport transport;
        //      if (true) {
        transport = new TSocket("localhost", 9090);
        //transport.open();
        //      }
        //      else {
        //        /*
        //         * Similar to the server, you can use the parameters to setup client parameters or
        //         * use the default settings. On the client side, you will need a TrustStore which
        //         * contains the trusted certificate along with the public key. 
        //         * For this example it's a self-signed cert. 
        //         */
        //        TSSLTransportParameters params = new TSSLTransportParameters();
        //        params.setTrustStore("../../lib/java/test/.truststore", "thrift", "SunX509", "JKS");
        //        /*
        //         * Get a client transport instead of a server transport. The connection is opened on
        //         * invocation of the factory method, no need to specifically call open()
        //         */
        //        transport = TSSLTransportFactory.getClientSocket("localhost", 9091, 0, params);
        //      }

        TProtocol protocol = new TBinaryProtocol(transport);
        TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol, "ExaService");
        ExaService.Client client = new ExaService.Client(mp1);

        TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "DemoService");
        DemoService.Client client2 = new DemoService.Client(mp2);

        transport.open();

        //first call
        JsonObject pp1 = new JsonObject();
        pp1.addProperty("echo", "How are you!");
        pp1.addProperty("name", "Darren");
        String signP1 = null;
        try {
            signP1 = ParamBuilder.buildSignedParams(pp1.toString(), "miftyExampleKey");
        } catch (CrossException e) {
            e.printStackTrace();
        }
        String ret = client.echo(signP1, false);
        System.out.println(ParamBuilder.checkSignAndRemove(ret, "miftyExampleKey"));

        //second call
        JsonObject pp2 = new JsonObject();
        pp2.addProperty("hello", "Good morning!");
        pp2.addProperty("name", "Darren");
        String signP2 = null;
        try {
            signP2 = ParamBuilder.buildEncryptedParams(
                    ParamBuilder.buildSignedParams(pp2.toString(), "miftyExampleKey"), "miftyExampleKey");
        } catch (CrossException e) {
            e.printStackTrace();
        }
        ret = client.sayHello(signP2, true);
        System.out.println(ParamBuilder.checkSignAndRemove(
                ParamBuilder.buildDecryptedParams(ret, "miftyExampleKey"), "miftyExampleKey"));

        //third call  {"echo":"I am a DEMO","name":"DemoService"}
        JsonObject pp3 = new JsonObject();
        pp3.addProperty("echo", "I am a DEMO");
        pp3.addProperty("name", "DemoService");
        String signP3 = null;
        try {
            signP3 = ParamBuilder.buildEncryptedParams(
                    ParamBuilder.buildSignedParams(pp3.toString(), "miftyExampleKey"), "miftyExampleKey");
        } catch (CrossException e) {
            e.printStackTrace();
        }
        ret = client2.demoSay(signP3, true);
        System.out.println(ParamBuilder.checkSignAndRemove(
                ParamBuilder.buildDecryptedParams(ret, "miftyExampleKey"), "miftyExampleKey"));

        transport.close();
    } catch (TException x) {
        x.printStackTrace();
    } catch (CrossException e1) {
        e1.printStackTrace();
    }

}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private boolean uploadAuthInfo() {
    SharedPreferences prefs = getSharedPreferences(Contants.SHARED_NAME, MODE_PRIVATE);

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("UserId", prefs.getString("UserId", ""));

    String userName = name.getText().toString();
    if (TextUtils.isEmpty(userName))
        return false;
    jsonObject.addProperty("UserName", userName);

    RadioButton radioButton = (RadioButton) findViewById(sexGroup.getCheckedRadioButtonId());
    if (radioButton == null)
        return false;
    String sex = radioButton.getText().toString();
    if (TextUtils.isEmpty(sex))
        return false;
    jsonObject.addProperty("Sex", sex);

    String idNumber = cardNo.getText().toString();
    if (TextUtils.isEmpty(idNumber))
        return false;
    jsonObject.addProperty("IDNumber", idNumber);

    String phoneStr = phone.getText().toString();
    if (TextUtils.isEmpty(phoneStr))
        return false;
    jsonObject.addProperty("Phone", phoneStr);

    String driverId = drivingLicense.getText().toString();
    if (TextUtils.isEmpty(driverId))
        return false;
    jsonObject.addProperty("DriverId", driverId);

    final String vehicleNoSelect = carNumberSelect.getText().toString();
    final String vehicleNo = carNumber.getText().toString();
    if (TextUtils.isEmpty(vehicleNoSelect) || TextUtils.isEmpty(vehicleNo))
        return false;
    jsonObject.addProperty("VehicleNo", vehicleNoSelect + vehicleNo);

    String travelCard = roadTransportPermit.getText().toString();
    if (TextUtils.isEmpty(travelCard))
        return false;
    jsonObject.addProperty("TravelCard", travelCard);

    String gpsNo = gpsSystemNo.getText().toString();
    if (TextUtils.isEmpty(gpsNo))
        return false;
    jsonObject.addProperty("GpsNo", gpsNo);

    if (VehType == -1)
        return false;
    jsonObject.addProperty("VehType", VehType);

    String phone1 = urgentContact.getText().toString();
    if (TextUtils.isEmpty(phone1))
        return false;
    jsonObject.addProperty("Phone1", phone1);

    String width = vehicleWidth.getText().toString();
    if (TextUtils.isEmpty(width))
        return false;
    jsonObject.addProperty("Width", width);

    String height = vehicleHeight.getText().toString();
    if (TextUtils.isEmpty(height))
        return false;
    jsonObject.addProperty("Height", height);

    String length = vehicleLength.getText().toString();
    if (TextUtils.isEmpty(length))
        return false;
    jsonObject.addProperty("Length", length);

    String tons = vehicleMaxCapacity.getText().toString();
    if (TextUtils.isEmpty(tons))
        return false;
    jsonObject.addProperty("Tons", tons);

    String checkCode = phoneVerify.getText().toString();
    if (TextUtils.isEmpty(checkCode))
        return false;
    jsonObject.addProperty("CheckCode", checkCode);

    if (isGetVerify) {
        Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());
        HttpUtil.doPost(AuthFirstActivity.this, Contants.url_TransporterVehicleCheck1, "VehicleCheck1", map,
                new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                        VolleyInterface.mErrorListener) {
                    @Override/*w w  w. j a  va  2  s  . c  o  m*/
                    public void onSuccess(JsonElement result) {
                        Intent intent = new Intent(AuthFirstActivity.this, AuthSecondActivity.class);
                        //intent.putExtra("VehicleNo", vehicleNoSelect + vehicleNo);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onError(VolleyError error) {
                    }

                    @Override
                    public void onStateError(int sta, String msg) {
                        if (!TextUtils.isEmpty(msg)) {
                            showShortToastByString(msg);
                        }
                    }
                });

        return true;
    } else {
        showShortToastByString("???");
        return false;
    }
}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private void getAuthInfo() {
    SharedPreferences prefs = getSharedPreferences(Contants.SHARED_NAME, MODE_PRIVATE);

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("UserID", prefs.getString("UserId", ""));

    Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());
    HttpUtil.doPost(AuthFirstActivity.this, Contants.url_TransporterGetVehicleCheck1, "GetVehicleCheck1", map,
            new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override//from   w w w . j av  a 2 s  . co  m
                public void onSuccess(JsonElement result) {
                    Gson gson = new Gson();
                    VehicleAuth1 vehicleAuth = gson.fromJson(result, VehicleAuth1.class);
                    setAuthInfo(vehicleAuth);
                }

                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private void getCheckCode() {
    String account = urgentContact.getText().toString();
    if (account.isEmpty()) {
        showShortToastByString("???");
        return;/*  ww w.  j a va  2  s.c o  m*/
    }
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("Tel", account);
    Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());

    HttpUtil.doPost(AuthFirstActivity.this, Contants.url_obtainCheckCode, "obtainCheckCode", map,
            new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override
                public void onSuccess(JsonElement result) {
                    isGetVerify = true;
                    Toast.makeText(AuthFirstActivity.this, "????", Toast.LENGTH_SHORT).show();

                    Message message = handler.obtainMessage(1); // Message
                    message.arg1 = 120;
                    handler.sendMessageDelayed(message, 1000); //
                }

                @Override
                public void onError(VolleyError error) {
                    Toast.makeText(AuthFirstActivity.this, "?", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private void getVehicleTypes() {

    JsonObject mJsonObject = new JsonObject();
    Map<String, String> map = EncryptUtil.encryptDES(mJsonObject.toString());

    HttpUtil.doPost(AuthFirstActivity.this, Contants.url_getvehicletypes, "getvehicletypes", map,
            new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override//w  w w. j a  v  a 2 s.  c o m
                public void onSuccess(JsonElement result) {
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<VehicleType>>() {
                    }.getType();
                    final ArrayList<VehicleType> vehicleTypes = gson
                            .fromJson(result.getAsJsonObject().get("VehicleTypeList"), listType);
                    ArrayAdapter<VehicleType> source = new ArrayAdapter<>(AuthFirstActivity.this,
                            android.R.layout.simple_spinner_dropdown_item, vehicleTypes);
                    vehicleType.setAdapter(source);
                    vehicleType.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                            VehType = vehicleTypes.get(arg2).getTypeCode();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {

                        }

                    });
                }

                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:cn.com.caronwer.activity.AuthSecondActivity.java

private void getAuthInfo() {
    SharedPreferences prefs = getSharedPreferences(Contants.SHARED_NAME, MODE_PRIVATE);

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("UserID", prefs.getString("UserId", ""));

    Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());
    HttpUtil.doPost(AuthSecondActivity.this, Contants.url_TransporterGetVehicleCheck2, "GetVehicleCheck2", map,
            new VolleyInterface(AuthSecondActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override/*from www .  ja va  2s.  c  o  m*/
                public void onSuccess(JsonElement result) {
                    Gson gson = new Gson();
                    VehicleAuth2 vehicleAuth = gson.fromJson(result, VehicleAuth2.class);
                    setAuthInfo(vehicleAuth);
                }

                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:cn.com.caronwer.activity.CertificationActivity.java

/**
 * ?//from ww  w  .  ja v a  2 s . c o  m
 */

public void getVehicleTypes() {

    JsonObject mJsonObject = new JsonObject();
    Map<String, String> map = EncryptUtil.encryptDES(mJsonObject.toString());

    HttpUtil.doPost(CertificationActivity.this, Contants.url_getvehicletypes, "getvehicletypes", map,
            new VolleyInterface(CertificationActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override
                public void onSuccess(JsonElement result) {
                    isChange = true;

                }

                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:co.aurasphere.botmill.rasa.service.RasaService.java

License:Open Source License

/**
 * Send train file request./*from   ww w  .j  a va 2s . c  o m*/
 *
 * @param jsonFile the json file
 * @return the training response
 */
public static TrainingResponse sendTrainFileRequest(File jsonFile) {

    JsonParser parser = new JsonParser();
    Object obj;
    try {
        obj = parser.parse(new FileReader(jsonFile));
        JsonObject jsonObject = (JsonObject) obj;
        TrainingResponse resp = RasaService.sendTrainRequest(jsonObject.toString());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

From source file:co.cask.cdap.gateway.router.handlers.SecurityAuthenticationHttpHandler.java

License:Apache License

/**
 * Intercepts the HttpMessage for getting the access token in authorization header
 * @param ctx channel handler context delegated from MessageReceived callback
 * @param msg intercepted HTTP message//from ww  w  . ja  v  a 2s  .  com
 * @param inboundChannel
 * @return {@code true} if the HTTP message has valid Access token
 * @throws Exception
 */
private boolean validateSecuredInterception(ChannelHandlerContext ctx, HttpRequest msg, Channel inboundChannel,
        AuditLogEntry logEntry) throws Exception {
    String auth = msg.getHeader(HttpHeaders.Names.AUTHORIZATION);
    String accessToken = null;

    /*
     * Parse the access token from authorization header.  The header will be in the form:
     *     Authorization: Bearer ACCESSTOKEN
     *
     * where ACCESSTOKEN is the base64 encoded serialized AccessToken instance.
     */
    if (auth != null) {
        int spIndex = auth.trim().indexOf(' ');
        if (spIndex != -1) {
            accessToken = auth.substring(spIndex + 1).trim();
        }
    }

    logEntry.setClientIP(((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress());
    logEntry.setRequestLine(msg.getMethod(), msg.getUri(), msg.getProtocolVersion());

    TokenState tokenState = tokenValidator.validate(accessToken);
    if (!tokenState.isValid()) {
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.UNAUTHORIZED);
        logEntry.setResponseCode(HttpResponseStatus.UNAUTHORIZED.getCode());

        JsonObject jsonObject = new JsonObject();
        if (tokenState == TokenState.MISSING) {
            httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE,
                    String.format("Bearer realm=\"%s\"", realm));
            LOG.debug("Authentication failed due to missing token");

        } else {
            httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE,
                    String.format("Bearer realm=\"%s\" error=\"invalid_token\"" + " error_description=\"%s\"",
                            realm, tokenState.getMsg()));
            jsonObject.addProperty("error", "invalid_token");
            jsonObject.addProperty("error_description", tokenState.getMsg());
            LOG.debug("Authentication failed due to invalid token, reason={};", tokenState);
        }
        JsonArray externalAuthenticationURIs = new JsonArray();

        //Waiting for service to get discovered
        stopWatchWait(externalAuthenticationURIs);

        jsonObject.add("auth_uri", externalAuthenticationURIs);

        ChannelBuffer content = ChannelBuffers.wrappedBuffer(jsonObject.toString().getBytes(Charsets.UTF_8));
        httpResponse.setContent(content);
        int contentLength = content.readableBytes();
        httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
        httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8");
        logEntry.setResponseContentLength(new Long(contentLength));
        ChannelFuture writeFuture = Channels.future(inboundChannel);
        Channels.write(ctx, writeFuture, httpResponse);
        writeFuture.addListener(ChannelFutureListener.CLOSE);
        return false;
    } else {
        AccessTokenTransformer.AccessTokenIdentifierPair accessTokenIdentifierPair = accessTokenTransformer
                .transform(accessToken);
        logEntry.setUserName(accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
        msg.setHeader(HttpHeaders.Names.AUTHORIZATION,
                "CDAP-verified " + accessTokenIdentifierPair.getAccessTokenIdentifierStr());
        msg.setHeader(Constants.Security.Headers.USER_ID,
                accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
        msg.setHeader(Constants.Security.Headers.USER_IP,
                ((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress());
        return true;
    }
}

From source file:co.cask.cdap.internal.AppFabricClient.java

License:Apache License

public void setWorkerInstances(String namespaceId, String appId, String workerId, int instances)
        throws Exception {
    MockResponder responder = new MockResponder();
    String uri = String.format("%s/apps/%s/worker/%s/instances", getNamespacePath(namespaceId), appId,
            workerId);/*w w  w .  ja v  a 2s  .c o m*/
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    programLifecycleHttpHandler.setWorkerInstances(request, responder, namespaceId, appId, workerId);
    verifyResponse(HttpResponseStatus.OK, responder.getStatus(), "Set worker instances failed");
}