public static void serialize(final boolean value, final JsonWriter sw) { if (value) { sw.writeAscii("true"); } else { sw.writeAscii("false"); } }
public static void serializeNullable(final Boolean value, final JsonWriter sw) { if (value == null) { sw.writeNull(); } else if (value) { sw.writeAscii("true"); } else { sw.writeAscii("false"); } }
public JsonSerialization() { super(); jsonWriter = new JsonWriter(); jsonWriter.setOutputType(JsonOutputType.json); jsonWriter.setQuoteLongValues(false); DataWriter<JsonString> writer = jsonWriter; this.setWriter(writer); }
@Test public void testPrimitiveArray() throws IOException { DslJson<Object> json = new DslJson<Object>(); JsonWriter writer = new JsonWriter(); int[] items = new int[] {1, 2}; json.serialize(writer, items); String result = writer.toString(); Assert.assertEquals("[1,2]", result); int[] deserialized = json.deserialize(int[].class, writer.getByteBuffer(), writer.size()); Assert.assertArrayEquals(items, deserialized); }
@Override protected void write(JsonWriter writer) throws IOException { writer.writeBeginArray(); int length = values.size(); for (int i = 0; i < length; i++) { if (i != 0) { writer.writeArrayValueSeparator(); } values.get(i).write(writer); } writer.writeEndArray(); }
@Override void write(JsonWriter writer) throws IOException { writer.writeArrayOpen(); Iterator<JsonValue> iterator = iterator(); if (iterator.hasNext()) { iterator.next().write(writer); while (iterator.hasNext()) { writer.writeArraySeparator(); iterator.next().write(writer); } } writer.writeArrayClose(); }
@Test public void testListGenerics() throws IOException { DslJson<Object> json = new DslJson<Object>(); JsonWriter writer = new JsonWriter(); List<Integer> items = Arrays.asList(1, 2); json.serialize(writer, items); String result = writer.toString(); Assert.assertEquals("[1,2]", result); List<Integer> deserialized = (List) json.deserialize( new Generic<List<Integer>>() {}.type, writer.getByteBuffer(), writer.size()); Assert.assertEquals(items, deserialized); }
@Ignore("not supported yet") @Test public void testNestedArray() throws IOException { DslJson<Object> json = new DslJson<Object>(); JsonWriter writer = new JsonWriter(); int[][] items = new int[2][]; items[0] = new int[] {1, 2}; items[1] = new int[] {3, 4, 5}; json.serialize(writer, items); String result = writer.toString(); Assert.assertEquals("[[1,2],[3,4,5]]", result); int[][] deserialized = json.deserialize(int[][].class, writer.getByteBuffer(), writer.size()); Assert.assertArrayEquals(items, deserialized); }
@Override protected void write(JsonWriter writer) throws IOException { writer.writeBeginObject(); int length = names.size(); for (int i = 0; i < length; i++) { if (i != 0) { writer.writeObjectValueSeparator(); } writer.writeString(names.get(i)); writer.writeNameValueSeparator(); values.get(i).write(writer); } writer.writeEndObject(); }
private static void runScanExercise(Map<String, Path> paths) { // Exercise name, should it be something else than directory name? String exerciseName = paths.get(EXERCISE_PATH).toFile().getName(); Optional<ExerciseDesc> exerciseDesc = Optional.absent(); try { exerciseDesc = executor.scanExercise(paths.get(EXERCISE_PATH), exerciseName); if (!exerciseDesc.isPresent()) { log.error("Absent exercise description after running scanExercise"); printErrAndExit("ERROR: Could not scan the exercises."); } } catch (NoLanguagePluginFoundException e) { log.error("No suitable language plugin for project at {}", paths.get(EXERCISE_PATH), e); printErrAndExit( "ERROR: Could not find suitable language plugin for the given " + "exercise path."); } try { JsonWriter.writeObjectIntoJsonFormat(exerciseDesc.get(), paths.get(OUTPUT_PATH)); System.out.println( "Exercises scanned successfully, results can be found in " + paths.get(OUTPUT_PATH).toString()); } catch (IOException e) { log.error("Could not write output to {}", paths.get(OUTPUT_PATH), e); printErrAndExit("ERROR: Could not write the results to the given file."); } }
public static ExecutionRequest readRequest0( String content, MultivaluedMap<String, String> headers) throws Exception { ExecutionRequest req = new ExecutionRequest(); JsonParser jp = JsonWriter.getFactory().createJsonParser(content); jp.nextToken(); // skip { JsonToken tok = jp.nextToken(); while (tok != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); jp.nextToken(); if ("input".equals(key)) { String input = jp.getText(); if (input != null) { req.setInput(resolveInput(input)); } } else if ("params".equals(key)) { readParams(jp, req); } else if ("context".equals(key)) { readContext(jp, req); } else if ("documentProperties".equals(key)) { // TODO XXX - this is wrong - headers are ready only! see with td String documentProperties = jp.getText(); if (documentProperties != null) { headers.putSingle(JsonDocumentWriter.DOCUMENT_PROPERTIES_HEADER, documentProperties); } } tok = jp.nextToken(); } return req; }
@Override public void write(JsonWriter out) throws IOException { out.startArray(); for (int i = 0; i < values.length; i++) { if (i > 0) { out.writeArraySeparator(); } if (values[i] == null) { out.write(Json.NULL); } else { values[i].write(out); } } out.endArray(); }
private static void createJsonFile() { JsonObject model = Json.createObjectBuilder() .add("firstName", "Martin") .add( "phoneNumbers", Json.createArrayBuilder() .add(Json.createObjectBuilder().add("mobile", "1234 56789")) .add(Json.createObjectBuilder().add("home", "2345 67890"))) .build(); try (JsonWriter jsonWriter = Json.createWriter( new FileWriter( Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) { jsonWriter.write(model); } catch (IOException e) { LOGGER.severe("Failed to create file: " + e.getMessage()); } }
public void toJasonFull(JsonWriter writer) { actualToJason(writer); writer.jsonWrite(","); append__type(writer, __type); writer.jsonWrite(","); append__id(writer); writer.jsonWrite(","); appendOnOff(writer, "ended", ended); writer.jsonWrite(",\"begin\":{"); begin.toJason(writer); writer.jsonWrite("},"); writer.jsonWrite("\"points\":["); for (Iterator<Point> iter = points.iterator(); iter.hasNext(); ) { writer.jsonWrite("{"); iter.next().toJason(writer); writer.jsonWrite("}"); if (iter.hasNext()) writer.jsonWrite(","); } writer.jsonWrite("]"); }
public final void write(JsonWriter paramJsonWriter, T paramT) { if (a == null) { a().write(paramJsonWriter, paramT); return; } if (paramT == null) { paramJsonWriter.nullValue(); return; } Streams.write(a.serialize(paramT, d.getType(), c.b), paramJsonWriter); }
@GET @RolesAllowed({"ADMINISTRATOR"}) public Response findByFilter() { final UserFilter userFilter = new UserUrlFilterExtractor(uriInfo).getFilter(); logger.debug("Finding users using filter: {}", userFilter); final PaginatedData<User> users = userService.find(userFilter); logger.debug("Found {} users", users.getNumberOfRows()); final JsonElement jsonWithPagingAndEntries = JsonUtils.getJsonElementWithPagingAndEntries(users, userJsonConverter); return Response.status(HttpCode.OK.getCode()) .entity(JsonWriter.writeToString(jsonWithPagingAndEntries)) .build(); }
public static String formulateJsonForListQueriesCall(Region<String, String> queryRegion) { HeapDataOutputStream outputStream = new HeapDataOutputStream(com.gemstone.gemfire.internal.Version.CURRENT); try { JsonGenerator generator = enableDisableJSONGeneratorFeature( getObjectMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8)); JsonWriter.writeQueryListAsJson(generator, "queries", queryRegion); generator.close(); return new String(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { outputStream.close(); } }
public static String formulateJsonForGetOnKey(Object value) throws JSONException { HeapDataOutputStream outputStream = new HeapDataOutputStream(com.gemstone.gemfire.internal.Version.CURRENT); try { JsonGenerator generator = enableDisableJSONGeneratorFeature( getObjectMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8)); JsonWriter.writeValueAsJson(generator, value, "GET_ON_KEY_RESPONSE"); generator.close(); return new String(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { outputStream.close(); } }
public static String convertStructToJson(StructImpl structSet) throws JSONException { HeapDataOutputStream outputStream = new HeapDataOutputStream(com.gemstone.gemfire.internal.Version.CURRENT); try { JsonGenerator generator = enableDisableJSONGeneratorFeature( getObjectMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8)); JsonWriter.writeStructAsJson(generator, structSet); generator.close(); return new String(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { outputStream.close(); } }
private static void runTests(Map<String, Path> paths) { RunResult runResult = null; try { runResult = executor.runTests(paths.get(EXERCISE_PATH)); } catch (NoLanguagePluginFoundException e) { log.error("No suitable language plugin for project at {}", paths.get(EXERCISE_PATH), e); printErrAndExit( "ERROR: Could not find suitable language plugin for the given " + "exercise path."); } try { JsonWriter.writeObjectIntoJsonFormat(runResult, paths.get(OUTPUT_PATH)); System.out.println("Test results can be found in " + paths.get(OUTPUT_PATH)); } catch (IOException e) { log.error("Could not write output to {}", paths.get(OUTPUT_PATH), e); printErrAndExit("ERROR: Could not write the results to the given file."); } }
public static String formulateJsonForListFunctionsCall(Set<String> functionIds) { HeapDataOutputStream outputStream = new HeapDataOutputStream(com.gemstone.gemfire.internal.Version.CURRENT); try { JsonGenerator generator = enableDisableJSONGeneratorFeature( getObjectMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8)); generator.writeStartObject(); generator.writeFieldName("functions"); JsonWriter.writeCollectionAsJson(generator, functionIds); generator.writeEndObject(); generator.close(); return new String(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { outputStream.close(); } }
private static void runCheckCodeStyle(Map<String, Path> paths) { ValidationResult validationResult = null; try { validationResult = executor.runCheckCodeStyle(paths.get(EXERCISE_PATH)); } catch (NoLanguagePluginFoundException e) { log.error( "Could not find a language plugin for the project at {}", paths.get(EXERCISE_PATH), e); printErrAndExit( "ERROR: Could not find suitable language plugin for the given exercise " + "path."); } try { JsonWriter.writeObjectIntoJsonFormat(validationResult, paths.get(OUTPUT_PATH)); System.out.println("Codestyle report can be found at " + paths.get(OUTPUT_PATH)); } catch (IOException e) { log.error("Could not write result into {}", paths.get(OUTPUT_PATH), e); printErrAndExit("ERROR: Could not write the results to the given file."); } }
public static void serialize(final boolean[] value, final JsonWriter sw) { if (value == null) { sw.writeNull(); } else if (value.length == 0) { sw.writeAscii("[]"); } else { sw.writeByte(JsonWriter.ARRAY_START); sw.writeAscii(value[0] ? "true" : "false"); for (int i = 1; i < value.length; i++) { sw.writeAscii(value[i] ? ",true" : ",false"); } sw.writeByte(JsonWriter.ARRAY_END); } }
@Override void write(JsonWriter writer) throws IOException { writer.writeObjectOpen(); Iterator<String> namesIterator = names.iterator(); Iterator<JsonValue> valuesIterator = values.iterator(); if (namesIterator.hasNext()) { writer.writeMemberName(namesIterator.next()); writer.writeMemberSeparator(); valuesIterator.next().write(writer); while (namesIterator.hasNext()) { writer.writeObjectSeparator(); writer.writeMemberName(namesIterator.next()); writer.writeMemberSeparator(); valuesIterator.next().write(writer); } } writer.writeObjectClose(); }
public static String formulateJsonForGetOnMultipleKey( Collection<Object> collection, String regionName) throws JSONException { HeapDataOutputStream outputStream = new HeapDataOutputStream(com.gemstone.gemfire.internal.Version.CURRENT); try { JsonGenerator generator = enableDisableJSONGeneratorFeature( getObjectMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8)); generator.writeStartObject(); generator.writeFieldName(regionName); JsonWriter.writeCollectionAsJson(generator, collection); generator.writeEndObject(); generator.close(); return new String(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { outputStream.close(); } }
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException { PrintWriter out = null; try { swiftDao.begin(); // Transaction-per-request final SearchRunFilter searchRunFilter = new SearchRunFilter(); searchRunFilter.setStart("0"); searchRunFilter.setCount("50"); out = resp.getWriter(); final StringBuilder response = new StringBuilder(TYPICAL_RESPONSE_SIZE); response.append("["); final List<SearchRun> searchRuns = swiftDao.getSearchRunList(searchRunFilter); for (int i = 0; i < searchRuns.size(); i++) { final SearchRun searchRun = searchRuns.get(i); final int runningTasks = swiftDao.getNumberRunningTasksForSearchRun(searchRun); JsonWriter.appendSearchRunJson(response, i, searchRun, runningTasks, null, false); if (i + 1 < searchRuns.size()) { response.append(",\n"); } } response.append("]"); out.print(response.toString()); swiftDao.commit(); } catch (Exception e) { swiftDao.rollback(); throw new MprcException("Could not obtain list of search runs", e); } finally { FileUtilities.closeQuietly(out); } }
public void outputWorldStats(File statsFile, String varNamePrefix) { if (statsFile.exists()) statsFile.delete(); System.out.println("Outputting world stats to " + statsFile.getAbsolutePath()); JsonWriter jsWriter = null; try { jsWriter = new JsonWriter(statsFile); jsWriter.startObject(varNamePrefix + "_worldStats"); jsWriter.writeVariable("numChunks", "" + numChunks); jsWriter.writeVariable("numPortals", "" + numPortals); jsWriter.writeVariable("numPlayers", "" + numPlayers); jsWriter.endObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (jsWriter != null) jsWriter.close(); } System.out.println("Outputted world stats"); }
@Override protected void write(JsonWriter writer) throws IOException { writer.write(string); }
public void write(OutputStream out) throws IOException { JsonWriter jsonWriter = new JsonWriter(); jsonWriter.write(this, out); }
public static String toJson(final OperationResult operationResult) { return JsonWriter.writeToString(getJsonObject(operationResult)); }