/** * Parse a json message collection to create a Message * * @param arg json collection * @return Message */ public static Message readMessage(String arg) { JsonReader jsonReader = Json.createReader(new StringReader(arg)); JsonObject msgValues = jsonReader.readObject(); jsonReader.close(); if (null == msgValues.getJsonArray(ATTACHMENTS)) { return new Message( msgValues.getString(ID), msgValues.getString(SENDER), msgValues.getString(TOPIC), msgValues.getJsonNumber(TIMESTAMP).longValue(), msgValues.getString(CONTENT)); } else { JsonArray attachmentsJson = msgValues.getJsonArray(ATTACHMENTS); Byte[] attachmentByte = new Byte[attachmentsJson.size()]; for (int i = 0; i < attachmentByte.length; i++) { attachmentByte[i] = Byte.valueOf(attachmentsJson.getString(i)); } return new Message( msgValues.getString(ID), msgValues.getString(SENDER), msgValues.getString(TOPIC), msgValues.getJsonNumber(TIMESTAMP).longValue(), msgValues.getString(CONTENT), attachmentByte); } }
private static JsonArray deepCopyArr(JsonArray from) { JsonArray result = new JsonArray(); for (JsonElement element : from) { result.add(deepCopy(element)); } return result; }
public List<CIBuild> getBuilds(CIJob job) throws PhrescoException { if (debugEnabled) { S_LOGGER.debug("Entering Method CIManagerImpl.getCIBuilds(CIJob job)"); } List<CIBuild> ciBuilds = null; try { if (debugEnabled) { S_LOGGER.debug("getCIBuilds() JobName = " + job.getName()); } JsonArray jsonArray = getBuildsArray(job); ciBuilds = new ArrayList<CIBuild>(jsonArray.size()); Gson gson = new Gson(); CIBuild ciBuild = null; for (int i = 0; i < jsonArray.size(); i++) { ciBuild = gson.fromJson(jsonArray.get(i), CIBuild.class); setBuildStatus(ciBuild, job); String buildUrl = ciBuild.getUrl(); String jenkinUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort(); buildUrl = buildUrl.replaceAll( "localhost:" + job.getJenkinsPort(), jenkinUrl); // when displaying url it should display setup machine ip ciBuild.setUrl(buildUrl); ciBuilds.add(ciBuild); } } catch (Exception e) { if (debugEnabled) { S_LOGGER.debug( "Entering Method CIManagerImpl.getCIBuilds(CIJob job) " + e.getLocalizedMessage()); } } return ciBuilds; }
public static Object gsonToPrimitive(JsonElement element) { if (element.isJsonPrimitive()) { JsonPrimitive prim = element.getAsJsonPrimitive(); if (prim.isString()) { return prim.getAsString(); } else if (prim.isBoolean()) { return prim.getAsBoolean(); } else if (prim.isNumber()) { return prim.getAsNumber(); } else { throw new IllegalArgumentException("Unknown Gson primitive: " + prim); } } else if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); List<Object> list = new ArrayList<Object>(); for (int i = 0; i < array.size(); i++) { list.add(gsonToPrimitive(array.get(i))); } return list; } else if (element.isJsonNull()) { return null; } else if (element.isJsonObject()) { Map<String, Object> map = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) { map.put(entry.getKey(), gsonToPrimitive(entry.getValue())); } return map; } else { throw new IllegalArgumentException("Unknown Gson value: " + element); } }
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); } }
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()); } }
private ArrayList<String> getAppUsersId() { // TODO: Fetch user ids from database ArrayList<String> usersID = new ArrayList<String>(); try { String response = new GetUsersTask() .execute("http://katanaserver.no-ip.org/gcm_server_php/get_users.php") .get(); // Parse the response JsonElement jelement = new JsonParser().parse(response); JsonArray jarray = jelement.getAsJsonArray(); for (int i = 0; i < jarray.size(); i++) { usersID.add(jarray.get(i).getAsJsonObject().get("UserID").toString()); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return usersID; }
static boolean equals(Object o1, Object o2) { if (o1 == o2) return true; if (o1 instanceof JsonObject) { return objectEquals(((JsonObject) o1).map, o2); } if (o1 instanceof Map<?, ?>) { return objectEquals((Map<?, ?>) o1, o2); } if (o1 instanceof JsonArray) { return JsonArray.arrayEquals(((JsonArray) o1).getList(), o2); } if (o1 instanceof List<?>) { return JsonArray.arrayEquals((List<?>) o1, o2); } if (o1 instanceof Number && o2 instanceof Number && o1.getClass() != o2.getClass()) { Number n1 = (Number) o1; Number n2 = (Number) o2; if (o1 instanceof Float || o1 instanceof Double || o2 instanceof Float || o2 instanceof Double) { return n1.doubleValue() == n2.doubleValue(); } else { return n1.longValue() == n2.longValue(); } } return o1.equals(o2); }
private final JsonArray JsonArray() throws ParseException { JsonArray array = new JsonArray(); jj_consume_token(25); switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case DIGITS: case SINGLE_QUOTE_LITERAL: case DOUBLE_QUOTE_LITERAL: case 20: case 22: case 25: case 27: case 28: case 29: Elements(array); break; default: jj_la1[3] = jj_gen; ; } jj_consume_token(26); array.reverse(); { if (true) return array; } throw new Error("Missing return statement in function"); }
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 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; }
/** * 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; }
/** * 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; }
@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; }
private List<String> getLocatorsFromJSONBody(String tenantId, String body) { JsonElement element = gson.fromJson(body, JsonElement.class); JsonArray metrics = element.getAsJsonArray(); final List<String> locators = new ArrayList<String>(); Iterator<JsonElement> it = metrics.iterator(); while (it.hasNext()) { JsonElement metricElement = it.next(); locators.add(metricElement.getAsString()); } return locators; }
private void SetPlayerManager(JsonArray players, JsonObject turnTracker) { Player[] catanPlayers = new Player[players.size()]; int longestRoad = turnTracker.getAsJsonPrimitive("longestRoad").getAsInt(); int largestArmy = turnTracker.getAsJsonPrimitive("largestArmy").getAsInt(); for (int i = 0; i < players.size(); i++) { if (!players.get(i).isJsonNull()) { JsonObject player = players.get(i).getAsJsonObject(); int index = player.getAsJsonPrimitive("playerIndex").getAsInt(); String name = player.getAsJsonPrimitive("name").getAsString(); String color = player.getAsJsonPrimitive("color").getAsString(); int playerId = player.getAsJsonPrimitive("playerID").getAsInt(); int cities = player.getAsJsonPrimitive("cities").getAsInt(); int settlements = player.getAsJsonPrimitive("settlements").getAsInt(); int roads = player.getAsJsonPrimitive("roads").getAsInt(); int victoryPoints = player.getAsJsonPrimitive("victoryPoints").getAsInt(); Player newPlayer = new Player(); newPlayer.setPoints(victoryPoints); try { newPlayer.setColor(color); } catch (InvalidColorException e) { e.printStackTrace(); } if (longestRoad == index) { newPlayer.setLongestRoad(true); } if (largestArmy == index) { newPlayer.setLargestArmy(true); } newPlayer.setId(playerId); newPlayer.setCitiesRemaining(cities); newPlayer.setSettlementsRemaining(settlements); newPlayer.setRoadsRemaining(roads); newPlayer.setPlayerIndex(index); newPlayer.setName(name); // <========Construct part of player manager here============> catanPlayers[index] = newPlayer; } } // <========Construct player manager here============> PlayerManager newPlayerManager = new PlayerManager(); newPlayerManager.setCatanPlayers(catanPlayers); newPlayerManager.setIndexOfLargestArmy(largestArmy); newPlayerManager.setIndexOfLongestRoad(longestRoad); this.playerManager = newPlayerManager; }
public List<RollupTask> parseRollupTasks(String json) throws BeanValidationException, QueryException { List<RollupTask> tasks = new ArrayList<RollupTask>(); JsonParser parser = new JsonParser(); JsonArray rollupTasks = parser.parse(json).getAsJsonArray(); for (int i = 0; i < rollupTasks.size(); i++) { JsonObject taskObject = rollupTasks.get(i).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, "tasks[" + i + "]"); task.addJson(taskObject.toString().replaceAll("\\n", "")); tasks.add(task); } return tasks; }
private void setBuildStatus(CIBuild ciBuild, CIJob job) throws PhrescoException { S_LOGGER.debug("Entering Method CIManagerImpl.setBuildStatus(CIBuild ciBuild)"); S_LOGGER.debug("setBuildStatus() url = " + ciBuild.getUrl()); String buildUrl = ciBuild.getUrl(); String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort(); buildUrl = buildUrl.replaceAll( "localhost:" + job.getJenkinsPort(), jenkinsUrl); // display the jenkins running url in ci list String response = getJsonResponse(buildUrl + API_JSON); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(response); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT); JsonElement idJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_ID); JsonElement timeJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_TIME_STAMP); JsonArray asJsonArray = jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS); if (jsonObject .get(FrameworkConstants.CI_JOB_BUILD_RESULT) .toString() .equals(STRING_NULL)) { // when build is result is not known ciBuild.setStatus(INPROGRESS); } else if (resultJson.getAsString().equals(CI_SUCCESS_FLAG) && asJsonArray.size() < 1) { // when build is success and zip relative path is not added in json ciBuild.setStatus(INPROGRESS); } else { ciBuild.setStatus(resultJson.getAsString()); // download path for (JsonElement jsonArtElement : asJsonArray) { String buildDownloadZip = jsonArtElement .getAsJsonObject() .get(FrameworkConstants.CI_JOB_BUILD_DOWNLOAD_PATH) .toString(); if (buildDownloadZip.endsWith(CI_ZIP)) { if (debugEnabled) { S_LOGGER.debug("download artifact " + buildDownloadZip); } ciBuild.setDownload(buildDownloadZip); } } } ciBuild.setId(idJson.getAsString()); String dispFormat = DD_MM_YYYY_HH_MM_SS; ciBuild.setTimeStamp(getDate(timeJson.getAsString(), dispFormat)); }
@Override public FriendList deserialize(JsonElement je, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { FriendList friendList = new FriendList(); JsonObject response = (JsonObject) je.getAsJsonObject().get("response"); JsonArray items = response.getAsJsonObject().getAsJsonArray("items"); for (int i = 0; i < items.size(); i++) { Friend friend = context.deserialize(items.get(i), Friend.class); friendList.getFriends().add(friend); } return friendList; }
@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; }
public static Class<? extends NBTBase> getNBTTypeSmart(JsonElement element) { if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); if (array.size() == 0) { return NBTTagList.class; } boolean allByte = true; boolean allInt = true; for (JsonElement arrayElement : array) { if (arrayElement.isJsonPrimitive()) { JsonPrimitive primitive = arrayElement.getAsJsonPrimitive(); if (!(primitive.isNumber() && primitive.getAsNumber() instanceof Byte)) { allByte = false; } if (!(primitive.isNumber() && primitive.getAsNumber() instanceof Integer)) { allInt = false; } } else { allByte = false; allInt = false; } } if (allByte) { return NBTTagByteArray.class; } if (allInt) { return NBTTagIntArray.class; } return NBTTagList.class; } else if (element.isJsonObject()) { return NBTTagCompound.class; } else if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isString()) { return NBTTagString.class; } else if (primitive.isNumber()) { return NBTBase.NBTPrimitive.class; } } return null; }
public WxMpUserList deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxMpUserList wxMpUserList = new WxMpUserList(); wxMpUserList.setTotal(GsonHelper.getInteger(o, "total")); wxMpUserList.setCount(GsonHelper.getInteger(o, "count")); wxMpUserList.setNextOpenId(GsonHelper.getString(o, "next_openid")); if (!o.get("data").isJsonNull() && !o.get("data").getAsJsonObject().get("openid").isJsonNull()) { JsonArray data = o.get("data").getAsJsonObject().get("openid").getAsJsonArray(); for (int i = 0; i < data.size(); i++) { wxMpUserList.getOpenIds().add(GsonHelper.getAsString(data.get(i))); } } return wxMpUserList; }
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); } } }
public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxCpUser user = new WxCpUser(); user.setUserId(GsonHelper.getString(o, "userid")); user.setName(GsonHelper.getString(o, "name")); if (o.get("department") != null) { JsonArray departJsonArray = o.get("department").getAsJsonArray(); Integer[] departIds = new Integer[departJsonArray.size()]; int i = 0; for (JsonElement jsonElement : departJsonArray) { departIds[i++] = jsonElement.getAsInt(); } user.setDepartIds(departIds); } user.setPosition(GsonHelper.getString(o, "position")); user.setMobile(GsonHelper.getString(o, "mobile")); Integer gender = GsonHelper.getInteger(o, "gender"); if (new Integer(1).equals(gender)) { user.setGender("男"); } else if (new Integer(2).equals(gender)) { user.setGender("女"); } else { user.setGender("未知"); } user.setTel(GsonHelper.getString(o, "tel")); user.setEmail(GsonHelper.getString(o, "email")); user.setWeiXinId(GsonHelper.getString(o, "weixinid")); user.setAvatar(GsonHelper.getString(o, "avatar")); user.setStatus(GsonHelper.getInteger(o, "status")); if (GsonHelper.isNotNull(o.get("extattr"))) { JsonArray attrJsonElements = o.get("extattr").getAsJsonObject().get("attrs").getAsJsonArray(); for (JsonElement attrJsonElement : attrJsonElements) { WxCpUser.Attr attr = new WxCpUser.Attr( GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name"), GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value")); user.getExtAttrs().add(attr); } } return user; }
@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 void parseAggregators( String context, QueryMetric queryMetric, JsonArray aggregators, DateTimeZone timeZone) throws QueryException, BeanValidationException { for (int J = 0; J < aggregators.size(); J++) { JsonObject jsAggregator = aggregators.get(J).getAsJsonObject(); JsonElement name = jsAggregator.get("name"); if (name == null || name.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation("aggregators[" + J + "]", "must have a name"), context); String aggContext = context + ".aggregators[" + J + "]"; String aggName = name.getAsString(); Aggregator aggregator = m_aggregatorFactory.createAggregator(aggName); if (aggregator == null) throw new BeanValidationException( new SimpleConstraintViolation(aggName, "invalid aggregator name"), aggContext); // If it is a range aggregator we will default the start time to // the start of the query. if (aggregator instanceof RangeAggregator) { RangeAggregator ra = (RangeAggregator) aggregator; ra.setStartTime(queryMetric.getStartTime()); } if (aggregator instanceof TimezoneAware) { TimezoneAware ta = (TimezoneAware) aggregator; ta.setTimeZone(timeZone); } if (aggregator instanceof GroupByAware) { GroupByAware groupByAware = (GroupByAware) aggregator; groupByAware.setGroupBys(queryMetric.getGroupBys()); } deserializeProperties(aggContext, jsAggregator, aggName, aggregator); validateObject(aggregator, aggContext); queryMetric.addAggregator(aggregator); } }
public RollupTask parseRollupTask(JsonObject rollupTask, String context) throws BeanValidationException, QueryException { RollupTask task = m_gson.fromJson(rollupTask.getAsJsonObject(), RollupTask.class); validateObject(task); JsonArray rollups = rollupTask.getAsJsonObject().getAsJsonArray("rollups"); if (rollups != null) { for (int j = 0; j < rollups.size(); j++) { JsonObject rollupObject = rollups.get(j).getAsJsonObject(); Rollup rollup = m_gson.fromJson(rollupObject, Rollup.class); context = context + "rollup[" + j + "]"; validateObject(rollup, context); JsonObject queryObject = rollupObject.getAsJsonObject("query"); List<QueryMetric> queries = parseQueryMetric(queryObject, context); for (int k = 0; k < queries.size(); k++) { QueryMetric query = queries.get(k); context += ".query[" + k + "]"; validateHasRangeAggregator(query, context); // Add aggregators needed for rollups SaveAsAggregator saveAsAggregator = (SaveAsAggregator) m_aggregatorFactory.createAggregator("save_as"); saveAsAggregator.setMetricName(rollup.getSaveAs()); TrimAggregator trimAggregator = (TrimAggregator) m_aggregatorFactory.createAggregator("trim"); trimAggregator.setTrim(TrimAggregator.Trim.LAST); query.addAggregator(saveAsAggregator); query.addAggregator(trimAggregator); } rollup.addQueries(queries); task.addRollup(rollup); } } return task; }
@When("^I fill the form with data from json and submit$") public void i_fill_the_form_with_data_from_json_and_submit() throws Throwable { JsonParser parser = new JsonParser(); JsonObject myobject = (JsonObject) parser.parse(json); JsonArray myarray = myobject.get("table").getAsJsonArray(); JsonObject pradeep = myarray.get(0).getAsJsonObject(); driver.findElement(By.name("firstname")).sendKeys(pradeep.get("firstname").getAsString()); driver.findElement(By.name("lastname")).sendKeys(pradeep.get("lastname").getAsString()); driver.findElement(By.id("sex-1")).click(); driver.findElement(By.id("exp-2")).click(); driver.findElement(By.id("datepicker")).sendKeys(pradeep.get("date_stopped").getAsString()); driver.findElement(By.id("tea3")).click(); driver.findElement(By.id("tool-1")).click(); Select continents_select = new Select(driver.findElement(By.id("continents"))); continents_select.selectByVisibleText(pradeep.get("continent").getAsString()); Select another_select_list = new Select(driver.findElement(By.id("selenium_commands"))); another_select_list.selectByVisibleText(pradeep.get("selenium_commands").getAsString()); driver.findElement(By.id("submit")).click(); AssertJUnit.assertEquals("Welcome", driver.getTitle()); }