List of usage examples for com.google.gson JsonObject JsonObject
JsonObject
From source file:club.jmint.crossing.specs.ServiceSpecsExmpleCallImpl.java
License:Apache License
/** * Demo non-encrypted interface with simple input parameters and output response. * @param params wrappered with JSON format: <br/> * "{"sign":"XXXXYYYYZZZZAAAABBBBCCCCCFFFFJJJJ","params":{"name":"Shao Huicheng","say":"Hello, World","job":"Software Engineer","skills":"Programming,People Management etc."}}" * @param encrypt params is encrypted or not * @return wrappered with JSON format: <br/> * "{"sign":"XXXXCCCCCFFFFJJJJYYYYZZZZAAAABBBB","errorCode":"0","errorInfo":"success", * "params":{"sentence":"Hi, Huicheng. Glad to hear you having finished the Crossing Project. I am deeply impressed with this project."}" *//* w w w .j a v a2s . co m*/ public String getSimpleReply(String params, boolean encrypt) { //parse parameters and verify signature JsonObject ip; try { ip = parseInputParams(params, encrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //validate parameters on business side String name, say, job, skills; try { name = getParamAsString(ip, "name"); say = getParamAsString(ip, "say"); job = getParamAsString(ip, "job"); skills = getParamAsString(ip, "skills"); } catch (CrossException ce) { return buildOutputByCrossException(ce); } System.out.println("name: " + name); System.out.println("say: " + say); System.out.println("job: " + job); System.out.println("skills: " + skills); //do more checks here //do your business logics String sentence = "Hi, " + name + "Glad to hear you having finished the Crossing Project. I am deeply impressed with this project."; //do more things here. //build response parameters JsonObject op = new JsonObject(); op.addProperty("sentence", sentence); String output = null; try { output = buildOutputParams(op, encrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } return output; }
From source file:club.jmint.crossing.specs.ServiceSpecsExmpleCallImpl.java
License:Apache License
/** * Demo encrypted interface with simple parameters * @param params <br/>//from w ww .j a va 2s .c om * "{"encrypted":"19adkfljj;adfmzfjk;[afakfjkl;adjfqrdkjk;akdfjkjkdajfjkjkadfkjdajf"}" <br/> * corresponding plain text: "{"sign":"DDDDTTTTZZZZAAAABBBBCCCCCFFFFJJJJ","params":{"s1":"Are","s2":"you","s3":"ready?"}}" * @param encrypt * @return <br/> * {"encrypted":"134780akfd;jadhadleiuqptihjadghlnzvadfjkj/dfa","errorCode":"0","erroDesc":"success"} <br/> * corresponding plain text: "{"sign":"EEEESSSSFFFFJJJJYYYYZZZZAAAABBBB","errorCode":"0","errorInfo":"success","params":{"reply":"Yes, I am ready."}}" */ public String doCopyMe(String params, boolean encrypt) { //parse parameters and verify signature JsonObject ip; try { ip = parseInputParams(params, encrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //validate parameters on business side String s1, s2, s3; try { s1 = getParamAsString(ip, "s1"); s2 = getParamAsString(ip, "s2"); s3 = getParamAsString(ip, "s3"); } catch (CrossException ce) { return buildOutputByCrossException(ce); } System.out.println("s1: " + s1); System.out.println("s2: " + s2); System.out.println("s3: " + s3); //do more checks here //do your business logics String copyme = s1 + " " + s2 + " " + s3; //do more things here. //build response parameters JsonObject op = new JsonObject(); op.addProperty("sentence", copyme); String output = null; try { output = buildOutputParams(op, encrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } return output; }
From source file:club.jmint.mifty.example.ExaClient.java
License:Apache License
public static void main(String[] args) { try {// ww w. j a v a2s. c o 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:club.jmint.mifty.example.ExaServiceImpl.java
License:Apache License
/** * @param {"hello":"Good morning!","name":"Darren"} *///w ww .j a v a 2 s. com public String sayHello(String params, boolean isEncrypt) throws TException { //parse parameters and verify signature CrossLog.logger.debug("sayHello: " + params); JsonObject ip; try { ip = parseInputParams(params, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //validate parameters on business side String name, hello; try { name = getParamAsString(ip, "name"); hello = getParamAsString(ip, "hello"); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //do more checks here if you need. Session session = Dao.getSessionFactory().openSession(); session.beginTransaction(); session.createSQLQuery("insert into test.user (uid,name) values (3,'zhouguoxing'); ").executeUpdate(); SQLQuery sq = session.createSQLQuery("select * from test.user;"); System.out.println(sq.getFirstResult()); session.createSQLQuery("delete from test.user where uid=1; ").executeUpdate(); session.getTransaction().commit(); session.close(); //do your business logics System.out.println("name: " + name); System.out.println("hello: " + hello); CrossLog.logger.info("\nname: " + name + "\nsay: " + hello); String sentence = "Hi, " + name + " ," + hello; //do more things here. //build response parameters JsonObject op = new JsonObject(); op.addProperty("sentence", sentence); String output = null; try { output = buildOutputParams(op, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } CrossLog.logger.debug("sayHello: " + output); return output; }
From source file:club.jmint.mifty.example.ExaServiceImpl.java
License:Apache License
/** * @param {"echo":"I am back","name":"Darren"} *//*from ww w . j a va2 s. c om*/ public String echo(String params, boolean isEncrypt) throws TException { //parse parameters and verify signature CrossLog.logger.debug("echo: " + params); JsonObject ip; try { ip = parseInputParams(params, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //validate parameters on business side String name, echo; try { name = getParamAsString(ip, "name"); echo = getParamAsString(ip, "echo"); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //do more checks here if you need. //do your business logics System.out.println("name: " + name); System.out.println("echo: " + echo); CrossLog.logger.info("\nname: " + name + "\nsay: " + echo); String sentence = "Hi, " + name + " ," + echo; //do more things here. //build response parameters JsonObject op = new JsonObject(); op.addProperty("sentence", sentence); String output = null; try { output = buildOutputParams(op, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } CrossLog.logger.debug("sayHello: " + output); return output; }
From source file:club.jmint.mifty.service.DemoServiceImpl.java
License:Apache License
/** * @param {"echo":"I am a DEMO","name":"DemoService"} *//*from w w w. j a v a 2 s .c o m*/ public String demoSay(String params, boolean isEncrypt) throws TException { //parse parameters and verify signature CrossLog.logger.debug("echo: " + params); JsonObject ip; try { ip = parseInputParams(params, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //validate parameters on business side String name, echo; try { name = getParamAsString(ip, "name"); echo = getParamAsString(ip, "echo"); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //do more checks here if you need. //do your business logics System.out.println("name: " + name); System.out.println("echo: " + echo); CrossLog.logger.info("\nname: " + name + "\nsay: " + echo); String sentence = "Hi, " + name + " ," + echo; //do more things here. //build response parameters JsonObject op = new JsonObject(); op.addProperty("sentence", sentence); String output = null; try { output = buildOutputParams(op, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } CrossLog.logger.debug("sayHello: " + output); return output; }
From source file:club.jmint.mifty.service.MiftyService.java
License:Apache License
public String callProxy(String method, String params, boolean isEncrypt) throws TException { //parse parameters and verify signature CrossLog.logger.debug("callProxy: " + method + "(in: " + params + ")"); JsonObject ip;/*from w w w .j a va 2s .co m*/ try { ip = parseInputParams(params, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //extract all parameters HashMap<String, String> inputMap = new HashMap<String, String>(); Iterator<Entry<String, JsonElement>> it = ip.entrySet().iterator(); Entry<String, JsonElement> en = null; String key; JsonElement je; while (it.hasNext()) { en = it.next(); key = en.getKey(); je = en.getValue(); if (je.isJsonArray()) { inputMap.put(key, je.getAsJsonArray().toString()); //System.out.println(je.getAsJsonArray().toString()); } else if (je.isJsonNull()) { inputMap.put(key, je.getAsJsonNull().toString()); //System.out.println(je.getAsJsonNull().toString()); } else if (je.isJsonObject()) { inputMap.put(key, je.getAsJsonObject().toString()); //System.out.println(je.getAsJsonObject().toString()); } else if (je.isJsonPrimitive()) { inputMap.put(key, je.getAsJsonPrimitive().getAsString()); //System.out.println(je.getAsJsonPrimitive().toString()); } else { //unkown type; } } //execute specific method Method[] ma = this.getClass().getMethods(); int idx = 0; for (int i = 0; i < ma.length; i++) { if (ma[i].getName().equals(method)) { idx = i; break; } } HashMap<String, String> outputMap = null; try { Method m = this.getClass().getDeclaredMethod(method, ma[idx].getParameterTypes()); outputMap = (HashMap<String, String>) m.invoke(this, inputMap); CrossLog.logger.debug("callProxy: " + method + "() executed."); } catch (NoSuchMethodException nsm) { CrossLog.logger.error("callProxy: " + method + "() not found."); CrossLog.printStackTrace(nsm); return buildOutputError(ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getCode(), ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getInfo()); } catch (Exception e) { CrossLog.logger.error("callProxy: " + method + "() executed with exception."); CrossLog.printStackTrace(e); if (e instanceof CrossException) { return buildOutputByCrossException((CrossException) e); } else { return buildOutputError(ErrorCode.COMMON_ERR_UNKOWN.getCode(), ErrorCode.COMMON_ERR_UNKOWN.getInfo()); } } //if got error then return immediately String ec = outputMap.get("errorCode"); String ecInfo = outputMap.get("errorInfo"); if ((ec != null) && (!ec.isEmpty())) { return buildOutputError(Integer.parseInt(ec), ecInfo); } //build response parameters JsonObject op = new JsonObject(); Iterator<Entry<String, String>> ito = outputMap.entrySet().iterator(); Entry<String, String> eno = null; JsonParser jpo = new JsonParser(); JsonElement jeo = null; while (ito.hasNext()) { eno = ito.next(); try { jeo = jpo.parse(eno.getValue()); } catch (JsonSyntaxException e) { // MyLog.logger.error("callProxy: Malformed output parameters["+eno.getKey()+"]."); // return buildOutputError(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), // ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); //we do assume that it should be a common string jeo = new JsonPrimitive(eno.getValue()); } op.add(eno.getKey(), jeo); } String output = null; try { output = buildOutputParams(op, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } CrossLog.logger.debug("callProxy: " + method + "(out: " + output + ")"); return output; }
From source file:cmput301.f13t01.elasticsearch.InterfaceAdapter.java
License:GNU General Public License
/** * This allows for the serialization of objects that use an interface to be * wrapped and retain memory of its type. * //from w w w . ja v a 2 s. c o m * @return Returns the JsonElement to be used by Gson */ public JsonElement serialize(T object, Type interfaceType, JsonSerializationContext context) { final JsonObject wrapper = new JsonObject(); wrapper.addProperty("type", object.getClass().getName()); wrapper.add("data", context.serialize(object)); return wrapper; }
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//from www. j ava 2s. c om 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 a v a 2s . c o 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); } } }); }