public void execute() throws IOException, URISyntaxException, AuthenticationException { String pa = restRequest.getParameterValue("project-area"); Map<String, JsonElement> typeMap = new TreeMap<String, JsonElement>(); try { IProjectAreaHandle targetArea = ProjectAreaHelpers.getProjectArea(pa, parentService); if(targetArea == null) { response.setStatus(400); return; } IWorkItemServer serverService = parentService.getService(IWorkItemServer.class); List<IWorkItemType> types = WorkItemTypeHelpers.getWorkItemTypes(targetArea, serverService, new NullProgressMonitor()); for(IWorkItemType type : types) { JsonObject typeObject = new JsonObject(); typeObject.addProperty("id", type.getIdentifier()); typeObject.addProperty("name", type.getDisplayName()); typeMap.put(type.getDisplayName(), typeObject); } } catch (TeamRepositoryException e) { response.setStatus(500); } response.getWriter().write(new Gson().toJson(typeMap.values())); }
public static Observable<List<Client>> getAllClients() { ClientsService service = ServiceGenerator.createService(ClientsService.class); return service.getAllClients(UrlManager.getAllClientsURL()) .flatMap(new Function<JsonElement, Observable<List<Client>>>() { @Override public Observable<List<Client>> apply(JsonElement jsonElement) throws Exception { if(jsonElement != null) { Log.i("Get All Clients" , "JSON: "+jsonElement.toString()); if(jsonElement.isJsonArray()) { List<Client> clients = Client.ClientsListParser.fromJsonArray(jsonElement.getAsJsonArray()); return Observable.just(clients); } else { return Observable.error(new Exception("Expected a JSON Array")); } } else { return Observable.just((List<Client>) new ArrayList<Client>()); } } }).observeOn(AndroidSchedulers.mainThread()); }
private static void handleMergeConflict(String key, JsonObject leftObj, JsonElement leftVal, JsonElement rightVal, ConflictStrategy conflictStrategy) throws JsonObjectExtensionConflictException { { switch (conflictStrategy) { case PREFER_FIRST_OBJ: break;//do nothing, the right val gets thrown out case PREFER_SECOND_OBJ: leftObj.add(key, rightVal);//right side auto-wins, replace left val with its val break; case PREFER_NON_NULL: //check if right side is not null, and left side is null, in which case we use the right val if (leftVal.isJsonNull() && !rightVal.isJsonNull()) { leftObj.add(key, rightVal); }//else do nothing since either the left value is non-null or the right value is null break; case THROW_EXCEPTION: throw new JsonObjectExtensionConflictException("Key " + key + " exists in both objects and the conflict resolution strategy is " + conflictStrategy); default: throw new UnsupportedOperationException("The conflict strategy " + conflictStrategy + " is unknown and cannot be processed"); } } }
private Map<String, String> getTextures(JsonObject object) { Map<String, String> map = Maps.<String, String>newHashMap(); if (object.has("textures")) { JsonObject jsonobject = object.getAsJsonObject("textures"); for (Entry<String, JsonElement> entry : jsonobject.entrySet()) { map.put(entry.getKey(), ((JsonElement)entry.getValue()).getAsString()); } } return map; }
static <T> List<T> toList(PickleTable dataTable, Type itemType, JsonElement testData) { List<T> result = new ArrayList<T>(); List<String> keys = convertTopCellsToFieldNames(raw(dataTable.getRows().get(0))); int count = dataTable.getRows().size(); for (int i = 1; i < count; i++) { List<String> valueRow = raw(dataTable.getRows().get(i)); T item = (T) SuperReflect.on((Class) itemType).create().get(); int j = 0; for (String cell : valueRow) { SuperReflect.on(item).set(keys.get(j), cell); j++; } result.add(item); } return Collections.unmodifiableList(result); }
public SetAttributes deserialize(JsonObject object, JsonDeserializationContext deserializationContext, LootCondition[] conditionsIn) { JsonArray jsonarray = JsonUtils.getJsonArray(object, "modifiers"); SetAttributes.Modifier[] asetattributes$modifier = new SetAttributes.Modifier[jsonarray.size()]; int i = 0; for (JsonElement jsonelement : jsonarray) { asetattributes$modifier[i++] = SetAttributes.Modifier.deserialize(JsonUtils.getJsonObject(jsonelement, "modifier"), deserializationContext); } if (asetattributes$modifier.length == 0) { throw new JsonSyntaxException("Invalid attribute modifiers array; cannot be empty"); } else { return new SetAttributes(conditionsIn, asetattributes$modifier); } }
public static SpecimenFhirMapping getSpecimenMappingAttributes (String filePath) throws Exception { SpecimenFhirMapping specimenAttributeMapping=new SpecimenFhirMapping(); Gson gson=new Gson(); try { JsonElement json=gson.fromJson(new FileReader(filePath), JsonElement.class); String jsonAttributeMappingString=((JsonObject)json).get("specimen_attribute_mapping").toString(); specimenAttributeMapping=gson.fromJson(jsonAttributeMappingString,SpecimenFhirMapping.class); //System.out.print(0); } catch (Exception exc) { throw new Exception(exc.toString()); } return specimenAttributeMapping; }
public void LoadPersonen(String path) throws FileNotFoundException { parser = new JsonParser(); Object obj = parser.parse(new FileReader(path)); JsonArray personen = (JsonArray) obj; for (JsonElement j : personen) { JsonObject jsonObject = j.getAsJsonObject(); PersonenSammelung.Personen.add( new Person( jsonObject.get("id").getAsString(), jsonObject.get("name").getAsString(), jsonObject.get("vorname").getAsString(), jsonObject.get("email").getAsString(), jsonObject.get("telefonnummer").getAsString() ) ); } }
private ConfigurationParam makeConfigParam(String key, JsonElement value) { if (value.isJsonNull()) { throw new NullPointerException("value for key '" + key + "' is null!"); } ConfigurationParam param = new ConfigurationParam(); param.setKey(key); String valueStr; if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) { // toString would return the string with quotes around it which we don't want valueStr = value.getAsString(); } else { valueStr = value.toString(); } param.setValue(valueStr); return param; }
public static Branch fromJsonElement(JsonElement jsonElement) { Branch branch = new Branch(); if(!JsonHelper.isNull(jsonElement ,"brCode")) { branch.setCodeBr(jsonElement.getAsJsonObject().get("brCode").getAsInt()); } if(!JsonHelper.isNull(jsonElement ,"brName")) { branch.setNameBr(jsonElement.getAsJsonObject().get("brName").getAsString()); } if(!JsonHelper.isNull(jsonElement ,"brTel")) { branch.setTelBr(jsonElement.getAsJsonObject().get("brTel").getAsString()); } if(!JsonHelper.isNull(jsonElement ,"brAddress")) { branch.setAddressBr(jsonElement.getAsJsonObject().get("brAddress").getAsString()); } return branch; }
/** * Method of converting hashmap to JSON * * @param wordweights a map from related metadata to weights * @param num the number of converted elements * @return converted JSON object */ protected JsonElement mapToJson(Map<String, Double> wordweights, int num) { Gson gson = new Gson(); List<JsonObject> nodes = new ArrayList<>(); Set<String> words = wordweights.keySet(); int i = 0; for (String wordB : words) { JsonObject node = new JsonObject(); node.addProperty("name", wordB); node.addProperty("weight", wordweights.get(wordB)); nodes.add(node); i += 1; if (i >= num) { break; } } String nodesJson = gson.toJson(nodes); JsonElement nodesElement = gson.fromJson(nodesJson, JsonElement.class); return nodesElement; }
private String findType(JsonElement value) throws ValidationException { if (!value.isJsonPrimitive()){ throw new ValidationException("value is an invalid type"); } JsonPrimitive primitiveValue = (JsonPrimitive) value; if (primitiveValue.isNumber() || (primitiveValue.isString() && Util.isNumber(value.getAsString()))) { String v = value.getAsString(); if (!v.contains(".")) { return "long"; } else { return "double"; } } else return "string"; }
@Override public PointDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { PointDto point = new PointDto(); JsonObject asJsonObject = json.getAsJsonObject(); JsonElement jsonElement = asJsonObject.get("coordinates"); PositionDto positionDto = context.deserialize(jsonElement, PositionDto.class); point.setPosition(positionDto); point.setBbox(BoundingBoxParser.parseBbox(asJsonObject, context)); return point; }
@Override public DataManager fromJson(final JsonElement json) { DataManager dt = new DataManager(); dt.fromJson(json); return dt; }
private static <PK extends PrimaryKey<PK>> void primaryKeyFromJson(PK pk, Fielder<PK> fielder, JsonObject json){ if(json == null){ return; } List<Field<?>> fields = fielder.getFields(pk); for(Field<?> field : fields){ String jsonFieldName = field.getKey().getColumnName(); JsonElement jsonValue = json.get(jsonFieldName); if(jsonValue == null || jsonValue instanceof JsonNull){//PK fields are required throw new IllegalStateException(json + " does not contain required key " + jsonFieldName); } Object value = field.parseStringEncodedValueButDoNotSet(jsonValue.getAsString()); field.setUsingReflection(pk, value); } }
static <T extends IJsonMappable> void readJsonableMap(JsonObject o, LinkedHashMap<String, T> list, String tagname, Class<T> clazz) { list.clear(); if (o.has(tagname)) { JsonArray g = JsonUtil.getAsArray(o, tagname); //o.getAsJsonArray(tagname); for (JsonElement element : g) { T def = IJsonable.create(clazz); JsonObject eo; /*try { eo = element.getAsJsonObject(); } catch (Exception e) { return; }*/ eo = JsonUtil.asObject(element); def.fromJson(eo); list.put(def.getMapKey(), def); } } }
/** * Gets the string value of the given JsonElement. Expects the second parameter to be the name of the element's * field if an error message needs to be thrown. */ public static String getString(JsonElement p_151206_0_, String p_151206_1_) { if (p_151206_0_.isJsonPrimitive()) { return p_151206_0_.getAsString(); } else { throw new JsonSyntaxException("Expected " + p_151206_1_ + " to be a string, was " + toString(p_151206_0_)); } }
public static Brand fromJsonElement(JsonElement jsonElement) { Brand brand = new Brand(); if(!JsonHelper.isNull(jsonElement ,"brdCode")) { brand.setCodeBrd(jsonElement.getAsJsonObject().get("brdCode").getAsInt()); } if(!JsonHelper.isNull(jsonElement ,"brdName")) { brand.setNameBrd(jsonElement.getAsJsonObject().get("brdName").getAsString()); } if(!JsonHelper.isNull(jsonElement ,"brdStatus")) { brand.setStatusBrd(jsonElement.getAsJsonObject().get("brdStatus").getAsBoolean()); } return brand; }
public ItemOverride deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException { JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); ResourceLocation resourcelocation = new ResourceLocation(JsonUtils.getString(jsonobject, "model")); Map<ResourceLocation, Float> map = this.makeMapResourceValues(jsonobject); return new ItemOverride(resourcelocation, map); }
private JsonObject getChacheFile(Plugin plugin){ File file = new File(plugin.getDataFolder().getPath()+"/truenonpcdata.json"); if(file.exists()){ try{ JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(new FileReader(file)); return jsonElement.getAsJsonObject(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } }else return null; }
@Override public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException{ @SuppressWarnings("unchecked") Class<T> classOfT = (Class<T>) typeOfT; T enumValue = classOfT.getEnumConstants()[0]; return enumValue.fromPersistentString(json.getAsString()); }
/** * Getting balances - part of account information * @return map of wallet assets structure * @throws BinanceApiException in case of any error */ public Map<String, BinanceWalletAsset> balancesMap() throws BinanceApiException { Map<String, BinanceWalletAsset> mapAssets = new ConcurrentHashMap<>(); for (JsonElement el : balances()) { BinanceWalletAsset w = new BinanceWalletAsset(el.getAsJsonObject()); mapAssets.put(w.getAsset(), w); } return mapAssets; }
public static Location getLocation(JsonElement object) { JsonObject json = object.getAsJsonObject(); World world = AgarMC.get().getWorld(); double x = json.get("x").getAsDouble() + 0.5; double y = json.get("y").getAsDouble(); double z = json.get("z").getAsDouble() + 0.5; try { float yaw = (float)json.get("yaw").getAsDouble(); float pitch = (float)json.get("pitch").getAsDouble(); return new Location(world, x, y, z, yaw, pitch); } catch (UnsupportedOperationException | NullPointerException ex) { return new Location(world, x, y, z); } }
public static Vector4l deserialize4l(JsonElement element) { return new Vector4l( element.getAsJsonObject().get("x").getAsLong(), element.getAsJsonObject().get("y").getAsLong(), element.getAsJsonObject().get("z").getAsLong(), element.getAsJsonObject().get("w").getAsLong() ); }
public static LootRule parse(JsonElement element) { if (element == null) { return null; } else { AttributeMap map = FACTORY.parse(element); return new LootRule(map); } }
private Map<Integer, Stream> getSegMap(JsonObject data) throws UnsupportedEncodingException { HashMap<Integer, Stream> streamMap = new HashMap<>(); JsonArray streams = data.getAsJsonArray("stream"); for (JsonElement streamJson : streams) { if (streamJson.getAsJsonObject().get("channel_type") != null && streamJson.getAsJsonObject().get("channel_type").getAsString().equals("tail")) continue; List<Seg> segList = new ArrayList<>(); JsonArray segJsons = streamJson.getAsJsonObject().getAsJsonArray("segs"); for (JsonElement segJson : segJsons) { String url = segJson.getAsJsonObject().get("cdn_url").getAsString(); double duration = segJson.getAsJsonObject().get("total_milliseconds_audio").getAsInt() / 1000; Seg seg = new Seg(url, duration); segList.add(seg); } int size = streamJson.getAsJsonObject().get("size").getAsInt(); int height = streamJson.getAsJsonObject().get("height").getAsInt(); int width = streamJson.getAsJsonObject().get("width").getAsInt(); Stream stream = new Stream(segList, size, height, width); stream.setSize(size); streamMap.put(calQualityByHeight(height), stream); } return streamMap; }
public DebeziumRecord(String topic, JsonObject payLoad) { this.topic = topic; char op = payLoad.get("op").getAsCharacter(); this.produceTime = payLoad.get("ts_ms").getAsLong(); JsonElement element = null; switch (op) { case 'r': case 'c': type = RowType.INSERT; element = payLoad.get("after"); break; case 'u': type = RowType.UPDATE; element = payLoad.get("after"); break; case 'd': type = RowType.DELETE; element = payLoad.get("before"); break; } this.data = element.getAsJsonObject(); }
private boolean containsCompatibleAsset(JsonArray assets) { for(JsonElement asset : assets) { if(!asset.getAsJsonObject().get("name").getAsString() .endsWith("MC" + WMinecraft.VERSION + (WMinecraft.OPTIFINE ? "-OF" : "") + ".jar")) continue; return true; } return false; }
private static <T> T getValue(JsonElement element, T compared) throws IllegalStateException, ClassCastException, IllegalArgumentException { if (compared instanceof Double) { return (T)(new Double(element.getAsDouble())); } else if (compared instanceof Integer) { return (T)(new Integer(element.getAsInt())); } else if (compared instanceof JsonObject) { return (T)element.getAsJsonObject(); } else if (compared instanceof JsonArray) { return (T)element.getAsJsonArray(); } else if (compared instanceof String) { return (T)element.getAsString(); } else if (compared instanceof Boolean) { return (T)(new Boolean(element.getAsBoolean())); } throw new IllegalArgumentException(); }
private static void getSvgPath(JsonElement path, StringBuilder d) { if (path != null && !path.isJsonNull()) { if (path.isJsonArray()) { Iterator<JsonElement> linesIt = path.getAsJsonArray().iterator(); while (linesIt.hasNext()) { if (d.length() > 0) { d.append(" "); } getSvgPath(linesIt.next(), d); } } else { d.append(path.getAsString()); } } }
@Override public SparseArray<T> read(JsonReader jsonReader) throws IOException { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); return null; } SparseArray<Object> temp = gson.fromJson(jsonReader, typeOfSparseArrayOfObject); SparseArray<T> result = new SparseArray<>(temp.size()); int key; JsonElement tElement; for (int i = 0, size = temp.size(); i < size; ++i) { key = temp.keyAt(i); tElement = gson.toJsonTree(temp.get(key)); result.put(key, (T) JSONUtils.jsonToSimpleObject(tElement.toString(), typeOfT)); } return result; }
public static String formatJson(Object src) { try { JsonParser jp = new JsonParser(); JsonElement je = jp.parse(toJson(src)); return JsonConvertor.getInstance().toJson(je); } catch (Exception e) { return e.getMessage(); } }
protected String getStringOrNull(JsonObject obj, String field) { if (!obj.has(field)) { return null; } JsonElement el = obj.get(field); if (el.isJsonNull()) { return null; } return el.getAsString(); }
private void parsePresenceEvents(JsonObject syncData) { if(syncData.has("presence")) { JsonObject presenceData = syncData.get("presence").getAsJsonObject(); if(presenceData.has("events")) { JsonArray presenceEvents = presenceData.get("events").getAsJsonArray(); for(JsonElement eventElement : presenceEvents) { JsonObject eventObject = eventElement.getAsJsonObject(); if(eventObject.has("sender")) { User user = users.get(eventObject.get("sender").getAsString()); user.update(eventObject); } } } } }
@Override public JsonElement serialize(Registration src, Type typeOfSrc, JsonSerializationContext context) { JsonObject element = new JsonObject(); element.addProperty("endpoint", src.getEndpoint()); element.addProperty("registrationId", src.getId()); element.add("registrationDate", context.serialize(src.getRegistrationDate())); element.add("lastUpdate", context.serialize(src.getLastUpdate())); element.addProperty("address", src.getAddress().getHostAddress() + ":" + src.getPort()); element.addProperty("smsNumber", src.getSmsNumber()); element.addProperty("lwM2mVersion", src.getLwM2mVersion()); element.addProperty("lifetime", src.getLifeTimeInSec()); element.addProperty("bindingMode", src.getBindingMode().toString()); element.add("rootPath", context.serialize(src.getRootPath())); element.add("objectLinks", context.serialize(src.getSortedObjectLinks())); element.add("secure", context.serialize(src.getRegistrationEndpointAddress().getPort() == securePort)); element.add("additionalRegistrationAttributes", context.serialize(src.getAdditionalRegistrationAttributes())); return element; }
public IntegerEntry(JsonObject fields) throws SchemaViolationError { for (Map.Entry<String, JsonElement> field : fields.entrySet()) { String key = field.getKey(); String fieldName = getFieldName(key); switch (fieldName) { case "key": { responseData.put(key, jsonAsString(field.getValue(), key)); break; } case "ttl": { LocalDateTime optional1 = null; if (!field.getValue().isJsonNull()) { optional1 = LocalDateTime.parse(jsonAsString(field.getValue(), key)); } responseData.put(key, optional1); break; } case "value": { responseData.put(key, jsonAsInteger(field.getValue(), key)); break; } case "__typename": { responseData.put(key, jsonAsString(field.getValue(), key)); break; } default: { throw new SchemaViolationError(this, key, field.getValue()); } } } }
public static Quat4f parseAxisRotation(JsonElement e) { if (!e.isJsonObject()) throw new JsonParseException("Axis rotation: object expected, got: " + e); JsonObject obj = e.getAsJsonObject(); if (obj.entrySet().size() != 1) throw new JsonParseException("Axis rotation: expected single axis object, got: " + e); Map.Entry<String, JsonElement> entry = obj.entrySet().iterator().next(); Quat4f ret = new Quat4f(); try { if (entry.getKey().equals("x")) { ret.set(new AxisAngle4d(1, 0, 0, Math.toRadians(entry.getValue().getAsNumber().floatValue()))); } else if (entry.getKey().equals("y")) { ret.set(new AxisAngle4d(0, 1, 0, Math.toRadians(entry.getValue().getAsNumber().floatValue()))); } else if (entry.getKey().equals("z")) { ret.set(new AxisAngle4d(0, 0, 1, Math.toRadians(entry.getValue().getAsNumber().floatValue()))); } else throw new JsonParseException("Axis rotation: expected single axis key, got: " + entry.getKey()); } catch(ClassCastException ex) { throw new JsonParseException("Axis rotation value: expected number, got: " + entry.getValue()); } return ret; }
private int createIssue(Issue newIssue) throws IOException { String json = getExecutor().execute(Request.Post("http://demo.bugify.com/api/issues.json") .bodyForm(new BasicNameValuePair("subject", newIssue.getSubject()), new BasicNameValuePair("description", newIssue.getDescription()))) .returnContent().asString(); JsonElement parsed = new JsonParser().parse(json); return parsed.getAsJsonObject().get("issue_id").getAsInt(); }
private ArrayList<String> retrieveTagsFromJson(JsonObject response) { JsonArray tagArray = response.getAsJsonArray("tags"); ArrayList<String> tags = new ArrayList<>(); for (JsonElement element : tagArray) tags.add(element.getAsJsonObject().get("name").getAsString()); return tags; }
private String parseArg(String arguments, ResourceOperation operation, PropertyValue value, String object) { // parse the argument string and get the "value" parameter JsonObject args; String val = null; JsonElement jElem = null; Boolean passed = true; // check for parameters from the command if(arguments != null){ args = new JsonParser().parse(arguments).getAsJsonObject(); jElem = args.get(object); } // if the parameter is passed from the command, use it, otherwise treat parameter as the default if (jElem == null || jElem.toString().equals("null")) { val = operation.getParameter(); passed = false; } else { val = jElem.toString().replace("\"", ""); } // if no value is specified by argument or parameter, take the object default from the profile if (val == null) { val = value.getDefaultValue(); passed = false; } // if a mapping translation has been specified in the profile, use it Map<String,String> mappings = operation.getMappings(); if (mappings != null && mappings.containsKey(val)) { val = mappings.get(val); passed = false; } if (!value.mask().equals(BigInteger.ZERO) && passed) { val = transform.format(value, val); } return val; }