javax.json.JsonWriter Java Examples

The following examples show how to use javax.json.JsonWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 8 votes vote down vote up
String toJson(JsonObject toJsonFunc) {
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
    jsonWriter.writeObject(toJsonFunc);
    jsonWriter.close();
    return stringWriter.toString();
}
 
Example #2
Source File: JavaxJsonpTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void testJavaxJsonp() throws IOException {
    JsonObject jsonOut = Json.createObjectBuilder()
            .add("greeting", "hi")
            .build();
    StringWriter stringWriter = new StringWriter(); 
    JsonWriter jsonWriter = Json.createWriter(stringWriter);
    jsonWriter.writeObject(jsonOut);

    String response = Request.Post("http://localhost:8080/jsonp").body(new StringEntity(stringWriter.toString()))
        .execute().returnContent().asString().trim();
    JsonReader jsonReader = Json.createReader(new StringReader(response));
    JsonObject jsonIn = jsonReader.readObject();

    assertThat(jsonIn.getString("greeting")).isEqualTo("hi");
    assertThat(jsonIn.getString("fromServlet")).isEqualTo("true");
}
 
Example #3
Source File: FHIRJsonPatchProvider.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(JsonArray t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    log.entering(this.getClass().getName(), "writeTo");
    try (JsonWriter writer = JSON_WRITER_FACTORY.createWriter(nonClosingOutputStream(entityStream))) {
        writer.writeArray(t);
    } catch (JsonException e) {
        // log the error but don't throw because that seems to block to original IOException from bubbling for some reason
        log.log(Level.WARNING, "an error occurred during JSON Patch serialization", e);
        if (RuntimeType.SERVER.equals(runtimeType)) {
            String acceptHeader = (String) httpHeaders.getFirst(HttpHeaders.ACCEPT);
            Response response = buildResponse(
                buildOperationOutcome(Collections.singletonList(
                    buildOperationOutcomeIssue(IssueSeverity.FATAL, IssueType.EXCEPTION, "FHIRProvider: " + e.getMessage(), null))), getMediaType(acceptHeader));
            throw new WebApplicationException(response);
        }
    } finally {
        log.exiting(this.getClass().getName(), "writeTo");
    }
}
 
Example #4
Source File: FHIRJsonProvider.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(JsonObject t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    log.entering(this.getClass().getName(), "writeTo");
    try (JsonWriter writer = JSON_WRITER_FACTORY.createWriter(nonClosingOutputStream(entityStream))) {
        writer.writeObject(t);
    } catch (JsonException e) {
        // log the error but don't throw because that seems to block to original IOException from bubbling for some reason
        log.log(Level.WARNING, "an error occurred during resource serialization", e);
        if (RuntimeType.SERVER.equals(runtimeType)) {
            Response response = buildResponse(
                buildOperationOutcome(Collections.singletonList(
                    buildOperationOutcomeIssue(IssueSeverity.FATAL, IssueType.EXCEPTION, "FHIRProvider: " + e.getMessage(), null))), mediaType);
            throw new WebApplicationException(response);
        }
    } finally {
        log.exiting(this.getClass().getName(), "writeTo");
    }
}
 
Example #5
Source File: BattleLog.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * ローデータを設定する
 *
 * @param log 戦闘ログ
 * @param consumer setter
 * @param json 設定するjson
 * @param req リクエスト
 */
@SuppressWarnings("unchecked")
public static void setRawData(BattleLog log, BiConsumer<RawData, ApiData> consumer,
        JsonObject json, RequestMetaData req) {
    RawData rawData = log.getRaw();
    if (rawData == null) {
        rawData = new RawData();
        log.setRaw(rawData);
    }
    ObjectMapper mapper = new ObjectMapper();
    StringWriter sw = new StringWriter(1024 * 4);
    try (JsonWriter jw = Json.createWriter(sw)) {
        jw.writeObject(json);
    }
    try {
        ApiData data = new ApiData();
        data.setUri(req.getRequestURI());
        data.setApidata(mapper.readValue(sw.toString(), Map.class));

        consumer.accept(rawData, data);
    } catch (Exception e) {
        LoggerHolder.get().warn("ローデータの設定に失敗しました", e);
    }
}
 
Example #6
Source File: TargetDirectoryJsonStructureWriter.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private File writeStructure(final File targetDir, final String directory,
		final String fileName, JsonStructure structure) throws IOException {
	Validate.notNull(fileName);

	final File dir = new File(targetDir, directory);
	dir.mkdirs();
	final File file = new File(dir, fileName);
	final FileWriter fileWriter = new FileWriter(file);
	try {
		final JsonWriter jsonWriter = provider.createWriterFactory(
				Collections.singletonMap(JsonGenerator.PRETTY_PRINTING,
						Boolean.TRUE)).createWriter(fileWriter);
		jsonWriter.write(structure);

	} finally {
		try {
			fileWriter.close();
		} catch (IOException ignored) {
		}
	}
	return file;
}
 
Example #7
Source File: HttpHeaderStatisticInjector.java    From porcupine with Apache License 2.0 6 votes vote down vote up
public String serializeStatistics(Statistics statistics) {
    JsonObjectBuilder stats = Json.createObjectBuilder();
    stats.add("pipelineName", statistics.getPipelineName());
    final String handlerName = statistics.getRejectedExecutionHandlerName();
    if (handlerName != null) {
        stats.add("rejectedExecutionHandlerName", handlerName);
    }
    stats.add("activeThreadCount", statistics.getActiveThreadCount());
    stats.add("completedTaskCount", statistics.getCompletedTaskCount());
    stats.add("corePoolSize", statistics.getCorePoolSize());
    stats.add("currentThreadPoolSize", statistics.getCurrentThreadPoolSize());
    stats.add("largestThreadPoolSize", statistics.getLargestThreadPoolSize());
    stats.add("maximumPoolSize", statistics.getMaximumPoolSize());
    stats.add("rejectedTasks", statistics.getRejectedTasks());
    stats.add("remainingQueueCapacity", statistics.getRemainingQueueCapacity());
    stats.add("minQueueCapacity", statistics.getMinQueueCapacity());
    stats.add("totalNumberOfTasks", statistics.getTotalNumberOfTasks());
    StringWriter writer = new StringWriter();
    try (JsonWriter outputWriter = Json.createWriter(writer)) {
        outputWriter.writeObject(stats.build());
    }
    return writer.toString();
}
 
Example #8
Source File: JsonUtil.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Create a JSON string.
 * @param structure the structure JsonAoject or JsonArray
 * @param pretty for pretty print
 * @return the JSON string
 */
public static String toJson(JsonStructure structure, boolean pretty) {
  JsonWriter writer  = null;
  StringWriter result = new StringWriter();
  try {
    Map<String, Object> props = new HashMap<String,Object>();
    if (pretty) props.put(JsonGenerator.PRETTY_PRINTING,true);
    JsonWriterFactory factory = Json.createWriterFactory(props);
    writer = factory.createWriter(result);
    writer.write(structure); 
  } finally {
    try {
      if (writer != null) writer.close();
    } catch (Throwable t) {
      t.printStackTrace(System.err);
    }
  }
  return result.toString().trim();
}
 
Example #9
Source File: RsPrettyJson.java    From takes with MIT License 6 votes vote down vote up
/**
 * Format body with proper indents.
 * @param body Response body
 * @return New properly formatted body
 * @throws IOException If fails
 */
private static byte[] transform(final InputStream body) throws IOException {
    final ByteArrayOutputStream res = new ByteArrayOutputStream();
    try (JsonReader rdr = Json.createReader(body)) {
        final JsonObject obj = rdr.readObject();
        try (JsonWriter wrt = Json.createWriterFactory(
            Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true)
            )
            .createWriter(res)
        ) {
            wrt.writeObject(obj);
        }
    } catch (final JsonException ex) {
        throw new IOException(ex);
    }
    return res.toByteArray();
}
 
Example #10
Source File: ApiStart2.java    From logbook-kai with MIT License 5 votes vote down vote up
/**
 * store
 * 
 * @param obj api_data
 */
private void store(JsonObject root) {
    if (AppConfig.get().isStoreApiStart2()) {
        try {
            String dir = AppConfig.get().getStoreApiStart2Dir();
            if (dir == null || "".equals(dir))
                return;

            Path dirPath = Paths.get(dir);
            Path parent = dirPath.getParent();
            if (parent != null && !Files.exists(parent)) {
                Files.createDirectories(parent);
            }

            JsonWriterFactory factory = Json
                    .createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
            for (Entry<String, JsonValue> entry : root.entrySet()) {
                String key = entry.getKey();
                JsonValue val = entry.getValue();
                JsonObject obj = Json.createObjectBuilder().add(key, val).build();

                Path outPath = dirPath.resolve(key + ".json");

                try (OutputStream out = Files.newOutputStream(outPath)) {
                    try (JsonWriter writer = factory.createWriter(out)) {
                        writer.write(obj);
                    }
                }
            }
        } catch (Exception e) {
            LoggerHolder.get().warn("api_start2の保存に失敗しました", e);
        }
    }
}
 
Example #11
Source File: BookListMessageBodyWriter.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void writeTo(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    JsonWriter jsonWriter = Json.createWriter(entityStream);
    JsonArray jsonArray = BookMapper.map(books);
    jsonWriter.writeArray(jsonArray);
    jsonWriter.close();
}
 
Example #12
Source File: JsonMergePatchHttpMessageConverter.java    From http-patch-spring with MIT License 5 votes vote down vote up
@Override
protected void writeInternal(JsonMergePatch jsonMergePatch, HttpOutputMessage outputMessage)
        throws HttpMessageNotWritableException {

    try (JsonWriter writer = Json.createWriter(outputMessage.getBody())) {
        writer.write(jsonMergePatch.toJsonValue());
    } catch (Exception e) {
        throw new HttpMessageNotWritableException(e.getMessage(), e);
    }
}
 
Example #13
Source File: CodeModelJsonStructureWriter.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private JTextFile createTextFile(String fileName,
		JsonStructure jsonStructure) throws IOException {
	Validate.notNull(fileName);
	final JTextFile textFile = new JTextFile(fileName);
	final StringWriter stringWriter = new StringWriter();
	final JsonWriter jsonWriter = provider.createWriterFactory(
			Collections.singletonMap(JsonGenerator.PRETTY_PRINTING,
					Boolean.TRUE)).createWriter(stringWriter);
	jsonWriter.write(jsonStructure);
	textFile.setContents(stringWriter.toString());
	return textFile;
}
 
Example #14
Source File: JsrJsonpProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(JsonStructure t, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
    throws IOException, WebApplicationException {

    if (entityStream == null) {
        throw new IOException("Initialized OutputStream should be provided");
    }

    try (JsonWriter writer = Json.createWriter(entityStream)) {
        writer.write(t);
    }
}
 
Example #15
Source File: ConfigurationBase.java    From AsciidocFX with Apache License 2.0 5 votes vote down vote up
protected void saveJson(JsonStructure jsonStructure) {
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);

    try (FileOutputStream fos = new FileOutputStream(getConfigPath().toFile());
         OutputStreamWriter fileWriter = new OutputStreamWriter(fos, "UTF-8");
         JsonWriter jsonWriter = Json.createWriterFactory(properties).createWriter(fileWriter);) {
        jsonWriter.write(jsonStructure);
    } catch (Exception e) {
        logger.error("Problem occured while saving {}", this.getClass().getSimpleName(), e);
    }
}
 
Example #16
Source File: Util.java    From jcypher with Apache License 2.0 5 votes vote down vote up
/**
 * write a JsonObject formatted in a pretty way into a String
 * @param jsonObject
 * @return a String containing the JSON
 */
public static String writePretty(JsonObject jsonObject) {
	JsonWriterFactory factory = createPrettyWriterFactory();
	StringWriter sw = new StringWriter();
	JsonWriter writer = factory.createWriter(sw);
	writer.writeObject(jsonObject);
	String ret = sw.toString();
	writer.close();
	return ret;
}
 
Example #17
Source File: ApiListenerServlet.java    From iaf with Apache License 2.0 5 votes vote down vote up
public void returnJson(HttpServletResponse response, int status, JsonObject json) throws IOException {
	response.setStatus(status);
	Map<String, Boolean> config = new HashMap<>();
	config.put(JsonGenerator.PRETTY_PRINTING, true);
	JsonWriterFactory factory = Json.createWriterFactory(config);
	try (JsonWriter jsonWriter = factory.createWriter(response.getOutputStream(), Charset.forName("UTF-8"))) {
		jsonWriter.write(json);
	}
}
 
Example #18
Source File: BetMessageEncoder.java    From javaee7-websocket with MIT License 5 votes vote down vote up
@Override
public String encode(BetMessage betMsg) throws EncodeException {
	StringWriter swriter = new StringWriter();
	try (JsonWriter jsonWrite = Json.createWriter(swriter)) {
		JsonObjectBuilder builder = Json.createObjectBuilder();
		builder.add("winner",
				betMsg.getWinner()).add("nbBets", betMsg.getNbBets())
		.add("result", betMsg.getResult());
		jsonWrite.writeObject(builder.build());
	}
	return swriter.toString();
}
 
Example #19
Source File: RsJson.java    From takes with MIT License 5 votes vote down vote up
/**
 * Print JSON.
 * @param src Source
 * @return JSON
 * @throws IOException If fails
 */
private static byte[] print(final RsJson.Source src) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (JsonWriter writer = Json.createWriter(baos)) {
        writer.write(src.toJson());
    }
    return baos.toByteArray();
}
 
Example #20
Source File: RequestTestDefWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given request cases in the form of a JSON document.
 */
public void write( RequestTestDef requestTestDef)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( RequestCaseJson.toJson( requestTestDef));
  }
 
Example #21
Source File: MocoTestConfigWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given request cases in the form of a JSON document.
 */
public void write( MocoTestConfig mocoTestConfig)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( MocoTestConfigJson.toJson( mocoTestConfig));
  }
 
Example #22
Source File: MocoServerConfigWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( RequestTestDef requestCases)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  try
    {
    jsonWriter.write( expectedConfigs( requestCases));
    }
  catch( Exception e)
    {
    throw new RequestCaseException( String.format( "Can't write Moco server configuration for %s", requestCases), e);
    }
  }
 
Example #23
Source File: SystemTestJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( SystemTestDef systemTest)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( SystemTestJson.toJson( systemTest));
  }
 
Example #24
Source File: BookListMessageBodyWriter.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void writeTo(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    JsonWriter jsonWriter = Json.createWriter(entityStream);
    JsonArray jsonArray = BookMapper.map(books);
    jsonWriter.writeArray(jsonArray);
    jsonWriter.close();
}
 
Example #25
Source File: ProjectJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given project definition the form of a JSON document.
 */
public void write( Project project)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( ProjectJson.toJson( project));
  }
 
Example #26
Source File: SystemInputJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( SystemInputDef systemInput)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( SystemInputJson.toJson( systemInput));
  }
 
Example #27
Source File: GeneratorSetJsonWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Writes the given system test definition the form of a JSON document.
 */
public void write( IGeneratorSet generatorSet)
  {
  JsonWriterFactory writerFactory = Json.createWriterFactory( MapBuilder.of( PRETTY_PRINTING, true).build());
  JsonWriter jsonWriter = writerFactory.createWriter( getWriter());

  jsonWriter.write( GeneratorSetJson.toJson( generatorSet));
  }
 
Example #28
Source File: EventHandler.java    From flowing-retail-old with Apache License 2.0 5 votes vote down vote up
public String asString(JsonObject jsonObject) {
  StringWriter eventStringWriter = new StringWriter();
  JsonWriter writer = Json.createWriter(eventStringWriter);
  writer.writeObject(jsonObject);
  writer.close();

  return eventStringWriter.toString();
}
 
Example #29
Source File: TestXmlSchema2JsonSchema.java    From iaf with Apache License 2.0 5 votes vote down vote up
private String jsonPrettyPrint(String json) {
	StringWriter sw = new StringWriter();
	JsonReader jr = Json.createReader(new StringReader(json));
	JsonObject jobj = jr.readObject();

	Map<String, Object> properties = new HashMap<>(1);
	properties.put(JsonGenerator.PRETTY_PRINTING, true);

	JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
	try (JsonWriter jsonWriter = writerFactory.createWriter(sw)) {
		jsonWriter.writeObject(jobj);
	}

	return sw.toString().trim();
}
 
Example #30
Source File: JVTypeFileFormat.java    From diirt with MIT License 5 votes vote down vote up
@Override
public void writeValue(Object value, OutputStream out) {
    try (JsonWriter writer = Json.createWriter(out)) {
        writer.writeObject(VTypeToJson.toJson((VType) value));
    } catch (RuntimeException e) {
        throw e;
    }
}