List of usage examples for com.google.gson JsonObject add
public void add(String property, JsonElement value)
From source file:clientcommunicator.Server.Cookie.java
private JsonObject getUserJsonObject(JsonElement element, boolean setNew) throws MalformedCookieException { JsonObject jobject = element.getAsJsonObject(); if (!jobject.has("playerID")) { throw new MalformedCookieException(); }//w ww. jav a 2s. c om JsonObject resultingCookie = new JsonObject(); resultingCookie.add("name", jobject.get("name")); resultingCookie.add("password", jobject.get("password")); resultingCookie.add("playerID", jobject.get("playerID")); if (setNew) { try { String realCookie = resultingCookie.toString(); realCookie = java.net.URLEncoder.encode(realCookie, "UTF-8"); this.userInformationString = realCookie; } catch (UnsupportedEncodingException ex) { Logger.getLogger(Cookie.class.getName()).log(Level.SEVERE, null, ex); } } return jobject; }
From source file:club.jmint.crossing.specs.CrossingService.java
License:Apache License
/** * //w ww .j a va2 s . c o m * @param obj * @param encrypt * @return */ protected String buildOutputParams(JsonObject obj, boolean encrypt) throws CrossException { if (obj == null || obj.toString().isEmpty()) { //we do resume that it's successful without any response parameters. JsonObject jo = new JsonObject(); jo.addProperty("errorCode", ErrorCode.SUCCESS.getCode()); jo.addProperty("errorInfo", ErrorCode.SUCCESS.getInfo()); return jo.toString(); } //create signature String op = obj.toString(); String signValue = buildSign(op, signKey); JsonObject jo = new JsonObject(); jo.addProperty("sign", signValue); jo.add("params", obj); String encrypted; if (encrypt) { //encrypt output encrypted = buildEncrypt(jo.toString()); JsonObject joen = new JsonObject(); joen.addProperty("encrypted", encrypted); joen.addProperty("errorCode", ErrorCode.SUCCESS.getCode()); joen.addProperty("errorInfo", ErrorCode.SUCCESS.getInfo()); return joen.toString(); } else { //non-encrypt output jo.addProperty("errorCode", ErrorCode.SUCCESS.getCode()); jo.addProperty("errorInfo", ErrorCode.SUCCESS.getInfo()); return jo.toString(); } }
From source file:club.jmint.crossing.specs.ParamBuilder.java
License:Apache License
public static String buildSignedParams(String p, String signKey) throws CrossException { String md5Value = Security.crossingSign(p, signKey, ""); JsonObject jo = new JsonObject(); jo.addProperty("sign", md5Value); JsonParser jp = new JsonParser(); JsonElement jop = null;/*from w w w .j a va 2 s . c o m*/ try { jop = jp.parse(p); if (!jop.isJsonObject()) { throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } } catch (JsonSyntaxException jse) { throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } jo.add("params", jop); return jo.toString(); }
From source file:club.jmint.crossing.specs.ParamBuilder.java
License:Apache License
public static String checkSignAndRemove(String p, String signKey) throws CrossException { JsonParser jp = new JsonParser(); JsonElement jop = null;//from www . ja va 2 s. c om try { jop = jp.parse(p); if (!jop.isJsonObject()) { throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } } catch (JsonSyntaxException jse) { //jse.printStackTrace(); throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } JsonObject jo = (JsonObject) jop; String np = null; if (jo.has("sign") || jo.has("params")) { String sign = jo.getAsJsonPrimitive("sign").getAsString(); np = jo.getAsJsonObject("params").toString(); String signValue = Security.crossingSign(np, signKey, ""); if (!sign.equals(signValue)) { throw new CrossException(ErrorCode.COMMON_ERR_SIGN_BAD.getCode(), ErrorCode.COMMON_ERR_SIGN_BAD.getInfo()); } //remove sign field only and return Iterator<Entry<String, JsonElement>> it = jo.entrySet().iterator(); JsonObject rjo = new JsonObject(); Entry<String, JsonElement> en; while (it.hasNext()) { en = it.next(); if (!en.getKey().equals("sign")) { rjo.add(en.getKey(), en.getValue()); } } return rjo.toString(); } return p; }
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;/* www . j a v a 2s. c o 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.edu.zjnu.acm.judge.util.excel.ExcelUtil.java
License:Apache License
private static <T> T parseRow(FormulaEvaluator evaluator, Row row, Map<Integer, String> fields, Class<T> type) { JsonObject jsonObject = new JsonObject(); for (Iterator<Cell> it = row.cellIterator(); it.hasNext();) { Cell cell = it.next();/*from w w w.j a va 2 s . co m*/ String name = fields.get(cell.getColumnIndex()); if (name != null) { JsonElement cellValue = parseAsJsonElement(cell, evaluator); if (cellValue != null) { jsonObject.add(name, cellValue); } } } return GsonHolder.GSON.fromJson(jsonObject, type); }
From source file:co.aikar.timings.TimingsExport.java
License:MIT License
/** * Builds a JSON timings report and sends it to Aikar's viewer * * @param sender Sender that issued the command *///from w w w . j a v a 2 s . c o m public static void reportTimings(CommandSender sender) { JsonObject out = new JsonObject(); out.addProperty("version", Server.getInstance().getVersion()); out.addProperty("maxplayers", Server.getInstance().getMaxPlayers()); out.addProperty("start", TimingsManager.timingStart / 1000); out.addProperty("end", System.currentTimeMillis() / 1000); out.addProperty("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000); if (!Timings.isPrivacy()) { out.addProperty("server", Server.getInstance().getName()); out.addProperty("motd", Server.getInstance().getMotd()); out.addProperty("online-mode", false); //In MCPE we have permanent offline mode. out.addProperty("icon", ""); //"data:image/png;base64," } final Runtime runtime = Runtime.getRuntime(); RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); JsonObject system = new JsonObject(); system.addProperty("timingcost", getCost()); system.addProperty("name", System.getProperty("os.name")); system.addProperty("version", System.getProperty("os.version")); system.addProperty("jvmversion", System.getProperty("java.version")); system.addProperty("arch", System.getProperty("os.arch")); system.addProperty("maxmem", runtime.maxMemory()); system.addProperty("cpu", runtime.availableProcessors()); system.addProperty("runtime", ManagementFactory.getRuntimeMXBean().getUptime()); system.addProperty("flags", String.join(" ", runtimeBean.getInputArguments())); system.add("gc", JsonUtil.mapToObject(ManagementFactory.getGarbageCollectorMXBeans(), (input) -> new JsonUtil.JSONPair(input.getName(), JsonUtil.toArray(input.getCollectionCount(), input.getCollectionTime())))); out.add("system", system); TimingsHistory[] history = HISTORY.toArray(new TimingsHistory[HISTORY.size() + 1]); history[HISTORY.size()] = new TimingsHistory(); //Current snapshot JsonObject timings = new JsonObject(); for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) { for (Timing id : group.timings.stream().toArray(Timing[]::new)) { if (!id.timed && !id.isSpecial()) { continue; } timings.add(String.valueOf(id.id), JsonUtil.toArray(group.id, id.name)); } } JsonObject idmap = new JsonObject(); idmap.add("groups", JsonUtil.mapToObject(TimingIdentifier.GROUP_MAP.values(), (group) -> new JsonUtil.JSONPair(group.id, group.name))); idmap.add("handlers", timings); idmap.add("worlds", JsonUtil.mapToObject(TimingsHistory.levelMap.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getValue(), entry.getKey()))); idmap.add("tileentity", JsonUtil.mapToObject(TimingsHistory.blockEntityMap.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue()))); idmap.add("entity", JsonUtil.mapToObject(TimingsHistory.entityMap.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue()))); out.add("idmap", idmap); //Information about loaded plugins out.add("plugins", JsonUtil.mapToObject(Server.getInstance().getPluginManager().getPlugins().values(), (plugin) -> { JsonObject jsonPlugin = new JsonObject(); jsonPlugin.addProperty("version", plugin.getDescription().getVersion()); jsonPlugin.addProperty("description", plugin.getDescription().getDescription());// Sounds legit jsonPlugin.addProperty("website", plugin.getDescription().getWebsite()); jsonPlugin.addProperty("authors", String.join(", ", plugin.getDescription().getAuthors())); return new JsonUtil.JSONPair(plugin.getName(), jsonPlugin); })); //Information on the users Config JsonObject config = new JsonObject(); if (!Timings.getIgnoredConfigSections().contains("all")) { JsonObject nukkit = JsonUtil.toObject(Server.getInstance().getConfig().getRootSection()); Timings.getIgnoredConfigSections().forEach(nukkit::remove); config.add("nukkit", nukkit); } else { config.add("nukkit", null); } out.add("config", config); new TimingsExport(sender, out, history).start(); }
From source file:co.aikar.timings.TimingsHistory.java
License:MIT License
JsonObject export() { JsonObject json = new JsonObject(); json.addProperty("s", this.startTime); json.addProperty("e", this.endTime); json.addProperty("tk", this.totalTicks); json.addProperty("tm", this.totalTime); json.add("w", this.levels); json.add("h", JsonUtil.mapToArray(this.entries, (entry) -> { if (entry.data.count == 0) { return null; }/*w w w . j av a 2s . c om*/ return entry.export(); })); json.add("mp", JsonUtil.mapToArray(this.minuteReports, MinuteReport::export)); return json; }
From source file:co.cask.cdap.api.dataset.lib.ConditionCodec.java
License:Apache License
@Override public JsonElement serialize(PartitionFilter.Condition condition, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("fieldName", condition.getFieldName()); jsonObj.add("lower", serializeComparable(condition.getLower(), jsonSerializationContext)); jsonObj.add("upper", serializeComparable(condition.getUpper(), jsonSerializationContext)); jsonObj.addProperty("isSingleValue", condition.isSingleValue()); return jsonObj; }