private void mergeUpdate(JsonObject update, JsonObject master) { for (Map.Entry<String, JsonElement> attr : update.entrySet()) { if ((null == attr.getValue()) || attr.getValue().isJsonNull()) { // TODO use singleton to reduce memory footprint master.add(attr.getKey(), new JsonNull()); } assertCompatibility(master.get(attr.getKey()), attr.getValue()); if (attr.getValue() instanceof JsonPrimitive) { if (!master.has(attr.getKey()) || !master.get(attr.getKey()).equals(attr.getValue())) { master.add(attr.getKey(), attr.getValue()); } } else if (attr.getValue() instanceof JsonObject) { if (!master.has(attr.getKey()) || master.get(attr.getKey()).isJsonNull()) { // copy whole subtree master.add(attr.getKey(), attr.getValue()); } else { // recurse to merge attribute updates mergeUpdate( attr.getValue().getAsJsonObject(), master.get(attr.getKey()).getAsJsonObject()); } } else if (attr.getValue() instanceof JsonArray) { // TODO any way to correlate elements between arrays? will need concept of // element identity to merge elements master.add(attr.getKey(), attr.getValue()); } } }
/** * Contains the logic to create URITemplate XML Element from the swagger 2.0 resource. * * @param swaggerDocObject swagger document * @return URITemplate element. */ private static List<OMElement> createURITemplateFromSwagger2(JsonObject swaggerDocObject) { List<OMElement> uriTemplates = new ArrayList<>(); JsonObject paths = swaggerDocObject.get(SwaggerConstants.PATHS).getAsJsonObject(); Set<Map.Entry<String, JsonElement>> pathSet = paths.entrySet(); for (Map.Entry path : pathSet) { JsonObject urlPattern = ((JsonElement) path.getValue()).getAsJsonObject(); String pathText = path.getKey().toString(); Set<Map.Entry<String, JsonElement>> operationSet = urlPattern.entrySet(); for (Map.Entry operationEntry : operationSet) { OMElement uriTemplateElement = factory.createOMElement(URI_TEMPLATE, namespace); OMElement urlPatternElement = factory.createOMElement(URL_PATTERN, namespace); OMElement httpVerbElement = factory.createOMElement(HTTP_VERB, namespace); OMElement authTypeElement = factory.createOMElement(AUTH_TYPE, namespace); urlPatternElement.setText(pathText); httpVerbElement.setText(operationEntry.getKey().toString()); uriTemplateElement.addChild(urlPatternElement); uriTemplateElement.addChild(httpVerbElement); uriTemplateElement.addChild(authTypeElement); uriTemplates.add(uriTemplateElement); } } return uriTemplates; }
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(); } }
@Override public CreatureTypeSaveObject deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { CreatureTypeSaveObject saveObject = new CreatureTypeSaveObject(); JsonObject endObject = GsonHelper.getAsJsonObject(json); String fileVersion = GsonHelper.getMemberOrDefault(endObject, FILE_VERSION_KEY, FILE_VERSION); JsonElement jsonElement = endObject.get(TYPE_KEY); if (jsonElement != null && jsonElement.isJsonObject()) { JsonObject types = jsonElement.getAsJsonObject(); TreeMap<String, CreatureTypeBuilder> typeMap = new TreeMap<String, CreatureTypeBuilder>(); for (Entry<String, JsonElement> entry : types.entrySet()) { JsonObject builderObject = GsonHelper.getAsJsonObject(entry.getValue()); CreatureTypeBuilder builder = new CreatureTypeBuilder( entry.getKey(), GsonHelper.getMemberOrDefault(builderObject, SPAWN_RATE_KEY, 1), GsonHelper.getMemberOrDefault(builderObject, MAX_CREATURE_KEY, 10)); builder.withChanceToChunkSpawn( GsonHelper.getMemberOrDefault(builderObject, CHUNK_CHANCE_KEY, 0f)); builder.setRawMedium( GsonHelper.getMemberOrDefault(builderObject, SPAWN_MEDIUM_KEY, "air")); builder.setIterationsPerChunk( GsonHelper.getMemberOrDefault(builderObject, ITER_PER_CHUNK, 3)); builder.setIterationsPerPack( GsonHelper.getMemberOrDefault(builderObject, ITER_PER_PACK, 4)); if (fileVersion.equals("1.0")) { TagConverter tag = new TagConverter(GsonHelper.getMemberOrDefault(builderObject, "Tags", "")); builder.withSpawnExpression(tag.expression); } else { builder.withSpawnExpression( GsonHelper.getMemberOrDefault(builderObject, OPTIONAL_PARAM_KEY, "")); } builder.withDefaultBiomeCap( GsonHelper.getMemberOrDefault(builderObject, DEFAULT_BIOME_CAP_KEY, -1)); JsonObject caps = GsonHelper.getMemberOrDefault(builderObject, MAPPING_TO_CAP, new JsonObject()); for (Entry<String, JsonElement> capEntry : caps.entrySet()) { builder.withBiomeCap( capEntry.getKey(), GsonHelper.getAsOrDefault(builderObject, builder.getDefaultBiomeCap())); if (capEntry.getValue().isJsonPrimitive() && capEntry.getValue().getAsJsonPrimitive().isNumber()) { builder.withBiomeCap( capEntry.getKey(), capEntry.getValue().getAsJsonPrimitive().getAsInt()); } } typeMap.put(builder.typeID, builder); } saveObject.types = Optional.of(typeMap); } return saveObject; }
@Override public void _on_data(String name, JsonObject obj) { Flog.info("on_data %s %s", obj, name); if (!name.equals("create_user")) { return; } FloorcJson floorcJson = FloorcJson.getFloorcJsonFromSettings(); HashMap<String, String> auth_host = floorcJson.auth.get(host); if (floorcJson.auth == null) { floorcJson.auth = new HashMap<String, HashMap<String, String>>(); } if (auth_host == null) { auth_host = new HashMap<String, String>(); floorcJson.auth.put(host, auth_host); } for (Map.Entry<String, JsonElement> thing : obj.entrySet()) { String key = thing.getKey(); if (key.equals("name")) { continue; } auth_host.put(key, thing.getValue().getAsString()); } PersistentJson p = PersistentJson.getInstance(); Settings.write(context, floorcJson); p.auto_generated_account = true; p.disable_account_creation = true; p.save(); context.statusMessage( String.format( "Successfully created new Floobits account with username %s. " + "You can now share a project or join a workspace.", auth_host.get("username"))); Flog.info("All setup"); context.shutdown(); }
private void convert(File oldFile, File newFile) throws IOException { if (oldFile.getName().equals("modules.json")) { try { setCurrentAction("Reading old keybinds"); BufferedReader load = new BufferedReader(new FileReader(oldFile)); JsonObject json = (JsonObject) new JsonParser().parse(load); load.close(); setCurrentAction("Converting keybinds"); TreeMap<String, String> keybinds = new TreeMap<String, String>(); Iterator<Entry<String, JsonElement>> itr1 = json.entrySet().iterator(); while (itr1.hasNext()) { Entry<String, JsonElement> entry = itr1.next(); JsonObject jsonModule = (JsonObject) entry.getValue(); keybinds.put( jsonModule.get("keybind").getAsString(), ".t " + entry.getKey().toLowerCase()); } json = new JsonObject(); Iterator<Entry<String, String>> itr2 = keybinds.entrySet().iterator(); while (itr2.hasNext()) { Entry<String, String> entry = itr2.next(); json.addProperty(entry.getKey(), entry.getValue()); } setCurrentAction("Saving converted keybinds"); PrintWriter save = new PrintWriter(new FileWriter(newFile)); save.println(gson.toJson(json)); save.close(); } catch (Exception e) { e.printStackTrace(); } } }
private Map<String, Object> asMap(JsonObject jsonObj) { Map<String, Object> retval = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) { retval.put(entry.getKey(), fromJsonValue(entry.getValue())); } return retval; }
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; }
protected static String encodeRedirectArgs(JsonObject args, Object[] args2) { if (args == null && args2 == null) return ""; if (args2 != null) { StringBuilder sb = new StringBuilder(); assert (args2.length & 1) == 0 : "Number of arguments shoud be power of 2."; // Must be field-name / value pairs for (int i = 0; i < args2.length; i += 2) { sb.append(i == 0 ? '?' : '&').append(args2[i]).append('='); try { sb.append(URLEncoder.encode(args2[i + 1].toString(), "UTF-8")); } catch (UnsupportedEncodingException ex) { throw Log.errRTExcept(ex); } } return sb.toString(); } StringBuilder sb = new StringBuilder(); sb.append("?"); for (Map.Entry<String, JsonElement> entry : args.entrySet()) { JsonElement e = entry.getValue(); if (sb.length() != 1) sb.append("&"); sb.append(entry.getKey()); sb.append("="); try { sb.append(URLEncoder.encode(e.getAsString(), "UTF-8")); } catch (UnsupportedEncodingException ex) { throw Log.errRTExcept(ex); } } return sb.toString(); }
protected ThingStatusDetail authenticate(String username, String password) { TokenRequest token = new TokenRequest(username, password); String payLoad = gson.toJson(token); Response response = tokenTarget.request().post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE)); logger.trace("Authenticating : Response : {}", response.getStatusInfo()); if (response != null) { if (response.getStatus() == 200 && response.hasEntity()) { String responsePayLoad = response.readEntity(String.class); JsonObject readObject = parser.parse(responsePayLoad).getAsJsonObject(); for (Entry<String, JsonElement> entry : readObject.entrySet()) { switch (entry.getKey()) { case "access_token": { accessToken = entry.getValue().getAsString(); logger.trace("Authenticating : Setting access code to : {}", accessToken); return ThingStatusDetail.NONE; } } } } else if (response.getStatus() == 401) { return ThingStatusDetail.CONFIGURATION_ERROR; } else if (response.getStatus() == 503) { return ThingStatusDetail.COMMUNICATION_ERROR; } } return ThingStatusDetail.CONFIGURATION_ERROR; }
@Override public void write(JsonWriter out, Patch<Data> value) throws IOException { JsonTreeWriter treeWriter = new JsonTreeWriter(); treeWriter.setSerializeNulls(true); _dataAdapter.write(treeWriter, value.data()); JsonObject tree = treeWriter.get().getAsJsonObject(); Set<String> presentJsonProperties = new HashSet<>(); for (Field field : value.changedFields()) { SerializedName nameSpecifier = field.getAnnotation(SerializedName.class); String jsonPropertyName = (nameSpecifier != null ? nameSpecifier.value() : field.getName()); presentJsonProperties.add(jsonPropertyName); } for (Map.Entry<String, JsonElement> entry : new ArrayList<>(tree.entrySet())) { if (!presentJsonProperties.contains(entry.getKey())) { tree.remove(entry.getKey()); } } // If a data field changed to null the null should be serialized. // This is the whole point of this adapter. ObjectTargetedJsonWriter patchWriter = new ObjectTargetedJsonWriter(out); patchWriter.setTargetedSerializeNulls(true); _gson.getAdapter(JsonObject.class).write(patchWriter, tree); }
private PillarsConfig() { String configText; JsonElement root; JsonObject rootObj; JsonObject pillarsObj; try { configText = Utils.getFileFromConfig(CORE_FILE_NAME, false); root = new JsonParser().parse(configText); rootObj = root.getAsJsonObject(); pillarsObj = rootObj.getAsJsonObject(KEY_PILLARS); for (Entry<String, JsonElement> entry : pillarsObj.entrySet()) { String name = entry.getKey(); if (name == null || name.equals("")) { System.out.println("Pillar name cant be null"); continue; } if (nameToPillar.containsKey(name)) { System.out.println("Pillar " + name + " allready registered"); continue; } processPillar(name, entry.getValue().getAsJsonObject()); } nameOrderedBySize = new ArrayList<String>(nameToPillar.size()); for (Entry<String, Pillar> entry : nameToPillar.entrySet()) { orderMap(entry.getValue()); } /*for(String s : nameOrderedBySize){ System.out.println("........................ "+s); }*/ } catch (Exception e) { e.printStackTrace(); } }
@Test public void write_onPatchWithInnerObject_fullyWritesInnerObject() { TestData original = new TestData(); TestData updated = new TestData(); updated.setInnerData(new InnerTestData()); Patch<TestData> patch = MakePatch.from(original).to(updated).with(new ReflectivePatchCalculator<>()); JsonObject json = toJson(patch); assertTrue(json.has("innerData")); assertTrue(json.get("innerData").isJsonObject()); JsonObject innerJson = json.get("innerData").getAsJsonObject(); Collection<String[]> fields = Collections2.transform( innerJson.entrySet(), entry -> new String[] {entry.getKey(), entry.getValue().getAsString()}); assertThat( fields, containsInAnyOrder( new String[] {"json-name-alias", "inner-named-value"}, new String[] {"name1", "inner-value-1"}, new String[] {"name2", "inner-value-2"})); }
public static JsonObject mergeJsonFiles(JsonObject target, String... filenames) throws IOException { if (target == null) { target = new JsonObject(); } for (String filename : filenames) { String url = Config.CLOUD_STORAGE_BASE_URL + filename; JsonObject obj = fetchJsonFromPublicURL(url); if (obj == null) { throw new FileNotFoundException(url); } else { for (Entry<String, JsonElement> entry : obj.entrySet()) { if (entry.getValue().isJsonArray()) { // tries to merge an array with the existing one, if it's the case: JsonArray existing = target.getAsJsonArray(entry.getKey()); if (existing == null) { existing = new JsonArray(); target.add(entry.getKey(), existing); } existing.addAll(entry.getValue().getAsJsonArray()); } else { target.add(entry.getKey(), entry.getValue()); } } } } return target; }
@Override protected void runOneIteration() throws Exception { NodesInfo action = new NodesInfo.Builder().build(); JestResult result = null; try { result = client.execute(action); } catch (Exception e) { logger.error("Error executing NodesInfo!", e); // do not elevate the exception since that will stop the scheduled calls. // throw new RuntimeException("Error executing NodesInfo!", e); } if (result != null) { LinkedHashSet<String> httpHosts = new LinkedHashSet<String>(); JsonObject jsonMap = result.getJsonObject(); JsonObject nodes = (JsonObject) jsonMap.get("nodes"); if (nodes != null) { for (Entry<String, JsonElement> entry : nodes.entrySet()) { JsonObject host = (JsonObject) entry.getValue(); String http_address = host.get("http_address").getAsString(); if (null != http_address) { String cleanHttpAddress = "http://" + http_address.substring(6, http_address.length() - 1); httpHosts.add(cleanHttpAddress); } } } logger.info("Discovered Http Hosts: {}", httpHosts); client.setServers(httpHosts); } }
/** * Compare an var map JSON object with another (original) and determine if there is any difference * from the original. * * @param obj (New) var map JSON object * @param original Original var map JSON object * @return If there is no difference between obj and original, return null If the two are * different, return a JSON object that has all the members and only the members of obj, with * the different fields marked by the sub-field "isNew: true" Note: if some keys of original * have been deleted in obj, the return value is still non-null, but the deletion is not * oreflected in the return value. */ public static JsonObject compare(JsonObject obj, JsonObject original) { boolean diff = false; for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { final String varName = entry.getKey(); final JsonObject varObj = entry.getValue().getAsJsonObject(); if (!original.has(varName)) { diff = true; obj.get(varName).getAsJsonObject().add(IS_NEW_KEY, new JsonPrimitive(true)); } else { final JsonObject origVarObj = original.get(varName).getAsJsonObject(); if (!varObj.get(TYPE_KEY).getAsString().equals(origVarObj.get(TYPE_KEY).getAsString()) || !varObj .get(VALUE_KEY) .getAsString() .equals(origVarObj.get(VALUE_KEY).getAsString())) { diff = true; obj.get(varName).getAsJsonObject().add(IS_NEW_KEY, new JsonPrimitive(true)); } } } return diff ? obj : null; }
public static SiebelPropertySet JsonObjectToPropertySet(JsonObject obj, SiebelPropertySet ps) { Iterator<Entry<String, JsonElement>> iterator = obj.entrySet().iterator(); ps.setType("SiebelMessage"); SiebelPropertySet child; while (iterator.hasNext()) { JsonArray jsonArray = new JsonArray(); JsonObject jsonObject = new JsonObject(); Map.Entry mapEntry = (Map.Entry) iterator.next(); if (mapEntry != null) { JsonElement jsonelement = (JsonElement) mapEntry.getValue(); if (jsonelement.isJsonArray()) { jsonArray = jsonelement.getAsJsonArray(); child = new SiebelPropertySet(); child.setType("ListOf-" + mapEntry.getKey().toString()); for (int i = 0; i < jsonArray.size(); i++) { if (jsonArray.get(i).isJsonObject() || jsonArray.get(i).isJsonArray()) { SiebelPropertySet temp = new SiebelPropertySet(); temp.setType("" + i); child.addChild(JsonObjectToPropertySet(jsonArray.get(i).getAsJsonObject(), temp)); } else child.setProperty("" + i, jsonArray.get(i).getAsString()); } ps.addChild(child); } else if (jsonelement.isJsonObject()) { jsonObject = jsonelement.getAsJsonObject(); child = new SiebelPropertySet(); child.setType(mapEntry.getKey().toString()); ps.addChild(JsonObjectToPropertySet(jsonObject, child)); } else { ps.setProperty(mapEntry.getKey().toString(), mapEntry.getValue().toString()); } } } return ps; }
@Override public void run() { try { while (active.get()) { SkypePullPacket skypePullPacket = new SkypePullPacket(ezSkype); JsonObject responseData = (JsonObject) skypePullPacket.executeSync(); EzSkype.LOGGER.debug(responseData.toString()); if (responseData.entrySet().size() != 0) { if (responseData.has("eventMessages")) { JsonArray messages = responseData.getAsJsonArray("eventMessages"); for (JsonElement jsonObject : messages) { try { extractInfo(jsonObject.getAsJsonObject()); } catch (Exception e) { EzSkype.LOGGER.error("Error extracting info from:\n" + jsonObject, e); } } } else { EzSkype.LOGGER.error("Bad poll response: " + responseData); } } } } catch (Exception e) { e.printStackTrace(); } }
/* * (non-Javadoc) * * @see * com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) */ public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; } else if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { return primitive.getAsString(); } else if (primitive.isNumber()) { return primitive.getAsNumber(); } else if (primitive.isBoolean()) { return primitive.getAsBoolean(); } } else if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); Object[] result = new Object[array.size()]; int i = 0; for (JsonElement element : array) { result[i] = deserialize(element, null, context); ++i; } return result; } else if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); Map<String, Object> result = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { Object value = deserialize(entry.getValue(), null, context); result.put(entry.getKey(), value); } return result; } else { throw new JsonParseException("Unknown JSON type for JsonElement " + json.toString()); } return null; }
@Override public VersionObject deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { VersionObject obj = new VersionObject(); obj.artifacts = new LinkedList<Artifact>(); JsonObject groupLevel = json.getAsJsonObject().getAsJsonObject("artefacts"); // itterate over the groups for (Entry<String, JsonElement> groupE : groupLevel.entrySet()) { String group = groupE.getKey(); // itterate over the artefacts in the groups for (Entry<String, JsonElement> artifactE : groupE.getValue().getAsJsonObject().entrySet()) { Artifact artifact = context.deserialize(artifactE.getValue(), Artifact.class); artifact.group = group; if ("latest".equals(artifactE.getKey())) { obj.latest = artifact; } else { obj.artifacts.add(artifact); } } } return obj; }
public PropertyMap deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { PropertyMap result = new PropertyMap(); Iterator i$; Map.Entry<String, JsonElement> entry; if ((json instanceof JsonObject)) { JsonObject object = (JsonObject) json; for (i$ = object.entrySet().iterator(); i$.hasNext(); ) { entry = (Map.Entry) i$.next(); if ((entry.getValue() instanceof JsonArray)) { for (JsonElement element : (JsonArray) entry.getValue()) { result.put( entry.getKey(), new Property((String) entry.getKey(), element.getAsString())); } } } } else if ((json instanceof JsonArray)) { for (JsonElement element : (JsonArray) json) { if ((element instanceof JsonObject)) { JsonObject object = (JsonObject) element; String name = object.getAsJsonPrimitive("name").getAsString(); String value = object.getAsJsonPrimitive("value").getAsString(); if (object.has("signature")) { result.put( name, new Property(name, value, object.getAsJsonPrimitive("signature").getAsString())); } else { result.put(name, new Property(name, value)); } } } } return result; }
@Override public HanabiraBoard deserialize( JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject boardsJsonObject = json.getAsJsonObject().get("boards").getAsJsonObject(); Set<Map.Entry<String, JsonElement>> boardsSet = boardsJsonObject.entrySet(); if (boardsSet.size() > 1) { throw new IllegalArgumentException("Few board entries received for a request"); } Map.Entry<String, JsonElement> boardEntry = boardsSet.iterator().next(); boardKey = boardEntry.getKey(); JsonObject boardObject = boardEntry.getValue().getAsJsonObject(); int pages = boardObject.get("pages").getAsInt(); HanabiraBoard cachedBoard = Hanabira.getStem().findBoardByKey(boardKey); if (cachedBoard == null) { cachedBoard = new HanabiraBoard(boardKey, pages, null); Hanabira.getStem().saveBoard(cachedBoard); } else { cachedBoard.update(pages, null); } JsonElement pageElement = boardObject.get("page"); int page = (pageElement == null) ? 0 : pageElement.getAsInt(); List<Integer> threadsOnPageIds = new ArrayList<>(); for (JsonElement threadElement : boardObject.getAsJsonArray("threads")) { threadsOnPageIds.add( createThreadWithPosts(threadElement.getAsJsonObject(), boardKey).getThreadId()); } cachedBoard.updatePage(page, threadsOnPageIds); return cachedBoard; }
public static BasicDBObject encode(JsonObject o) { BasicDBObject dbo = new BasicDBObject(); for (Map.Entry<String, JsonElement> elKV : o.entrySet()) { dbo.append(elKV.getKey(), encodeUnknown(elKV.getValue())); } return dbo; } // TESTED
public static Map<String, Object> decodeMap(JsonObject root) { Map<String, Object> map = new HashMap<String, Object>(); for (Entry<String, JsonElement> property : root.entrySet()) { JsonObject value = (JsonObject) property.getValue(); String type = value.get("type").getAsString(); if ("String".equals(type)) { map.put(property.getKey(), value.get("value").getAsString()); } else if ("Integer".equals(type)) { map.put(property.getKey(), value.get("value").getAsInt()); } else if ("Double".equals(type)) { map.put(property.getKey(), value.get("value").getAsDouble()); } else if ("Date".equals(type)) { map.put(property.getKey(), new Date(value.get("time").getAsLong())); } else if ("Boolean".equals(type)) { map.put(property.getKey(), value.get("value").getAsBoolean()); } else if ("LocalDate".equals(type)) { map.put(property.getKey(), LocalDate.parse(value.get("value").getAsString())); } else { throw new IllegalArgumentException( "map contains key with unsupported value type -- " + property.getKey() + ": " + type); } } return map; }
private static void readLabelsToScores(Map<String, Double> obj, JsonObject json) { if (json.has(LABEL_SCORE_MAP)) { JsonObject map = json.getAsJsonObject(LABEL_SCORE_MAP); for (Entry<String, JsonElement> e : map.entrySet()) { obj.put(e.getKey(), e.getValue().getAsDouble()); } } }
/** * Asigna los parametros contantes del request http * * @param httpform */ private void setCommonRequestParamsfromConfig(HttpForm httpform) { Map<String, String> headersParams = new LinkedHashMap<String, String>(); JsonObject jsonHeaderCofig = getJsonConfig().get("request_headers").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : jsonHeaderCofig.entrySet()) { headersParams.put(entry.getKey(), entry.getValue().getAsString()); httpform.putAdditionalRequestProperty(entry.getKey(), entry.getValue().getAsString()); } Map<String, String> requestParams = new LinkedHashMap<String, String>(); JsonObject jsonRequestCofig = getJsonConfig().get("request_parameters").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : jsonRequestCofig.entrySet()) { requestParams.put(entry.getKey(), entry.getValue().getAsString()); httpform.putFieldValue(entry.getKey(), entry.getValue().getAsString()); } }
@NotNull public static List<SymfonyInstallerVersion> getVersions(@NotNull String jsonContent) { JsonObject jsonObject = new JsonParser().parse(jsonContent).getAsJsonObject(); List<SymfonyInstallerVersion> symfonyInstallerVersions = new ArrayList<>(); // prevent adding duplicate version on alias names Set<String> aliasBranches = new HashSet<>(); // get alias version, in most common order for (String s : new String[] {"latest", "lts"}) { JsonElement asJsonObject = jsonObject.get(s); if (asJsonObject == null) { continue; } String asString = asJsonObject.getAsString(); aliasBranches.add(asString); symfonyInstallerVersions.add( new SymfonyInstallerVersion(s, String.format("%s (%s)", asString, s))); } List<SymfonyInstallerVersion> branches = new ArrayList<>(); Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entries) { if (!entry.getKey().matches("^\\d+\\.\\d+$")) { continue; } // "2.8.0-dev", "2.8.0-DEV" is not supported String asString = entry.getValue().getAsString(); if (asString.matches(".*[a-zA-Z].*") || aliasBranches.contains(asString)) { continue; } branches.add( new SymfonyInstallerVersion( asString, String.format("%s (%s)", entry.getKey(), asString))); } branches.sort(Comparator.comparing(SymfonyInstallerVersion::getVersion)); Collections.reverse(branches); symfonyInstallerVersions.addAll(branches); // we need reverse order for sorting them on version string List<SymfonyInstallerVersion> installableVersions = new ArrayList<>(); for (JsonElement installable : jsonObject.getAsJsonArray("installable")) { installableVersions.add(new SymfonyInstallerVersion(installable.getAsString())); } Collections.reverse(installableVersions); symfonyInstallerVersions.addAll(installableVersions); return symfonyInstallerVersions; }
public static APINodeList<ProfilePictureSource> parseResponse( String json, APIContext context, APIRequest request) { APINodeList<ProfilePictureSource> profilePictureSources = new APINodeList<ProfilePictureSource>(request, json); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); try { JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { profilePictureSources.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context)); } ; return profilePictureSources; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { try { JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject(); profilePictureSources.setPaging( paging.get("before").getAsString(), paging.get("after").getAsString()); } catch (Exception ignored) { } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { profilePictureSources.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context)); } ; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); profilePictureSources.add(loadJSON(obj.toString(), context)); } return profilePictureSources; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { profilePictureSources.add(loadJSON(entry.getValue().toString(), context)); } return profilePictureSources; } else { // Fifth, check if it's pure JsonObject profilePictureSources.add(loadJSON(json, context)); return profilePictureSources; } } } catch (Exception e) { } return null; }
private static String compareObjects(String path, JsonObject o1, JsonObject o2) { for (Map.Entry<String, JsonElement> en : o1.entrySet()) { String n = en.getKey(); if (!n.equals("fhir_comments")) { if (o2.has(n)) { String s = compareNodes(path + '.' + n, en.getValue(), o2.get(n)); if (!Utilities.noString(s)) return s; } else return "properties differ at " + path + ": missing property " + n; } } for (Map.Entry<String, JsonElement> en : o2.entrySet()) { String n = en.getKey(); if (!n.equals("fhir_comments")) { if (!o1.has(n)) return "properties differ at " + path + ": missing property " + n; } } return null; }
private static void readAttributes(HasAttributes obj, JsonObject json) { if (json.has("properties")) { JsonObject properties = json.getAsJsonObject("properties"); for (Entry<String, JsonElement> entry : properties.entrySet()) { obj.addAttribute(entry.getKey(), entry.getValue().getAsString()); } } }