private static JsonObject getJsonError(OperationResult operationResult) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("errorIdentification", operationResult.getErrorIdentification()); jsonObject.addProperty("errorDescription", operationResult.getErrorDescription()); return jsonObject; }
@Override public JsonElement serialize(Project project, Type type, JsonSerializationContext context) { JsonObject o = new JsonObject(); o.addProperty("id", project.getId()); o.addProperty("name", project.getName()); return o; }
private void createDatabaseFile() { try { fos = this.context.openFileOutput(this.databaseName, Context.MODE_APPEND); JsonObject dataObject = new JsonObject(); dataObject.addProperty( "ANDROID_ID", Settings.Secure.getString(this.context.getContentResolver(), Settings.Secure.ANDROID_ID)); dataObject.addProperty( this.COLUMN_TIME_OFFSET, TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60); try { dataObject.addProperty("FUNF_VERSION", FunfManager.funfManager.getVersion()); } catch (NullPointerException e) { } try { dataObject.addProperty( "APPLICATION_VERSION", FunfManager.funfManager.getApplicationVersion()); } catch (NullPointerException e) { } fos.write((dataObject.toString() + "\n").getBytes()); } catch (IOException e) { e.printStackTrace(); } }
/** * Converts the properties object into a JSON string. * * @param properties The properties object to convert. * @param envelope Envelope for resulting JSON object. Null if not needed. * @return A JSON string representing the object. */ public static String toJson(PropertiesConfiguration properties, String envelope) { JsonObject json = new JsonObject(); Iterator<String> i = properties.getKeys(); while (i.hasNext()) { final String key = i.next(); final String value = properties.getString(key); if (value.equals("true") || value.equals("false")) { json.addProperty(key.toString(), Boolean.parseBoolean(value)); } else if (PATTERN_INTEGER.matcher(value).matches()) { json.addProperty(key.toString(), Integer.parseInt(value)); } else if (PATTERN_FLOAT.matcher(value).matches()) { json.addProperty(key.toString(), Float.parseFloat(value)); } else { json.addProperty(key.toString(), value); } } GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping(); Gson gson = gsonBuilder.create(); String _json = gson.toJson(json); if (envelope != null && !envelope.isEmpty()) { _json = envelope(_json, envelope); } return _json; }
@Override protected Response serve() { InputStream s = null; String urlStr = _url.value(); try { // if( urlStr.startsWith("file://") ) { // urlStr = urlStr.substring("file://".length()); if (urlStr.startsWith("file:///")) { urlStr = urlStr.substring("file:///".length()); File f = new File(urlStr); // urlStr = "file://"+f.getCanonicalPath(); urlStr = "file:///" + f.getCanonicalPath(); } URL url = new URL(urlStr); Key k = _key.value(); if (k == null) k = Key.make(urlStr); s = url.openStream(); if (s == null) return Response.error("Unable to open stream to URL " + url.toString()); ValueArray.readPut(k, s); JsonObject json = new JsonObject(); json.addProperty(KEY, k.toString()); json.addProperty(URL, urlStr); Response r = Response.done(json); r.setBuilder(KEY, new KeyElementBuilder()); return r; } catch (IllegalArgumentException e) { return Response.error("Not a valid key: " + urlStr); } catch (IOException e) { return Response.error(e); } finally { Closeables.closeQuietly(s); } }
private JsonObject getJsonObject(String action, String payload, Map<String, String> env) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", action); jsonMessage.addProperty("payload", payload); jsonMessage.add("env", this.parser.fromJson(this.parser.toJson(env), JsonObject.class)); return jsonMessage; }
@Override public JsonElement serialize( CreatureTypeSaveObject src, Type typeOfSrc, JsonSerializationContext context) { JsonObject endObject = new JsonObject(); endObject.addProperty(FILE_VERSION_KEY, FILE_VERSION); JsonObject types = new JsonObject(); for (CreatureTypeBuilder type : src.types.get().values()) { JsonObject entry = new JsonObject(); entry.addProperty(SPAWN_RATE_KEY, type.spawnRate); entry.addProperty(MAX_CREATURE_KEY, type.maxNumberOfCreature); entry.addProperty(CHUNK_CHANCE_KEY, type.getChunkSpawnChance()); entry.addProperty(SPAWN_MEDIUM_KEY, type.getRawSpawnMedium()); entry.addProperty(ITER_PER_CHUNK, type.getIterationsPerChunk()); entry.addProperty(ITER_PER_PACK, type.getIterationsPerPack()); entry.addProperty(OPTIONAL_PARAM_KEY, type.getSpawnExpression()); entry.addProperty(DEFAULT_BIOME_CAP_KEY, type.getDefaultBiomeCap()); JsonObject biomeCaps = new JsonObject(); for (Entry<String, Integer> capEntry : type.getBiomeCaps().entrySet()) { biomeCaps.addProperty(capEntry.getKey(), capEntry.getValue()); } entry.add(MAPPING_TO_CAP, biomeCaps); types.add(type.typeID, entry); } endObject.add(TYPE_KEY, types); return endObject; }
public static String a(Map var0) { JsonObject var1 = new JsonObject(); Iterator var2 = var0.entrySet().iterator(); while (var2.hasNext()) { Entry var3 = (Entry) var2.next(); if (((class_nf) var3.getValue()).b() != null) { JsonObject var4 = new JsonObject(); var4.addProperty("value", Integer.valueOf(((class_nf) var3.getValue()).a())); try { var4.add("progress", ((class_nf) var3.getValue()).b().a()); } catch (Throwable var6) { b.warn( "Couldn\'t save statistic " + ((class_nd) var3.getKey()).e() + ": error serializing progress", var6); } var1.add(((class_nd) var3.getKey()).e, var4); } else { var1.addProperty( ((class_nd) var3.getKey()).e, Integer.valueOf(((class_nf) var3.getValue()).a())); } } return var1.toString(); }
@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; }
public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("account", accountName); jsonObject.addProperty("password", accountPassword); jsonObject.add("user", user.toJson()); return jsonObject; }
@Override public JsonObject saveToJson() { JsonObject obj = new JsonObject(); obj.addProperty("type", getClass().getSimpleName()); obj.addProperty("duration", getDuration()); return obj; }
@Override public JsonElement serialize( FirewallOptions src, Type typeOfSrc, JsonSerializationContext context) { JsonObject firewall = new JsonObject(); if (src.getName() != null) { firewall.addProperty("name", src.getName()); } if (src.getNetwork() != null) { firewall.addProperty("network", src.getNetwork().toString()); } if (!src.getSourceRanges().isEmpty()) { firewall.add("sourceRanges", buildArrayOfStrings(src.getSourceRanges())); } if (!src.getSourceTags().isEmpty()) { firewall.add("sourceTags", buildArrayOfStrings(src.getSourceTags())); } if (!src.getTargetTags().isEmpty()) { firewall.add("targetTags", buildArrayOfStrings(src.getTargetTags())); } if (!src.getAllowed().isEmpty()) { JsonArray rules = new JsonArray(); for (Rule rule : src.getAllowed()) { rules.add(context.serialize(rule, Firewall.Rule.class)); } firewall.add("allowed", rules); } return firewall; }
@Test public void testOpeningTimeTypeAdapter() { assertEquals(adapter.getAdaptedType(), OpeningTime.class); JsonObject openingTimeJson = new JsonObject(); openingTimeJson.addProperty("day", "Monday"); openingTimeJson.addProperty("timeStart", "12:00"); openingTimeJson.addProperty("timeStop", "15:00"); OpeningTime openingTime = adapter.deserialize(openingTimeJson, OpeningTime.class, null); assertEquals(openingTimeJson.get("day").getAsString(), openingTime.getDay().value()); assertEquals( openingTimeJson.get("timeStart").getAsString(), String.format( "%02d:%02d", openingTime.getTimeStart().getHourOfDay(), openingTime.getTimeStart().getMinutesInHour())); assertEquals( openingTimeJson.get("timeStop").getAsString(), String.format( "%02d:%02d", openingTime.getTimeStop().getHourOfDay(), openingTime.getTimeStop().getMinutesInHour())); }
@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; }
private void saveSetup() { RequestProperties headers = null; if (this.getString("item_id") == null) { headers = new RequestProperties.Builder() .method("POST") .endPoint("api/v/1/data/" + collectionId) .body(this.json) .build(); } else { // Create Payload object JsonObject payload = new JsonObject(); payload.addProperty("$set", this.changes.toString()); JsonObject query = new JsonObject(); query.addProperty("item_id", this.getString("item_id")); payload.addProperty("query", query.toString()); headers = new RequestProperties.Builder() .method("PUT") .endPoint("api/v/1/data/" + collectionId) .body(payload) .build(); } request.setHeaders(headers); }
@Override public void updateCommand(String deviceId, DeviceCommand command) throws HiveException { if (command == null) { throw new HiveClientException("Command cannot be null!", BAD_REQUEST.getStatusCode()); } if (command.getId() == null) { throw new HiveClientException("Command id cannot be null!", BAD_REQUEST.getStatusCode()); } logger.debug( "DeviceCommand: update requested for device id {] and command: id {}, flags {}, status {}, " + " result {}", deviceId, command.getId(), command.getFlags(), command.getStatus(), command.getResult()); JsonObject request = new JsonObject(); request.addProperty("action", "command/update"); request.addProperty("deviceGuid", deviceId); request.addProperty("commandId", command.getId()); Gson gson = GsonFactory.createGson(COMMAND_UPDATE_FROM_DEVICE); request.add("command", gson.toJsonTree(command)); websocketAgent.getWebsocketConnector().sendMessage(request); logger.debug( "DeviceCommand: update request proceed successfully for device id {] and command: id {}, " + "flags {}, status {}, result {}", deviceId, command.getId(), command.getFlags(), command.getStatus(), command.getResult()); }
private JsonObject getJsonObject(String action, String payload, String scriptPath) { JsonObject jsonMessage = new JsonObject(); jsonMessage.addProperty("action", action); jsonMessage.addProperty("payload", payload); jsonMessage.addProperty("script-path", scriptPath); return jsonMessage; }
public static JsonObject getElementContent(ElementModel model, JsonObject j) { int type = model.getType(); int color = model.getColor(); String title = model.getTitle(); j.addProperty("type", type); j.addProperty("color", color); j.addProperty("title", title); if (type == Constants.TYPE_ELEMENT_PICTURE) { byte[] content = ((PictureElementModel) model).getContent(); if (content != null) { String picture_str = Base64.encodeBytes(content, Base64.NO_OPTIONS); j.addProperty(Constants.JSON_CONTENT, picture_str); } } else if (type == Constants.TYPE_ELEMENT_LINK) { String url = ((LinkElementModel) (model)).getContent(); j.addProperty(Constants.JSON_CONTENT, url); } else if (type == Constants.TYPE_ELEMENT_TEXT) { String text = ((TextElementModel) model).getContent(); j.addProperty(Constants.JSON_CONTENT, text); } // TODO /*else if(type == Constants.TYPE_ELEMENT_FILE){ String file_str = new String( ((FileElementModel)(((ElementAgent)sender).getContentModel())).getContent(), "UTF-8"); }*/ return j; }
private void getStats(WebSocketSession session) { try { Map<String, Stats> wr_stats = webRtcEndpoint.getStats(); for (Stats s : wr_stats.values()) { switch (s.getType()) { case endpoint: EndpointStats end_stats = (EndpointStats) s; double e2eVideLatency = end_stats.getVideoE2ELatency() / 1000000; JsonObject response = new JsonObject(); response.addProperty("id", "videoE2Elatency"); response.addProperty("message", e2eVideLatency); sendMessage(session, new TextMessage(response.toString())); break; default: break; } } } catch (Throwable t) { log.error("Exception getting stats...", t); } }
public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); jsonObject.add("classElement", classElement.toJson()); if (displayName != null) { jsonObject.addProperty("displayName", displayName); } if (memberElement != null) { jsonObject.add("memberElement", memberElement.toJson()); } if (superclass != null) { jsonObject.addProperty("superclass", superclass); } JsonArray jsonArrayInterfaces = new JsonArray(); for (int elt : interfaces) { jsonArrayInterfaces.add(new JsonPrimitive(elt)); } jsonObject.add("interfaces", jsonArrayInterfaces); JsonArray jsonArrayMixins = new JsonArray(); for (int elt : mixins) { jsonArrayMixins.add(new JsonPrimitive(elt)); } jsonObject.add("mixins", jsonArrayMixins); JsonArray jsonArraySubclasses = new JsonArray(); for (int elt : subclasses) { jsonArraySubclasses.add(new JsonPrimitive(elt)); } jsonObject.add("subclasses", jsonArraySubclasses); return jsonObject; }
private static InputStream generateSoundsJSON() throws IOException { OpenSecurity.logger.info( Minecraft.getMinecraft().mcDataDir + "\\mods\\OpenSecurity\\sounds\\alarms\\"); JsonObject root = new JsonObject(); for (Map.Entry<String, String> entry : sound_map.entrySet()) { JsonObject event = new JsonObject(); event.addProperty("category", "master"); // put under the "record" category for sound options JsonArray sounds = new JsonArray(); // array of sounds (will only ever be one) JsonObject sound = new JsonObject(); // sound object (instead of primitive to use 'stream' flag) sound.addProperty( "name", new File(".") + "\\mods\\OpenSecurity\\sounds\\alarms\\" + entry.getValue().substring(0, entry.getValue().lastIndexOf('.'))); // path to file sound.addProperty("stream", false); // prevents lag for large files sounds.add(sound); event.add("sounds", sounds); root.add( entry.getValue().substring(0, entry.getValue().lastIndexOf('.')), event); // event name (same as name sent to ItemCustomRecord) } // System.out.println(new Gson().toJson(root)); return new ByteArrayInputStream(new Gson().toJson(root).getBytes()); }
public String create() { try { JsonObject gistJson = new JsonObject(); gistJson.addProperty("description", this.getDescription()); gistJson.addProperty("public", this.isPublic()); JsonObject filesJson = new JsonObject(); for (int i = 0; i < getFiles().length; i++) { GistFile gistFile = getFiles()[i]; JsonObject file = new JsonObject(); file.addProperty("content", gistFile.getContent()); String name = gistFile.getFileName(); filesJson.add( (name == null || name.isEmpty() ? "" : name + "-") + date.replace(' ', '_'), file); } gistJson.add("files", filesJson); HttpResponse<JsonNode> response = Unirest.post(GitHub.GISTS_API_URL) .header( "authorization", "token " + Nexus.getInstance().getGitHubConfig().getNexusGitHubApiKey()) .header("accept", "application/json") .header("content-type", "application/json; charset=utf-8") .body(gistJson.toString()) .asJson(); return response.getBody().getObject().getString("html_url"); } catch (UnirestException e) { throw new GistException("Failed to Gist!", e); } }
@Path("/create/{ObjID}/{ObjInsId}") @POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public Response sendCreate( @PathParam("ObjID") String objectId, @PathParam("ObjInsId") String objectInstanceId, @QueryParam("ep") String endPoint, String value) throws InterruptedException { String string = objectId + "/" + objectInstanceId; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("operation", "create"); jsonObject.addProperty("directory", string); jsonObject.addProperty("value", value); Info.setInfo(endPoint, jsonObject.toString()); CountDownLatch signal = Info.getCountDown(endPoint); if (signal == null) { return Response.status(200).entity("Devices not registered yet").build(); } signal.countDown(); CountDownLatch signalRead = new CountDownLatch(1); Info.setCountDownLatchMessageMap(endPoint, signalRead); signalRead.await(); return Response.status(200).entity("creation success").build(); }
@POST @Path("action") public String action( @FormParam("element_1") double n1, @FormParam("element_2") double n2, @FormParam("element_3") String s) { try { MemcachedClient client = MccFactory.getConst("localhost").getMemcachedClient(); JsonObject innerObject = new JsonObject(); innerObject.addProperty("key", s); innerObject.addProperty("firstNum", n1); innerObject.addProperty("secondNum", n2); client.add(s, 30000, innerObject.toString()); String keys = (String) client.get("mykeys"); keys = (keys == null) ? "" : keys; keys += s + "/"; client.replace("mykeys", 30000, keys); } catch (Exception e) { e.printStackTrace(); return getStringStackTrace(e); } return "String: " + s + ". First number = " + n1 + ", Second number = " + n2; }
private void deleteConference(HttpServletRequest request, HttpServletResponse response) throws IOException { JsonObject jsonObject = new JsonObject(); String confName = request.getParameter(ProjConst.CONF_NAME); String resultSuccess; String message; try { ConferenceDao.getInstance().deleteConference(confName); message = "Conference successfully deleted"; resultSuccess = "true"; } catch (Exception e) { message = "Found problem while deleting conference, message: " + e.getMessage(); resultSuccess = "false"; } response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Gson gson = new Gson(); String json; jsonObject.addProperty("resultSuccess", resultSuccess); jsonObject.addProperty("message", message); json = gson.toJson(jsonObject); out.write(json); out.flush(); } finally { out.close(); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String blobKey = req.getParameter("blobKey"); String path = req.getParameter("path"); if (path != null && path.trim().length() > 0) { JsonObject retObj = new JsonObject(); String uploadBlobPath = BlobstoreServiceFactory.getBlobstoreService() .createUploadUrl(URLDecoder.decode(path), UploadOptions.Builder.withDefaults()); retObj.addProperty("result", "success"); retObj.addProperty("path", URLEncoder.encode(uploadBlobPath)); if (retObj.get("result") == null) { retObj.addProperty("result", "fail"); } resp.getWriter().write(retObj.toString()); } else if (blobKey != null) { BlobstoreServiceFactory.getBlobstoreService().serve(new BlobKey(blobKey), resp); } }
@Override public JsonElement serialize(Crowd crowd, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if (crowd.getId() == null || crowd.getId().isEmpty()) { object.addProperty("_id", "-1"); } else { object.addProperty("_id", crowd.getId()); } object.addProperty("name", crowd.getName()); object.addProperty("owner", crowd.getOwner()); if (crowd.getMembers() == null || crowd.getMembers().isEmpty()) { object.add("members", JsonNull.INSTANCE); } else { JsonArray members = new JsonArray(); for (MemberId memberId : crowd.getMembers()) { members.add(new JsonPrimitive(memberId.getId())); object.add("members", members); } } Log.i("CrowdSerializer", "Serialized: " + object.toString()); return object; }
/** * Gson invokes this call-back method during serialization when it encounters a field of the * specified type. * * <p> * * <p>In the implementation of this call-back method, you should consider invoking {@link * com.google.gson.JsonSerializationContext#serialize(Object, java.lang.reflect.Type)} method to * create JsonElements for any non-trivial field of the {@code wrappedStack} object. However, you * should never invoke it on the {@code wrappedStack} object itself since that will cause an * infinite loop (Gson will call your call-back method again). * * @param wrappedStack the object that needs to be converted to Json. * @param typeOfSrc the actual type (fully genericized version) of the source object. * @param context * @return a JsonElement corresponding to the specified object. */ @Override public JsonElement serialize( WrappedStack wrappedStack, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonWrappedStack = new JsonObject(); Gson gson = new Gson(); jsonWrappedStack.addProperty("type", wrappedStack.objectType); jsonWrappedStack.addProperty("stackSize", wrappedStack.stackSize); if (wrappedStack.wrappedStack instanceof ItemStack) { JsonItemStack jsonItemStack = new JsonItemStack(); jsonItemStack.itemName = Item.itemRegistry.getNameForObject(((ItemStack) wrappedStack.wrappedStack).getItem()); jsonItemStack.itemDamage = ((ItemStack) wrappedStack.wrappedStack).getItemDamage(); if (((ItemStack) wrappedStack.wrappedStack).stackTagCompound != null) { jsonItemStack.itemNBTTagCompound = ((ItemStack) wrappedStack.wrappedStack).stackTagCompound; } jsonWrappedStack.add( "objectData", JsonItemStack.jsonSerializer.toJsonTree(jsonItemStack, JsonItemStack.class)); } else if (wrappedStack.wrappedStack instanceof OreStack) { jsonWrappedStack.add( "objectData", gson.toJsonTree(wrappedStack.wrappedStack, OreStack.class)); } else if (wrappedStack.wrappedStack instanceof FluidStack) { JsonFluidStack jsonFluidStack = new JsonFluidStack((FluidStack) wrappedStack.wrappedStack); jsonWrappedStack.add( "objectData", JsonFluidStack.jsonSerializer.toJsonTree(jsonFluidStack, JsonFluidStack.class)); } return jsonWrappedStack; }
@Override public JsonElement serialize( final Counter src, final Type typeOfSrc, final JsonSerializationContext context) { final JsonObject container = new JsonObject(); final JsonObject baseLabels = new JsonObject(); baseLabels.addProperty(Reserved.NAME.label(), src.name); container.add(SERIALIZE_BASE_LABELS, baseLabels); container.addProperty(SERIALIZE_DOCSTRING, src.docstring); final JsonObject metric = new JsonObject(); metric.addProperty("type", "counter"); final JsonArray values = new JsonArray(); for (final Map<String, String> labelSet : src.children.keySet()) { final JsonObject element = new JsonObject(); element.add("labels", context.serialize(labelSet)); final Child vector = src.children.get(labelSet); element.add("value", context.serialize(vector.value.get())); values.add(element); } metric.add("value", values); container.add(SERIALIZE_METRIC, context.serialize(metric)); return container; }
@Override public JsonElement serialize(RemoteClass src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if (src.getName() != null) { object.addProperty("name", src.getName()); } if (src.getDoc() != null) { object.addProperty("doc", src.getDoc().getDoc()); } if (src.isAbstract()) { object.add("abstract", new JsonPrimitive(true)); } if (src.getExtends() != null) { object.add("extends", context.serialize(src.getExtends())); } if (!src.getConstructors().isEmpty()) { object.add("constructors", context.serialize(src.getConstructors())); } if (!src.getMethods().isEmpty()) { object.add("methods", context.serialize(src.getMethods())); } if (!src.getEvents().isEmpty()) { object.add("events", context.serialize(src.getEvents())); } return object; }