@Override public JsonElement serialize(Operator op, Type type, JsonSerializationContext jsc) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(PlanExpressionConstants.CONTAINERNAME, op.containerName); jsonObject.addProperty(PlanExpressionConstants.OPERATOR, op.operator); jsonObject.addProperty(PlanExpressionConstants.OPERATORNAME, op.operatorName); if (op.queryString != null) { jsonObject.addProperty(PlanExpressionConstants.QUERYSTRING, op.queryString); } if (op.locations != null) { JsonParser parser = new JsonParser(); JsonArray locations = new JsonArray(); for (URL url : op.locations) { locations.add(parser.parse(url.toString())); } jsonObject.add(PlanExpressionConstants.LOCATIONS, locations); } if (op.paramList != null) { JsonParser parser = new JsonParser(); JsonArray params = new JsonArray(); for (Parameter param : op.paramList) { JsonArray p = new JsonArray(); p.add(parser.parse(param.name)); p.add(parser.parse(param.value)); params.add(p); } jsonObject.add(PlanExpressionConstants.PARAMETERS, params); } return jsonObject; }
private static void addFolder(FileSystem fs, Path p, JsonArray succeeded, JsonArray failed) { try { if (fs == null) return; for (FileStatus file : fs.listStatus(p)) { Path pfs = file.getPath(); if (file.isDir()) { addFolder(fs, pfs, succeeded, failed); } else { Key k = Key.make(pfs.toString()); long size = file.getLen(); Value val = null; if (pfs.getName().endsWith(Extensions.JSON)) { JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new InputStreamReader(fs.open(pfs))).getAsJsonObject(); JsonElement v = json.get(Constants.VERSION); if (v == null) throw new RuntimeException("Missing version"); JsonElement type = json.get(Constants.TYPE); if (type == null) throw new RuntimeException("Missing type"); Class c = Class.forName(type.getAsString()); OldModel model = (OldModel) c.newInstance(); model.fromJson(json); } else if (pfs.getName().endsWith(Extensions.HEX)) { // Hex file? FSDataInputStream s = fs.open(pfs); int sz = (int) Math.min(1L << 20, size); // Read up to the 1st meg byte[] mem = MemoryManager.malloc1(sz); s.readFully(mem); // Convert to a ValueArray (hope it fits in 1Meg!) ValueArray ary = new ValueArray(k, 0).read(new AutoBuffer(mem)); val = new Value(k, ary, Value.HDFS); } else if (size >= 2 * ValueArray.CHUNK_SZ) { val = new Value( k, new ValueArray(k, size), Value.HDFS); // ValueArray byte wrapper over a large file } else { val = new Value(k, (int) size, Value.HDFS); // Plain Value val.setdsk(); } DKV.put(k, val); Log.info("PersistHdfs: DKV.put(" + k + ")"); JsonObject o = new JsonObject(); o.addProperty(Constants.KEY, k.toString()); o.addProperty(Constants.FILE, pfs.toString()); o.addProperty(Constants.VALUE_SIZE, file.getLen()); succeeded.add(o); } } } catch (Exception e) { Log.err(e); JsonObject o = new JsonObject(); o.addProperty(Constants.FILE, p.toString()); o.addProperty(Constants.ERROR, e.getMessage()); failed.add(o); } }
public JsonObject toJson() { JsonObject res = new JsonObject(); JsonArray rows = new JsonArray(); for (int i = 0; i < _rows.length; ++i) rows.add(new JsonPrimitive(_rows[i])); JsonArray dist = new JsonArray(); for (int i = 0; i < _dist.length; ++i) dist.add(new JsonPrimitive(_dist[i])); res.add("rows_per_cluster", rows); res.add("sqr_error_per_cluster", dist); return res; }
@Override public JsonElement serialize(WxCpUser user, Type typeOfSrc, JsonSerializationContext context) { JsonObject o = new JsonObject(); if (user.getUserId() != null) { o.addProperty("userid", user.getUserId()); } if (user.getName() != null) { o.addProperty("name", user.getName()); } if (user.getDepartIds() != null) { JsonArray jsonArray = new JsonArray(); for (Integer departId : user.getDepartIds()) { jsonArray.add(new JsonPrimitive(departId)); } o.add("department", jsonArray); } if (user.getPosition() != null) { o.addProperty("position", user.getPosition()); } if (user.getMobile() != null) { o.addProperty("mobile", user.getMobile()); } if (user.getGender() != null) { o.addProperty("gender", user.getGender().equals("男") ? 0 : 1); } if (user.getTel() != null) { o.addProperty("tel", user.getTel()); } if (user.getEmail() != null) { o.addProperty("email", user.getEmail()); } if (user.getWeiXinId() != null) { o.addProperty("weixinid", user.getWeiXinId()); } if (user.getAvatar() != null) { o.addProperty("avatar", user.getAvatar()); } if (user.getStatus() != null) { o.addProperty("status", user.getStatus()); } if (user.getExtAttrs().size() > 0) { JsonArray attrsJsonArray = new JsonArray(); for (WxCpUser.Attr attr : user.getExtAttrs()) { JsonObject attrJson = new JsonObject(); attrJson.addProperty("name", attr.getName()); attrJson.addProperty("value", attr.getValue()); attrsJsonArray.add(attrJson); } JsonObject attrsJson = new JsonObject(); attrsJson.add("attrs", attrsJsonArray); o.add("extattr", attrsJson); } return o; }
@Override public JsonObject toJson() { JsonObject res = new JsonObject(); res.addProperty(Constants.VERSION, H2O.VERSION); res.addProperty(Constants.TYPE, KMeansModel.class.getName()); res.addProperty(Constants.ERROR, _error); JsonArray ary = new JsonArray(); for (double[] dd : clusters()) { JsonArray ary2 = new JsonArray(); for (double d : dd) ary2.add(new JsonPrimitive(d)); ary.add(ary2); } res.add(Constants.CLUSTERS, ary); return res; }
private static JsonArray deepCopyArr(JsonArray from) { JsonArray result = new JsonArray(); for (JsonElement element : from) { result.add(deepCopy(element)); } return result; }
private JsonArray serializeIterable( Iterable value, Type typeOfSrc, JsonSerializationContext context, String localPropertyView, int depth) { JsonArray property = new JsonArray(); for (Object o : value) { // non-null check in case a lazy evaluator returns null if (o != null) { if (o instanceof GraphObject) { GraphObject obj = (GraphObject) o; JsonElement recursiveSerializedValue = this.serializeFlatNameValue(obj, typeOfSrc, context, localPropertyView, depth + 1); if (recursiveSerializedValue != null) { property.add(recursiveSerializedValue); } } else if (o instanceof Map) { property.add( serializeMap((Map) o, typeOfSrc, context, localPropertyView, false, false, depth)); } else if (o instanceof Iterable) { property.add( serializeIterable((Iterable) o, typeOfSrc, context, localPropertyView, depth)); } else { // serialize primitive, this is for PropertyNotion // property.add(new JsonPrimitive(o.toString())); property.add(primitive(o)); } } } return property; }
public void processListing(ObjectListing listing, JsonArray succ, JsonArray fail) { for (S3ObjectSummary obj : listing.getObjectSummaries()) { try { Key k = PersistS3.loadKey(obj); JsonObject o = new JsonObject(); o.addProperty(KEY, k.toString()); o.addProperty(FILE, obj.getKey()); o.addProperty(VALUE_SIZE, obj.getSize()); succ.add(o); } catch (IOException e) { JsonObject o = new JsonObject(); o.addProperty(FILE, obj.getKey()); o.addProperty(ERROR, e.getMessage()); fail.add(o); } } }
/** * Creates a new JsonArray that contains the JSON representations of the given <code>boolean * </code> values. * * @param values the values to be included in the new JSON array * @return a new JSON array that contains the given values */ public static JsonArray array(boolean... values) { if (values == null) { throw new NullPointerException("values is null"); } JsonArray array = new JsonArray(); for (boolean value : values) { array.add(value); } return array; }
/** * Creates a new JsonArray that contains the JSON representations of the given strings. * * @param strings the strings to be included in the new JSON array * @return a new JSON array that contains the given strings */ public static JsonArray array(String... strings) { if (strings == null) { throw new NullPointerException("values is null"); } JsonArray array = new JsonArray(); for (String value : strings) { array.add(value); } return array; }
public static void addFolder(Path p, JsonArray succeeded, JsonArray failed) throws IOException { FileSystem fs = FileSystem.get(p.toUri(), PersistHdfs.CONF); if (!fs.exists(p)) { JsonObject o = new JsonObject(); o.addProperty(Constants.FILE, p.toString()); o.addProperty(Constants.ERROR, "Path does not exist!"); failed.add(o); return; } addFolder(fs, p, succeeded, failed); }
@Override public JsonElement serialize( DeviceIconType deviceIcon, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonDeviceIconType = new JsonObject(); for (Position.Status status : Position.Status.values()) { PositionIconType positionIcon = deviceIcon.getPositionIconType(status); JsonObject jsonPositionIconType = new JsonObject(); jsonPositionIconType.addProperty("width", positionIcon.getWidth()); jsonPositionIconType.addProperty("height", positionIcon.getHeight()); JsonArray urls = new JsonArray(); urls.add(new JsonPrimitive(positionIcon.getURL(false))); urls.add(new JsonPrimitive(positionIcon.getURL(true))); jsonPositionIconType.add("urls", urls); jsonDeviceIconType.add(status.name(), jsonPositionIconType); } return jsonDeviceIconType; }
@Override public JsonElement serialize( DeviceOption[] src, Type typeOfSrc, JsonSerializationContext context) { JsonArray jsonObject = new JsonArray(); for (DeviceOption option : src) { JsonObject newObject = new JsonObject(); newObject.addProperty("property", option.getProperty()); newObject.addProperty("name", option.getName()); newObject.addProperty("description", option.getDescription()); newObject.addProperty("readonly", option.isReadOnly()); newObject.addProperty("type", option.getType().toString()); JsonArray newArray = new JsonArray(); for (String value : option.getValidValues()) { newArray.add(value); } newObject.add("validValues", newArray); if (option.isArray()) { newArray = new JsonArray(); for (String value : option.getArrayValue()) { newArray.add(value); } newObject.add("values", newArray); } else { newObject.addProperty("value", option.getValue()); } jsonObject.add(newObject); } return jsonObject; }
private final void Elements(JsonArray array) throws ParseException { JsonElement element; element = JsonValue(); switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case 23: jj_consume_token(23); Elements(array); break; default: jj_la1[4] = jj_gen; ; } array.add(element); }
@Override protected Response serve() { int tasks = 0; int finished = 0; RFModel model = _modelKey.value(); double[] weights = _weights.value(); // Finish refresh after rf model is done and confusion matrix for all trees is computed boolean done = false; int classCol = _classCol.specified() ? _classCol.value() : findResponseIdx(model); tasks = model._totalTrees; finished = model.size(); // Handle cancelled/aborted jobs if (_job.value() != null) { Job jjob = Job.findJob(_job.value()); if (jjob != null && jjob.isCancelled()) return Response.error( jjob.exception == null ? "Job was cancelled by user!" : jjob.exception); } JsonObject response = defaultJsonResponse(); // CM return and possible computation is requested if (!_noCM.value() && (finished == tasks || _iterativeCM.value()) && finished > 0) { // Compute the highest number of trees which is less then a threshold int modelSize = tasks * _refreshThresholdCM.value() / 100; modelSize = modelSize == 0 || finished == tasks ? finished : modelSize * (finished / modelSize); // Get the computing the matrix - if no job is computing, then start a new job Job cmJob = ConfusionTask.make( model, modelSize, _dataKey.value()._key, classCol, weights, _oobee.value()); // Here the the job is running - it saved a CM which can be already finished or in invalid // state. CMFinal confusion = UKV.get(cmJob.dest()); // if the matrix is valid, report it in the JSON if (confusion != null && confusion.valid() && modelSize > 0) { // finished += 1; JsonObject cm = new JsonObject(); JsonArray cmHeader = new JsonArray(); JsonArray matrix = new JsonArray(); cm.addProperty(JSON_CM_TYPE, _oobee.value() ? "OOB error estimate" : "full scoring"); cm.addProperty(JSON_CM_CLASS_ERR, confusion.classError()); cm.addProperty(JSON_CM_ROWS_SKIPPED, confusion.skippedRows()); cm.addProperty(JSON_CM_ROWS, confusion.rows()); // create the header for (String s : cfDomain(confusion, 1024)) cmHeader.add(new JsonPrimitive(s)); cm.add(JSON_CM_HEADER, cmHeader); // add the matrix final int nclasses = confusion.dimension(); JsonArray classErrors = new JsonArray(); for (int crow = 0; crow < nclasses; ++crow) { JsonArray row = new JsonArray(); int classHitScore = 0; for (int ccol = 0; ccol < nclasses; ++ccol) { row.add(new JsonPrimitive(confusion.matrix(crow, ccol))); if (crow != ccol) classHitScore += confusion.matrix(crow, ccol); } // produce infinity members in case of 0.f/0 classErrors.add( new JsonPrimitive( (float) classHitScore / (classHitScore + confusion.matrix(crow, crow)))); matrix.add(row); } cm.add(JSON_CM_CLASSES_ERRORS, classErrors); cm.add(JSON_CM_MATRIX, matrix); cm.addProperty(JSON_CM_TREES, modelSize); response.add(JSON_CM, cm); // Signal end only and only if all trees were generated and confusion matrix is valid done = finished == tasks; } } else if (_noCM.value() && finished == tasks) done = true; // Trees JsonObject trees = new JsonObject(); trees.addProperty(Constants.TREE_COUNT, model.size()); if (model.size() > 0) { trees.add(Constants.TREE_DEPTH, model.depth().toJson()); trees.add(Constants.TREE_LEAVES, model.leaves().toJson()); } response.add(Constants.TREES, trees); // Build a response Response r; if (done) { r = jobDone(response); r.addHeader( "<div class='alert'>" + /*RFScore.link(MODEL_KEY, model._key, "Use this model for scoring.") */ GeneratePredictionsPage .link(model._key, "Predict!") + " </div>"); } else { r = Response.poll(response, finished, tasks); } r.setBuilder(JSON_CM, new ConfusionMatrixBuilder()); r.setBuilder(TREES, new TreeListBuilder()); return r; }
// ----- private methods ----- private JsonElement serializeNestedKeyValueType( GraphObject src, Type typeOfSrc, JsonSerializationContext context, boolean includeTypeInOutput, String localPropertyView, int depth) { // prevent endless recursion by pruning at depth 2 if (depth > outputNestingDepth) { return null; } JsonObject jsonObject = new JsonObject(); // id (only if idProperty is not set) if (idProperty == null) { jsonObject.add("id", new JsonPrimitive(src.getId())); } else { Object idPropertyValue = src.getProperty(idProperty); if (idPropertyValue != null) { String idString = idPropertyValue.toString(); jsonObject.add("id", new JsonPrimitive(idString)); } } /* * String type = src.getType(); * if (type != null) { * * jsonObject.add("type", new JsonPrimitive(type)); * * } */ // property keys JsonArray properties = new JsonArray(); for (String key : src.getPropertyKeys(localPropertyView)) { Object value = src.getProperty(key); if (value instanceof Iterable) { JsonArray property = new JsonArray(); for (Object o : (Iterable) value) { if (o instanceof GraphObject) { GraphObject obj = (GraphObject) o; JsonElement recursiveSerializedValue = this.serializeNestedKeyValueType( obj, typeOfSrc, context, includeTypeInOutput, localPropertyView, depth + 1); if (recursiveSerializedValue != null) { property.add(recursiveSerializedValue); } } else if (o instanceof Map) { properties.add( serializeMap( (Map) o, typeOfSrc, context, localPropertyView, includeTypeInOutput, true, depth)); } else { // serialize primitive, this is for PropertyNotion properties.add(serializePrimitive(key, o, includeTypeInOutput)); } // TODO: Unterstützung von Notions mit mehr als einem Property bei der Ausgabe! // => neuer Typ? } properties.add(property); } else if (value instanceof GraphObject) { GraphObject graphObject = (GraphObject) value; properties.add( this.serializeNestedKeyValueType( graphObject, typeOfSrc, context, includeTypeInOutput, localPropertyView, depth + 1)); } else if (value instanceof Map) { properties.add( serializeMap( (Map) value, typeOfSrc, context, localPropertyView, includeTypeInOutput, true, depth)); } else { properties.add(serializePrimitive(key, value, includeTypeInOutput)); } } jsonObject.add("properties", properties); if (src instanceof AbstractNode) { // outgoing relationships Map<RelationshipType, Long> outRelStatistics = ((AbstractNode) src).getRelationshipInfo(Direction.OUTGOING); if (outRelStatistics != null) { JsonArray outRels = new JsonArray(); for (Entry<RelationshipType, Long> entry : outRelStatistics.entrySet()) { RelationshipType relType = entry.getKey(); Long count = entry.getValue(); JsonObject outRelEntry = new JsonObject(); outRelEntry.add("type", new JsonPrimitive(relType.name())); outRelEntry.add("count", new JsonPrimitive(count)); outRels.add(outRelEntry); } jsonObject.add("out", outRels); } // incoming relationships Map<RelationshipType, Long> inRelStatistics = ((AbstractNode) src).getRelationshipInfo(Direction.INCOMING); if (inRelStatistics != null) { JsonArray inRels = new JsonArray(); for (Entry<RelationshipType, Long> entry : inRelStatistics.entrySet()) { RelationshipType relType = entry.getKey(); Long count = entry.getValue(); JsonObject inRelEntry = new JsonObject(); inRelEntry.add("type", new JsonPrimitive(relType.name())); inRelEntry.add("count", new JsonPrimitive(count)); inRels.add(inRelEntry); } jsonObject.add("in", inRels); } } else if (src instanceof AbstractRelationship) { // start node id (for relationships) String startNodeId = ((AbstractRelationship) src).getStartNodeId(); if (startNodeId != null) { jsonObject.add("startNodeId", new JsonPrimitive(startNodeId)); } // end node id (for relationships) String endNodeId = ((AbstractRelationship) src).getEndNodeId(); if (endNodeId != null) { jsonObject.add("endNodeId", new JsonPrimitive(endNodeId)); } } return jsonObject; }
public JsonElement serialize( IChatComponent p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_) { if (p_serialize_1_ instanceof ChatComponentText && p_serialize_1_.getChatStyle().isEmpty() && p_serialize_1_.getSiblings().isEmpty()) { return new JsonPrimitive( ((ChatComponentText) p_serialize_1_).getChatComponentText_TextValue()); } else { JsonObject var4 = new JsonObject(); if (!p_serialize_1_.getChatStyle().isEmpty()) { this.serializeChatStyle(p_serialize_1_.getChatStyle(), var4, p_serialize_3_); } if (!p_serialize_1_.getSiblings().isEmpty()) { JsonArray var5 = new JsonArray(); Iterator var6 = p_serialize_1_.getSiblings().iterator(); while (var6.hasNext()) { IChatComponent var7 = (IChatComponent) var6.next(); var5.add(this.serialize(var7, var7.getClass(), p_serialize_3_)); } var4.add("extra", var5); } if (p_serialize_1_ instanceof ChatComponentText) { var4.addProperty( "text", ((ChatComponentText) p_serialize_1_).getChatComponentText_TextValue()); } else if (p_serialize_1_ instanceof ChatComponentTranslation) { ChatComponentTranslation var11 = (ChatComponentTranslation) p_serialize_1_; var4.addProperty("translate", var11.getKey()); if (var11.getFormatArgs() != null && var11.getFormatArgs().length > 0) { JsonArray var14 = new JsonArray(); Object[] var16 = var11.getFormatArgs(); int var8 = var16.length; for (int var9 = 0; var9 < var8; ++var9) { Object var10 = var16[var9]; if (var10 instanceof IChatComponent) { var14.add(this.serialize((IChatComponent) var10, var10.getClass(), p_serialize_3_)); } else { var14.add(new JsonPrimitive(String.valueOf(var10))); } } var4.add("with", var14); } } else if (p_serialize_1_ instanceof ChatComponentScore) { ChatComponentScore var12 = (ChatComponentScore) p_serialize_1_; JsonObject var15 = new JsonObject(); var15.addProperty("name", var12.func_179995_g()); var15.addProperty("objective", var12.func_179994_h()); var15.addProperty("value", var12.getUnformattedTextForChat()); var4.add("score", var15); } else { if (!(p_serialize_1_ instanceof ChatComponentSelector)) { throw new IllegalArgumentException( "Don\'t know how to serialize " + p_serialize_1_ + " as a Component"); } ChatComponentSelector var13 = (ChatComponentSelector) p_serialize_1_; var4.addProperty("selector", var13.func_179992_g()); } return var4; } }
/** **************** Creation tests * **************** */ @Test public void testCreate() { try { // Constructors JsonArray array = new JsonArray(); assertEquals(0, array.size()); JsonArray array2 = new JsonArray(57); assertEquals(0, array2.size()); // add(Object) + get(int) Object addObj = new Object(); array.add(addObj); assertEquals(1, array.size()); assertEquals(addObj, array.get(0)); Object addObj2 = new Object(); array.add(addObj2); assertEquals(2, array.size()); assertEquals(addObj2, array.get(1)); // add(JsonObject) + getObject(int) JsonObject addJObj = new JsonObject(); array.add(addJObj); assertEquals(3, array.size()); assertEquals(addJObj, array.getObject(2)); // add(JsonArray) + getArray(int) JsonArray addJArray = new JsonArray(); array.add(addJArray); assertEquals(4, array.size()); assertEquals(addJArray, array.getArray(3)); // add(String) + getString(int) String addStr = "Kawaii desu!"; array.add(addStr); assertEquals(5, array.size()); assertEquals(addStr, array.getString(4)); // add(int) + getLong(int) int addInt = 1_2_4_8; array.add(addInt); assertEquals(6, array.size()); assertEquals(addInt, array.getLong(5).longValue()); // add(long) + getLong(int) long addLong = 1_2_4_8_16_32_64; array.add(addLong); assertEquals(7, array.size()); assertEquals(addLong, array.getLong(6).longValue()); // add(float) + getDouble(int) float addFloat = 1_2_4_8.0f; array.add(addFloat); assertEquals(8, array.size()); assertEquals(addFloat, array.getDouble(7).doubleValue(), 0.01); // add(double) + getDouble(int) double addDouble = 1_2_4_8.16_32_64; array.add(addDouble); assertEquals(9, array.size()); assertEquals(addDouble, array.getDouble(8).doubleValue(), 0.0000001); // add(boolean) + getBoolean(int) boolean addBoolean = true; array.add(addBoolean); assertEquals(10, array.size()); assertTrue(array.getBoolean(9)); // Clone constructor JsonArray array3 = new JsonArray(array); assertEquals(10, array3.size()); assertEquals(addObj, array3.get(0)); assertEquals(addObj2, array3.get(1)); assertEquals(addJObj, array3.getObject(2)); assertEquals(addJArray, array3.getArray(3)); assertEquals(addStr, array3.getString(4)); assertEquals(addInt, array3.getLong(5).longValue()); assertEquals(addLong, array3.getLong(6).longValue()); assertEquals(addFloat, array3.getDouble(7).doubleValue(), 0.01); assertEquals(addDouble, array3.getDouble(8).doubleValue(), 0.0000001); assertTrue(array3.getBoolean(9)); } catch (JsonException e) { fail("This shouldn't happen!"); } }
public JsonElement serialize( WxMpCustomMessage message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); messageJson.addProperty("touser", message.getToUser()); messageJson.addProperty("msgtype", message.getMsgType()); if (WxConsts.CUSTOM_MSG_TEXT.equals(message.getMsgType())) { JsonObject text = new JsonObject(); text.addProperty("content", message.getContent()); messageJson.add("text", text); } if (WxConsts.CUSTOM_MSG_IMAGE.equals(message.getMsgType())) { JsonObject image = new JsonObject(); image.addProperty("media_id", message.getMediaId()); messageJson.add("image", image); } if (WxConsts.CUSTOM_MSG_VOICE.equals(message.getMsgType())) { JsonObject voice = new JsonObject(); voice.addProperty("media_id", message.getMediaId()); messageJson.add("voice", voice); } if (WxConsts.CUSTOM_MSG_VIDEO.equals(message.getMsgType())) { JsonObject video = new JsonObject(); video.addProperty("media_id", message.getMediaId()); video.addProperty("thumb_media_id", message.getThumbMediaId()); video.addProperty("title", message.getTitle()); video.addProperty("description", message.getDescription()); messageJson.add("video", video); } if (WxConsts.CUSTOM_MSG_MUSIC.equals(message.getMsgType())) { JsonObject music = new JsonObject(); music.addProperty("title", message.getTitle()); music.addProperty("description", message.getDescription()); music.addProperty("thumb_media_id", message.getThumbMediaId()); music.addProperty("musicurl", message.getMusicUrl()); music.addProperty("hqmusicurl", message.getHqMusicUrl()); messageJson.add("music", music); } if (WxConsts.CUSTOM_MSG_NEWS.equals(message.getMsgType())) { JsonObject newsJsonObject = new JsonObject(); JsonArray articleJsonArray = new JsonArray(); for (WxMpCustomMessage.WxArticle article : message.getArticles()) { JsonObject articleJson = new JsonObject(); articleJson.addProperty("title", article.getTitle()); articleJson.addProperty("description", article.getDescription()); articleJson.addProperty("url", article.getUrl()); articleJson.addProperty("picurl", article.getPicUrl()); articleJsonArray.add(articleJson); } newsJsonObject.add("articles", articleJsonArray); messageJson.add("news", newsJsonObject); } if (StringUtils.isNotBlank(message.getKfAccount())) { JsonObject newsJsonObject = new JsonObject(); newsJsonObject.addProperty("kf_account", message.getKfAccount()); messageJson.add("customservice", newsJsonObject); } return messageJson; }
@Override public JsonElement serialize( WebSocketMessage src, Type typeOfSrc, JsonSerializationContext context) { JsonObject root = new JsonObject(); JsonObject jsonNodeData = new JsonObject(); JsonObject jsonRelData = new JsonObject(); JsonArray removedProperties = new JsonArray(); JsonArray modifiedProperties = new JsonArray(); if (src.getCommand() != null) { root.add("command", new JsonPrimitive(src.getCommand())); } if (src.getId() != null) { root.add("id", new JsonPrimitive(src.getId())); } if (src.getPageId() != null) { root.add("pageId", new JsonPrimitive(src.getPageId())); } if (src.getMessage() != null) { root.add("message", new JsonPrimitive(src.getMessage())); } if (src.getCode() != 0) { root.add("code", new JsonPrimitive(src.getCode())); } if (src.getSessionId() != null) { root.add("sessionId", new JsonPrimitive(src.getSessionId())); } if (src.getToken() != null) { root.add("token", new JsonPrimitive(src.getToken())); } if (src.getCallback() != null) { root.add("callback", new JsonPrimitive(src.getCallback())); } if (src.getButton() != null) { root.add("button", new JsonPrimitive(src.getButton())); } if (src.getParent() != null) { root.add("parent", new JsonPrimitive(src.getParent())); } if (src.getView() != null) { root.add("view", new JsonPrimitive(src.getView())); } if (src.getSortKey() != null) { root.add("sort", new JsonPrimitive(src.getSortKey())); } if (src.getSortOrder() != null) { root.add("order", new JsonPrimitive(src.getSortOrder())); } if (src.getPageSize() > 0) { root.add("pageSize", new JsonPrimitive(src.getPageSize())); } if (src.getPage() > 0) { root.add("page", new JsonPrimitive(src.getPage())); } JsonArray nodesWithChildren = new JsonArray(); Set<String> nwc = src.getNodesWithChildren(); if ((nwc != null) && !src.getNodesWithChildren().isEmpty()) { for (String nodeId : nwc) { nodesWithChildren.add(new JsonPrimitive(nodeId)); } root.add("nodesWithChildren", nodesWithChildren); } // serialize session valid flag (output only) root.add("sessionValid", new JsonPrimitive(src.isSessionValid())); // UPDATE only, serialize only removed and modified properties and use the correct values if ((src.getGraphObject() != null)) { GraphObject graphObject = src.getGraphObject(); if (!src.getModifiedProperties().isEmpty()) { for (PropertyKey modifiedKey : src.getModifiedProperties()) { modifiedProperties.add(toJsonPrimitive(modifiedKey)); // Object newValue = graphObject.getProperty(modifiedKey); // // if (newValue != null) { // // if (graphObject instanceof AbstractNode) { // // src.getNodeData().put(modifiedKey.jsonName(), newValue); // } else { // // src.getRelData().put(modifiedKey.jsonName(), newValue); // } // // } } root.add("modifiedProperties", modifiedProperties); } if (!src.getRemovedProperties().isEmpty()) { for (PropertyKey removedKey : src.getRemovedProperties()) { removedProperties.add(toJsonPrimitive(removedKey)); } root.add("removedProperties", removedProperties); } } // serialize node data if (src.getNodeData() != null) { for (Entry<String, Object> entry : src.getNodeData().entrySet()) { Object value = entry.getValue(); String key = entry.getKey(); if (value != null) { jsonNodeData.add(key, toJsonPrimitive(value)); } } root.add("data", jsonNodeData); } // serialize relationship data if (src.getRelData() != null) { for (Entry<String, Object> entry : src.getRelData().entrySet()) { Object value = entry.getValue(); String key = entry.getKey(); if (value != null) { jsonRelData.add(key, toJsonPrimitive(value)); } } root.add("relData", jsonRelData); } // serialize result list if (src.getResult() != null) { if (src.getView() != null) { try { propertyView.set(null, src.getView()); } catch (FrameworkException fex) { logger.log(Level.WARNING, "Unable to set property view", fex); } } else { try { propertyView.set(null, PropertyView.Ui); } catch (FrameworkException fex) { logger.log(Level.WARNING, "Unable to set property view", fex); } } JsonArray result = new JsonArray(); for (GraphObject obj : src.getResult()) { result.add(graphObjectSerializer.serialize(obj, System.currentTimeMillis())); } root.add("result", result); root.add("rawResultCount", toJsonPrimitive(src.getRawResultCount())); } // serialize result tree // if (src.getResultTree() != null) { // // TreeNode node = src.getResultTree(); // // root.add("root", buildTree(node, context)); // // } return root; }
private Token advanceToken() throws JsonParserException { int c = advanceChar(); while (isWhitespace(c)) { c = advanceChar(); } tokenLinePos = linePos; tokenCharPos = index - rowPos - utf8adjust; tokenCharOffset = charOffset + index; switch (c) { case -1: return token = Token.EOF; case '[': JsonArray list = new JsonArray(); if (advanceToken() != Token.ARRAY_END) while (true) { list.add(currentValue()); if (advanceToken() == Token.ARRAY_END) break; if (token != Token.COMMA) throw createParseException( null, "Expected a comma or end of the array instead of " + token, true); if (advanceToken() == Token.ARRAY_END) throw createParseException(null, "Trailing comma found in array", true); } value = list; return token = Token.ARRAY_START; case ']': return token = Token.ARRAY_END; case ',': return token = Token.COMMA; case ':': return token = Token.COLON; case '{': JsonObject map = new JsonObject(); if (advanceToken() != Token.OBJECT_END) while (true) { if (token != Token.STRING) { throw createParseException(null, "Expected STRING, got " + token, true); } String key = (String) value; if (advanceToken() != Token.COLON) { throw createParseException(null, "Expected COLON, got " + token, true); } advanceToken(); map.put(key, currentValue()); if (advanceToken() == Token.OBJECT_END) { break; } if (token != Token.COMMA) { throw createParseException( null, "Expected a comma or end of the object instead of " + token, true); } if (advanceToken() == Token.OBJECT_END) { throw createParseException(null, "Trailing object found in array", true); } } value = map; return token = Token.OBJECT_START; case '}': return token = Token.OBJECT_END; case 't': consumeKeyword((char) c, TRUE); value = Boolean.TRUE; return token = Token.TRUE; case 'f': consumeKeyword((char) c, FALSE); value = Boolean.FALSE; return token = Token.FALSE; case 'n': consumeKeyword((char) c, NULL); value = null; return token = Token.NULL; case '\"': value = consumeTokenString(); return token = Token.STRING; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value = consumeTokenNumber((char) c); return token = Token.NUMBER; case '+': case '.': throw createParseException(null, "Numbers may not start with '" + (char) c + "'", true); default: } if (isAsciiLetter(c)) { throw createHelpfulException((char) c, null, 0); } throw createParseException(null, "Unexpected character: " + (char) c, true); }