private void parsePlugins(String context, QueryMetric queryMetric, JsonArray plugins) throws BeanValidationException, QueryException { for (int I = 0; I < plugins.size(); I++) { JsonObject pluginJson = plugins.get(I).getAsJsonObject(); JsonElement name = pluginJson.get("name"); if (name == null || name.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation("plugins[" + I + "]", "must have a name"), context); String pluginContext = context + ".plugins[" + I + "]"; String pluginName = name.getAsString(); QueryPlugin plugin = m_pluginFactory.createQueryPlugin(pluginName); if (plugin == null) throw new BeanValidationException( new SimpleConstraintViolation(pluginName, "invalid query plugin name"), pluginContext); deserializeProperties(pluginContext, pluginJson, pluginName, plugin); validateObject(plugin, pluginContext); queryMetric.addPlugin(plugin); } }
private static boolean parseProperty( JsonElement propertyElement, IConfigPropertyHolder property, Gson gson) { if (!(propertyElement instanceof JsonObject)) return true; JsonObject propertyNode = propertyElement.getAsJsonObject(); JsonElement value = propertyNode.get(VALUE_TAG); if (value == null) return true; try { Object parsedValue = gson.fromJson(value, property.getType()); property.setValue(parsedValue); } catch (Exception e) { Log.warn(e, "Failed to parse value of field %s:%s", property.category(), property.name()); return true; } JsonElement comment = propertyNode.get(COMMENT_TAG); final String expectedComment = property.comment(); if (comment == null) { return !Strings.isNullOrEmpty(expectedComment); } else if (comment.isJsonPrimitive()) { String commentValue = comment.getAsString(); return !expectedComment.equals(commentValue); } return true; }
@Override public TargetInfo deserialize( JsonElement element, Type type, final JsonDeserializationContext context) throws JsonParseException { final JsonObject object = element.getAsJsonObject(); final List<String> targets = getStringListField(object, "targets"); final List<String> libraries = getStringListField(object, "libraries"); final List<String> excludes = getStringListField(object, "excludes"); final List<SourceRoot> sourceRoots = getFieldAsList( object.getAsJsonArray("roots"), new Function<JsonElement, SourceRoot>() { @Override public SourceRoot fun(JsonElement element) { return context.deserialize(element, SourceRoot.class); } }); final TargetAddressInfo addressInfo = context.deserialize(element, TargetAddressInfo.class); return new TargetInfo( new HashSet<TargetAddressInfo>(Collections.singleton(addressInfo)), new HashSet<String>(targets), new HashSet<String>(libraries), new HashSet<String>(excludes), new HashSet<SourceRoot>(sourceRoots)); }
public static void dumpJSON(JsonValue tree, String key, String depthPrefix) { if (key != null) logger.info(depthPrefix + "Key " + key + ": "); switch (tree.getValueType()) { case OBJECT: logger.info(depthPrefix + "OBJECT"); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) dumpJSON(object.get(name), name, depthPrefix + " "); break; case ARRAY: logger.info(depthPrefix + "ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) dumpJSON(val, null, depthPrefix + " "); break; case STRING: JsonString st = (JsonString) tree; logger.info(depthPrefix + "STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; logger.info(depthPrefix + "NUMBER " + num.toString()); break; case TRUE: case FALSE: case NULL: logger.info(depthPrefix + tree.getValueType().toString()); break; } }
public RollupTask parseRollupTask(String json) throws BeanValidationException, QueryException { JsonParser parser = new JsonParser(); JsonObject taskObject = parser.parse(json).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, ""); task.addJson(taskObject.toString().replaceAll("\\n", "")); return task; }
private static JsonObject deepCopyObj(JsonObject from) { JsonObject result = new JsonObject(); for (Map.Entry<String, JsonElement> entry : from.entrySet()) { result.add(entry.getKey(), deepCopy(entry.getValue())); } return result; }
/** * Write the contents of the JsonArray as JSON text to a writer. For compactness, no whitespace is * added. * * <p>Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JsonException */ public Writer write(Writer writer) { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JsonObject) { ((JsonObject) v).write(writer); } else if (v instanceof JsonArray) { ((JsonArray) v).write(writer); } else { writer.write(JsonObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JsonException(e); } }
@Override public JsonElement serialize(MoveStrategy src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); result.add("type", new JsonPrimitive(src.getClass().getSimpleName())); result.add("properties", context.serialize(src, src.getClass())); return result; }
/** * Make a prettyprinted JSON text of this JsonArray. Warning: This method assumes that the data * structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. * @param indent The indention of the top level. * @return a printable, displayable, transmittable representation of the array. * @throws JsonException */ String toString(int indentFactor, int indent) { int len = length(); if (len == 0) { return "[]"; } int i; StringBuilder sb = new StringBuilder("["); if (len == 1) { sb.append(JsonObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JsonObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); }
/** * Returns the information for the given node-id * * @param id the id of the host which connectivity information u want * @return NodeInfo object with all information * @throws FileNotFoundException * @throws Exception */ public NodeInfo getNodeConnectivityInfoForId(String id) throws FileNotFoundException, Exception { // reading and parsing the hostfile JsonReader reader = new JsonReader(new FileReader(fileHosts)); JsonParser parser = new JsonParser(); JsonArray hostsArray = parser.parse(reader).getAsJsonArray(); NodeInfo nodeInfo = null; // gernerating NodeInfo for id for (JsonElement obj : hostsArray) { JsonObject host = obj.getAsJsonObject(); try { String hostId = host.get(GraphManager.JSON_ID).getAsString(); if (hostId.equals(id)) { nodeInfo = new NodeInfo( hostId, host.get(GraphManager.JSON_HOSTNAME).getAsString(), Integer.valueOf(host.get(GraphManager.JSON_PORT).getAsString())); break; } } catch (Exception e) { throw new JsonParseException( "Fehler in der JSON-Konfigdatei: Bitte README.pdf fuer das richtige Format lesen"); } } if (nodeInfo == null) { throw new Exception("No connectivity info for id found"); } return nodeInfo; }
private static void readJsonFile() { try (JsonReader jsonReader = Json.createReader( new FileReader( Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) { JsonStructure jsonStructure = jsonReader.read(); JsonValue.ValueType valueType = jsonStructure.getValueType(); if (valueType == JsonValue.ValueType.OBJECT) { JsonObject jsonObject = (JsonObject) jsonStructure; JsonValue firstName = jsonObject.get("firstName"); LOGGER.info("firstName=" + firstName); JsonValue emailAddresses = jsonObject.get("phoneNumbers"); if (emailAddresses.getValueType() == JsonValue.ValueType.ARRAY) { JsonArray jsonArray = (JsonArray) emailAddresses; for (int i = 0; i < jsonArray.size(); i++) { JsonValue jsonValue = jsonArray.get(i); LOGGER.info("emailAddress(" + i + "): " + jsonValue); } } } else { LOGGER.warning("First object is not of type " + JsonValue.ValueType.OBJECT); } } catch (FileNotFoundException e) { LOGGER.severe("Failed to open file: " + e.getMessage()); } }
public static LauncherProfiles load() throws IOException { System.out.println("Loading Minecraft profiles from " + DevLauncher.workingDirectory); try (FileReader reader = new FileReader(getFile())) { LauncherProfiles profiles = new LauncherProfiles(); JsonObject e = new JsonParser().parse(reader).getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : e.entrySet()) { if (entry.getKey().equals("clientToken")) { profiles.clientToken = entry.getValue().getAsString(); } else if (entry.getKey().equals("authenticationDatabase")) { JsonObject o = entry.getValue().getAsJsonObject(); for (Map.Entry<String, JsonElement> entry1 : o.entrySet()) { profiles.authenticationDatabase.profiles.put( UUIDTypeAdapter.fromString(entry1.getKey()), GSON.fromJson(entry1.getValue(), OnlineProfile.class)); } } else { profiles.everythingElse.add(entry.getKey(), entry.getValue()); } } INSTANCE = profiles; return INSTANCE; } finally { if (INSTANCE == null) { INSTANCE = new LauncherProfiles(); } INSTANCE.markLoaded(); } }
private void parseGroupBy(String context, QueryMetric queryMetric, JsonArray groupBys) throws QueryException, BeanValidationException { for (int J = 0; J < groupBys.size(); J++) { String groupContext = "group_by[" + J + "]"; JsonObject jsGroupBy = groupBys.get(J).getAsJsonObject(); JsonElement nameElement = jsGroupBy.get("name"); if (nameElement == null || nameElement.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation(groupContext, "must have a name"), context); String name = nameElement.getAsString(); GroupBy groupBy = m_groupByFactory.createGroupBy(name); if (groupBy == null) throw new BeanValidationException( new SimpleConstraintViolation(groupContext + "." + name, "invalid group_by name"), context); deserializeProperties(context + "." + groupContext, jsGroupBy, name, groupBy); validateObject(groupBy, context + "." + groupContext); groupBy.setStartDate(queryMetric.getStartTime()); queryMetric.addGroupBy(groupBy); } }
@Override public Flag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); FlagType flagType = FlagType.valueOf(jsonObject.get("flagType").getAsString()); return new Flag(flagType, jsonObject.get("value").getAsString()); }
@Override public JsonElement serialize(Flag flag, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); json.addProperty("flagType", flag.flagType.name); json.addProperty("value", flag.flagType.serializeValue(flag.value)); return json; }
public AbstractProperty(String name, String category, JsonObject data) { super(name, category); canRandomize = !(data.has("random") && data.get("random").isJsonPrimitive() && data.get("random").getAsJsonPrimitive().isBoolean() && !data.get("random").getAsBoolean()); }
@Override public JsonObject exportToJson() { JsonObject json = new JsonObject(); if (canRandomize) { json.addProperty("shouldRandomize", shouldRandomize); } return json; }
public JsonElement serialize( AppAudioSession src, Type typeOfSrc, JsonSerializationContext context) { JsonObject element = new JsonObject(); element.addProperty("ID", src.ID); element.addProperty("Volume", src.Volume); element.addProperty("Muted", src.Muted); return element; }
@Override public String toString() { JsonObject ob = new JsonObject(); ob.addProperty("lat", this.getLat()); ob.addProperty("longitude", this.getLongitude()); ob.addProperty("base64Image", this.getBase64Encoding()); return ob.toString(); }
public static Response redirect( JsonObject fromPageResponse, Key rfModel, Key dataKey, boolean oobee) { JsonObject redir = new JsonObject(); redir.addProperty(MODEL_KEY, rfModel.toString()); redir.addProperty(DATA_KEY, dataKey.toString()); redir.addProperty(OOBEE, oobee); return Response.redirect(fromPageResponse, RFView.class, redir); }
private JsonObject transformGuysData(JsonArray array) { JsonObject result = new JsonObject(); for (JsonElement e : array) { String key = e.getAsJsonObject().get("sample").getAsString(); result.add(key, e.getAsJsonObject().get("Expression")); } return result; }
/** * @param id the id of the node which neighbours you want to get * @return returns a list all neighbours for the given host id * @throws FileNotFoundException * @throws ParseException * @throws Exception */ public ArrayList<NodeInfo> getHostsListForId(String id) throws Exception { // Reading the graphfile File f = new File(this.fileGraph); FileReader in = new FileReader(f); // parsing the graphfile Parser graphParser = new Parser(); graphParser.parse(in); ArrayList<Graph> graphList = graphParser.getGraphs(); if (graphList.size() < 1) { throw new Exception("No graph in graphfile found."); } Graph graph = graphList.get(0); ArrayList<Edge> edges = graph.getEdges(); // getting all neighbours ArrayList<String> neighbours = new ArrayList<>(); for (Edge edge : edges) { String sourceId = edge.getSource().getNode().getId().getId(); String targetId = edge.getTarget().getNode().getId().getId(); if (sourceId.equals(id)) { neighbours.add(targetId); } else if (targetId.equals(id)) { neighbours.add(sourceId); } } // reading the host information File file = new File(this.fileHosts); Scanner input; ArrayList<NodeInfo> hosts = new ArrayList<>(); JsonReader reader = new JsonReader(new FileReader(fileHosts)); // parsing the host information Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray hostsArray = parser.parse(reader).getAsJsonArray(); // matching the hostinformation for the neighbours for (JsonElement obj : hostsArray) { JsonObject host = obj.getAsJsonObject(); String hostId = host.get(GraphManager.JSON_ID).getAsString(); if (neighbours.contains(hostId)) { if (!listContainsHost(hosts, hostId)) { hosts.add( new NodeInfo( host.get(GraphManager.JSON_ID).getAsString(), host.get(GraphManager.JSON_HOSTNAME).getAsString(), host.get(GraphManager.JSON_PORT).getAsInt())); } } } return hosts; }
private void SetTurnManager(JsonObject turnTracker) throws TurnIndexException, InvalidTurnStatusException, GeneralPlayerException { int currentTurn = turnTracker.getAsJsonPrimitive("currentTurn").getAsInt(); String status = turnTracker.getAsJsonPrimitive("status").getAsString(); PlayerTurnTracker playerTurnTracker = new PlayerTurnTracker(currentTurn, TurnType.toEnum(status)); playerManager.setTurnTracker(playerTurnTracker); }
@Override public JsonElement serialize(Throwable src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.add("class", new JsonPrimitive(src.getClass().getName())); if (src.getMessage() != null) { jsonObject.add("message", new JsonPrimitive(src.getMessage())); } return jsonObject; }
private SegmentTileEntity deserializeTileEntity( JsonObject json, JsonDeserializationContext context) { SegmentTileEntity segment = new SegmentTileEntity(); segment.retainsOwner = json.getAsJsonObject().get("retainsOwner").getAsBoolean(); json.remove("retainsOwner"); return segment; }
/** * Annotate the number of columns and rows of the training data set in the job parameter JSON * * @return JsonObject annotated with num_cols and num_rows of the training data set */ @Override public JsonObject toJSON() { JsonObject jo = super.toJSON(); if (source != null) { jo.getAsJsonObject("source").addProperty("num_cols", source.numCols()); jo.getAsJsonObject("source").addProperty("num_rows", source.numRows()); } return jo; }
/** * Annotate the number of columns and rows of the validation data set in the job parameter JSON * * @return JsonObject annotated with num_cols and num_rows of the validation data set */ @Override public JsonObject toJSON() { JsonObject jo = super.toJSON(); if (validation != null) { jo.getAsJsonObject("validation").addProperty("num_cols", validation.numCols()); jo.getAsJsonObject("validation").addProperty("num_rows", validation.numRows()); } return jo; }
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); } }
@Override public JsonElement serialize( AssetReference asset, Type typeOfSrc, JsonSerializationContext context) { JsonElement jsonAsset = context.serialize(asset.asset, asset.asset.getClass()); GsonUtils.appendClassProperty(jsonAsset, asset.asset, context); JsonObject jsonObject = new JsonObject(); jsonObject.add("asset", jsonAsset); return jsonObject; }
private void serializeBlock( SegmentBlock segment, JsonObject json, JsonSerializationContext context) { json.add("actions", serializeAsElementOrArray(segment.types, context)); json.addProperty("meta", segment.getMeta()); if (segment.clientUpdate != null) { JsonObject jsonUpdate = new JsonObject(); jsonUpdate.add("coords", context.serialize(segment.clientUpdate.relativeCoords)); json.add("clientUpdate", jsonUpdate); } }