Java Code Examples for javax.json.Json#createWriter()

The following examples show how to use javax.json.Json#createWriter() . These examples are extracted from open source projects. 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 Project: thorntail   File: JavaxJsonpTest.java    License: 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 2
Source Project: logbook-kai   File: BattleLog.java    License: 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 3
Source Project: cxf   File: JsrJsonpProvider.java    License: 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 4
@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 5
Source Project: AttestationServer   File: AttestationServer.java    License: MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, false, null);
    if (account == null) {
        return;
    }
    final JsonObjectBuilder accountJson = Json.createObjectBuilder();
    accountJson.add("username", account.username);
    accountJson.add("verifyInterval", account.verifyInterval);
    accountJson.add("alertDelay", account.alertDelay);

    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, true);
        final SQLiteStatement select = conn.prepare("SELECT address FROM EmailAddresses " +
                "WHERE userId = ?");
        select.bind(1, account.userId);
        if (select.step()) {
            accountJson.add("email", select.columnString(0));
        }
        select.dispose();
    } finally {
        conn.dispose();
    }

    exchange.getResponseHeaders().set("Content-Type", "application/json");
    exchange.sendResponseHeaders(200, 0);
    try (final OutputStream output = exchange.getResponseBody();
            final JsonWriter writer = Json.createWriter(output)) {
        writer.write(accountJson.build());
    }
}
 
Example 6
Source Project: quarkus   File: ServerDtoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void encode(Dto object, Writer writer) {
    JsonObject jsonObject = Json.createObjectBuilder()
            .add("content", object.getContent())
            .build();
    try (JsonWriter jsonWriter = Json.createWriter(writer)) {
        jsonWriter.writeObject(jsonObject);
    }
}
 
Example 7
String toJson() {
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
    jsonWriter.writeObject(toJsonObject());
    jsonWriter.close();
    return stringWriter.toString();
}
 
Example 8
String toJson() {
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
    jsonWriter.writeObject(this.toJsonObject());
    jsonWriter.close();
    return stringWriter.toString();
}
 
Example 9
String toJson() {
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
    jsonWriter.writeObject(toJsonObject());
    jsonWriter.close();
    return stringWriter.toString();
}
 
Example 10
Source Project: tutorials   File: BookListMessageBodyWriter.java    License: 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 11
public String toJson() {
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
    jsonWriter.writeObject(toJsonObject());
    jsonWriter.close();
    return stringWriter.toString();
}
 
Example 12
Source Project: journaldev   File: EmployeeJSONWriter.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException {

		Employee emp = createEmployee();

		JsonObjectBuilder empBuilder = Json.createObjectBuilder();
		JsonObjectBuilder addressBuilder = Json.createObjectBuilder();
		JsonArrayBuilder phoneNumBuilder = Json.createArrayBuilder();

		for (long phone : emp.getPhoneNumbers()) {
			phoneNumBuilder.add(phone);
		}
		
		addressBuilder.add("street", emp.getAddress().getStreet())
						.add("city", emp.getAddress().getCity())
							.add("zipcode", emp.getAddress().getZipcode());
		
		empBuilder.add("id", emp.getId())
					.add("name", emp.getName())
						.add("permanent", emp.isPermanent())
							.add("role", emp.getRole());
		
		empBuilder.add("phoneNumbers", phoneNumBuilder);
		empBuilder.add("address", addressBuilder);
		
		JsonObject empJsonObject = empBuilder.build();
		
		System.out.println("Employee JSON String\n"+empJsonObject);
		
		//write to file
		OutputStream os = new FileOutputStream("emp.txt");
		JsonWriter jsonWriter = Json.createWriter(os);
		/**
		 * We can get JsonWriter from JsonWriterFactory also
		JsonWriterFactory factory = Json.createWriterFactory(null);
		jsonWriter = factory.createWriter(os);
		*/
		jsonWriter.writeObject(empJsonObject);
		jsonWriter.close();
	}
 
Example 13
Source Project: tutorials   File: BookListMessageBodyWriter.java    License: 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 14
public String asString(JsonObjectBuilder builder) {
  JsonObject jsonObject = builder.build();

  StringWriter eventStringWriter = new StringWriter();
  JsonWriter writer = Json.createWriter(eventStringWriter);
  writer.writeObject(jsonObject);
  writer.close();

  return eventStringWriter.toString();
}
 
Example 15
Source Project: takes   File: RsJson.java    License: 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 16
Source Project: javaee7-websocket   File: BetMessageEncoder.java    License: 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 17
Source Project: javaee7-websocket   File: MatchMessageEncoder.java    License: MIT License 4 votes vote down vote up
@Override
public String encode(MatchMessage m) throws EncodeException {
	StringWriter swriter = new StringWriter();
	try (JsonWriter jsonWrite = Json.createWriter(swriter)) {
		JsonObjectBuilder builder = Json.createObjectBuilder();
		builder.add(
				"match",
				Json.createObjectBuilder()
						.add("serve", m.getMatch().getServe())
						.add("title", m.getMatch().getTitle())
						.add("players",
								Json.createArrayBuilder()
										.add(Json
												.createObjectBuilder()
												.add("name",
														m.getMatch()
																.getPlayerOneName())
												.add("country",
														m.getMatch()
																.getP1Country())
												.add("games",
														m.getMatch()
																.getP1CurrentGame())
												.add("sets",
														m.getMatch()
																.getP1Sets())
												.add("points",
														m.getMatch()
																.getPlayer1Score())
												.add("set1",
														m.getMatch()
																.getP1Set1())
												.add("set2",
														m.getMatch()
																.getP1Set2())
												.add("set3",
														m.getMatch()
																.getP1Set3()))
										.add(Json
												.createObjectBuilder()
												.add("name",
														m.getMatch()
																.getPlayerTwoName())
												.add("games",
														m.getMatch()
																.getP2CurrentGame())
												.add("country",
														m.getMatch()
																.getP2Country())
												.add("sets",
														m.getMatch()
																.getP2Sets())
												.add("points",
														m.getMatch()
																.getPlayer2Score())
												.add("set1",
														m.getMatch()
																.getP2Set1())
												.add("set2",
														m.getMatch()
																.getP2Set2())
												.add("set3",
														m.getMatch()
																.getP2Set3())))
						.add("comments", m.getMatch().getLiveComments())
						.add("finished", m.getMatch().isFinished()));

		jsonWrite.writeObject(builder.build());
	}
	return swriter.toString();
}
 
Example 18
Source Project: fabric-sdk-java   File: HFCAClient.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Generate certificate revocation list.
 *
 * @param registrar     admin user configured in CA-server
 * @param revokedBefore Restrict certificates returned to revoked before this date if not null.
 * @param revokedAfter  Restrict certificates returned to revoked after this date if not null.
 * @param expireBefore  Restrict certificates returned to expired before this date if not null.
 * @param expireAfter   Restrict certificates returned to expired after this date if not null.
 * @throws InvalidArgumentException
 */

public String generateCRL(User registrar, Date revokedBefore, Date revokedAfter, Date expireBefore, Date expireAfter)
        throws InvalidArgumentException, GenerateCRLException {

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    if (registrar == null) {
        throw new InvalidArgumentException("registrar is not set");
    }

    try {
        setUpSSL();

        //---------------------------------------
        JsonObjectBuilder factory = Json.createObjectBuilder();
        if (revokedBefore != null) {
            factory.add("revokedBefore", Util.dateToString(revokedBefore));
        }
        if (revokedAfter != null) {
            factory.add("revokedAfter", Util.dateToString(revokedAfter));
        }
        if (expireBefore != null) {
            factory.add("expireBefore", Util.dateToString(expireBefore));
        }
        if (expireAfter != null) {
            factory.add("expireAfter", Util.dateToString(expireAfter));
        }
        if (caName != null) {
            factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
        }

        JsonObject jsonObject = factory.build();

        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();
        String body = stringWriter.toString();

        //---------------------------------------

        // send revoke request
        JsonObject ret = httpPost(url + HFCA_GENCRL, body, registrar);

        return ret.getString("CRL");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new GenerateCRLException(e.getMessage(), e);
    }
}
 
Example 19
Source Project: tutorials   File: BookMessageBodyWriter.java    License: MIT License 3 votes vote down vote up
/**
 * Marsahl Book to OutputStream
 *
 * @param book
 * @param type
 * @param genericType
 * @param annotations
 * @param mediaType
 * @param httpHeaders
 * @param entityStream
 * @throws IOException
 * @throws WebApplicationException
 */
@Override
public void writeTo(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    JsonWriter jsonWriter = Json.createWriter(entityStream);
    JsonObject jsonObject = BookMapper.map(book);
    jsonWriter.writeObject(jsonObject);
    jsonWriter.close();
}
 
Example 20
Source Project: tutorials   File: BookMessageBodyWriter.java    License: MIT License 3 votes vote down vote up
/**
 * Marsahl Book to OutputStream
 *
 * @param book
 * @param type
 * @param genericType
 * @param annotations
 * @param mediaType
 * @param httpHeaders
 * @param entityStream
 * @throws IOException
 * @throws WebApplicationException
 */
@Override
public void writeTo(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    JsonWriter jsonWriter = Json.createWriter(entityStream);
    JsonObject jsonObject = BookMapper.map(book);
    jsonWriter.writeObject(jsonObject);
    jsonWriter.close();
}