javax.json.Json Java Examples

The following examples show how to use javax.json.Json. 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: PropertiesReader.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Properties readFrom(Class<Properties> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    JsonReader jr = Json.createReader(entityStream);
    JsonObject json = jr.readObject();
    Properties retVal = new Properties();

    json.keySet().forEach(key -> {
        JsonValue value = json.get(key);
        if (!JsonValue.NULL.equals(value)) {
            if (value.getValueType() != JsonValue.ValueType.STRING) {
                throw new IllegalArgumentException(
                        "Non-String JSON prop value found in payload.  Sample data is more than this sample can deal with.  It's not intended to handle any payload.");
            }
            JsonString jstr = (JsonString) value;

            retVal.setProperty(key, jstr.getString());
        }
    });
    return retVal;
}
 
Example #2
Source File: RtNetworksTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * RtNetworks can return its Docker parent.
 */
@Test
public void returnsDocker() {
    MatcherAssert.assertThat(
        new ListedNetworks(
            new AssertRequest(
                new Response(
                    HttpStatus.SC_OK,
                    Json.createArrayBuilder().build().toString()
                )
            ),
            URI.create("http://localhost"),
            DOCKER
        ).docker(),
        new IsEqual<>(DOCKER)
    );
}
 
Example #3
Source File: ProviderInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected raw token claim is as expected")
public void verifyInjectedRawToken() throws Exception {
    Reporter.log("Begin verifyInjectedRawToken\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedRawToken";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.raw_token.name(), token)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #4
Source File: Service.java    From rapid with MIT License 6 votes vote down vote up
@DELETE
@Path("{id}")
public Response deleteService(@PathParam("id") String id) {

    WebTarget target = resource().path("services").path(id);

    Response response = deleteResponse(target);
    try {
        if (response.getStatus() == OK.getStatusCode())
            return Response.ok(Json.createObjectBuilder().add("message", id + " service deleted.").build()).build();
        else
            return Response.status(response.getStatus()).entity(response.readEntity(JsonObject.class)).build();
    } finally {
        response.close();
    }
}
 
Example #5
Source File: JWKxPEMTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void generatePublicKeyFromJWKs() throws Exception {
    String jsonJwk = TokenUtils.readResource("/signer-keyset4k.jwk");
    System.out.printf("jwk: %s\n", jsonJwk);
    JsonObject jwks = Json.createReader(new StringReader(jsonJwk)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject jwk = keys.getJsonObject(0);
    String e = jwk.getString("e");
    String n = jwk.getString("n");

    byte[] ebytes = Base64.getUrlDecoder().decode(e);
    BigInteger publicExponent = new BigInteger(1, ebytes);
    byte[] nbytes = Base64.getUrlDecoder().decode(n);
    BigInteger modulus = new BigInteger(1, nbytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    PublicKey publicKey = kf.generatePublic(rsaPublicKeySpec);
    System.out.printf("publicKey=%s\n", publicKey);
    String pem = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
    System.out.printf("pem: %s\n", pem);
}
 
Example #6
Source File: JaxrsHttpReceiver.java    From sample.microservices.12factorapp with Apache License 2.0 6 votes vote down vote up
@Path("/{name}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response deleteResponse(@PathParam("name") String name) {
    System.out.println("Deleting database called " + name);
    String response;
    try {
        ResponseHandler responseHandler = new ResponseHandler("/" + name);
        response = responseHandler.invoke(RequestType.DELETE);
        return Response.ok("Deleted database " + response).build();
    } catch (Exception e) {
        JsonObject exception = Json.createObjectBuilder().add("Exception", e.getMessage()).build();
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(exception).build();
    }

}
 
Example #7
Source File: Config.java    From rapid with MIT License 6 votes vote down vote up
@DELETE
@Path("{id}")
public Response deleteConfig(@PathParam("id") String configId) {

    WebTarget target = resource().path(CONFIGS).path(configId);
    Response response = deleteResponse(target);

    String entity = response.readEntity(String.class);

    if (entity.isEmpty()) {
        JsonObjectBuilder jsonObject = Json.createObjectBuilder();
        jsonObject.add("id", configId);
        jsonObject.add("message", "the config is deleted.");

        return Response.ok(jsonObject.build()).build();
    }

    try (JsonReader json = Json.createReader(new StringReader(entity))) {
        return Response.status(response.getStatus()).entity(json.read()).build();
    }
}
 
Example #8
Source File: ProviderInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected customDouble claim is as expected")
public void verifyInjectedCustomDouble() throws Exception {
    Reporter.log("Begin verifyInjectedCustomDouble\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomDouble";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", 3.141592653589793)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #9
Source File: ObviousJsonReader.java    From training with MIT License 6 votes vote down vote up
private static List<Map<String, String>> readJsonAsMap() throws FileNotFoundException {
	List<Map<String, String>> mapList = new ArrayList<>();
	
	try (JsonReader jsonReader = Json.createReader(new BufferedReader(new FileReader("big.json")))) {
		// memory leak happens if reading & testing from the same methods
		JsonArray array = jsonReader.readArray();
		for (JsonValue jsonValue : array) {
			JsonObject object= (JsonObject) jsonValue;
			Map<String, String> map = new HashMap<>();
			for (String key: object.keySet()) {
				map.put(key.intern(), object.getString(key));
			}
			mapList.add(map);
		}
	}
	return mapList;
}
 
Example #10
Source File: SchemaBuilder.java    From jaxrs-analyzer with Apache License 2.0 6 votes vote down vote up
private void addObject(final JsonObjectBuilder builder, final TypeIdentifier identifier, final Map<String, TypeIdentifier> properties) {
    final String definition = definitionNameBuilder.buildDefinitionName(identifier.getName(), jsonDefinitions);

    if (jsonDefinitions.containsKey(definition)) {
        builder.add("$ref", "#/definitions/" + definition);
        return;
    }

    // reserve definition
    jsonDefinitions.put(definition, Pair.of(identifier.getName(), Json.createObjectBuilder().build()));

    final JsonObjectBuilder nestedBuilder = Json.createObjectBuilder();

    properties.entrySet().stream().sorted(mapKeyComparator()).forEach(e -> nestedBuilder.add(e.getKey(), build(e.getValue())));
    jsonDefinitions.put(definition, Pair.of(identifier.getName(), Json.createObjectBuilder().add("properties", nestedBuilder).build()));

    builder.add("$ref", "#/definitions/" + definition);
}
 
Example #11
Source File: NetworkConfigTest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private static JsonObject createJsonChannel(JsonArray orderers, JsonObject peers, JsonArray chaincodes) {

        JsonObjectBuilder builder = Json.createObjectBuilder();

        if (orderers != null) {
            builder.add("orderers", orderers);
        }

        if (peers != null) {
            builder.add("peers", peers);
        }

        if (chaincodes != null) {
            builder.add("chaincodes", chaincodes);
        }

        return builder.build();
    }
 
Example #12
Source File: RequiredClaimsUnitTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the token aud claim is as expected
 *
 */
@Test()
public void verifyAudience2() {
    io.restassured.response.Response response = RestAssured.given().auth()
            .oauth2(token)
            .when()
            .queryParam(Claims.aud.name(), "")
            .queryParam(Claims.iss.name(), "https://server.example.com")
            .queryParam(Claims.auth_time.name(), authTimeClaim)
            .get("/endp/verifyOptionalAudience").andReturn();

    Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
    String replyString = response.body().asString();
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Assertions.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #13
Source File: ProviderInjectionEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedIssuer")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedIssuer(@QueryParam("iss") String iss) {
    boolean pass = false;
    String msg;
    String issValue = issuer.get();
    if(issValue == null || issValue.length() == 0) {
        msg = Claims.iss.name()+"value is null or empty, FAIL";
    }
    else if(issValue.equals(iss)) {
        msg = Claims.iss.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.iss.name(), issValue, iss);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example #14
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Histogram with unit=MINUTES,
 * check that the statistics from JsonExporter will be presented in MINUTES.
 */
@Test
public void histogram_json() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("timer1")
            .withType(MetricType.TIMER)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Timer metric = registry.timer(metadata);
    metric.update(Duration.ofHours(1));
    metric.update(Duration.ofHours(2));
    metric.update(Duration.ofHours(3));

    JsonExporter exporter = new JsonExporter();
    String exported = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("timer1")).toString();

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject().getJsonObject("timer1");
    assertEquals(120.0, json.getJsonNumber("p50").doubleValue(), 0.001);
    assertEquals(120.0, json.getJsonNumber("mean").doubleValue(), 0.001);
    assertEquals(60.0, json.getJsonNumber("min").doubleValue(), 0.001);
    assertEquals(180.0, json.getJsonNumber("max").doubleValue(), 0.001);
}
 
Example #15
Source File: JsonValueInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected aud claim is as expected from Token2")
public void verifyInjectedAudience2() throws Exception {
    Reporter.log("Begin verifyInjectedAudience2\n");
    String token2 = TokenUtils.generateTokenString("/Token2.json");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedAudience";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.aud.name(), "s6BhdRkqt3.2")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token2).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #16
Source File: ProviderInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected iat claim is as expected")
public void verifyInjectedIssuedAt() throws Exception {
    Reporter.log("Begin verifyInjectedIssuedAt\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuedAt";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.iat.name(), iatClaim)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #17
Source File: Secret.java    From rapid with MIT License 6 votes vote down vote up
@POST
@Path("{id}/update")
public Response updateSecret(@PathParam("id") String id,
                             @QueryParam("version") String version,
                             JsonObject content) {

    WebTarget target = resource().path("secrets").path(id).path("update").queryParam("version", version);

    Response response = postResponse(target, content);
    String entity = response.readEntity(String.class);

    try {
        if (entity.isEmpty()) {
            return Response.ok(Json.createObjectBuilder().add("message", id + " updated.").build())
                    .build();
        } else {
            return Response.status(response.getStatus())
                    .entity(Json.createReader(new StringReader(entity)).read())
                    .build();
        }
    } finally {
        response.close();
    }
}
 
Example #18
Source File: Data.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get actions
 * 
 * @return all actions from TD file in JsonObject format 
 */
public JsonObject getActions() {
	
	JsonObject actions = null;
	
	if (thingDescription != null) {
		try {
			
			JsonArray actionsArr = thingDescription.getJsonArray("actions");
			actions = Json.createObjectBuilder().add("actions", actionsArr).build();
		
		} catch (JSONException e) {
			
			logger.info("There are no actions in TD for object: " + objectId);
		}
	} 
	return actions;
}
 
Example #19
Source File: ClaimValueInjectionEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedIssuedAtStandard")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedIssuedAtStandard(@QueryParam("iat") Long iat) {
    boolean pass = false;
    String msg;
    // iat
    Long iatValue = issuedAtStandard.getValue();
    if(iatValue == null || iatValue.intValue() == 0) {
        msg = Claims.iat.name()+"value is null or empty, FAIL";
    }
    else if(iatValue.equals(iat)) {
        msg = Claims.iat.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.iat.name(), iatValue, iat);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example #20
Source File: OrchestratorResourceMockTest.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
private String buildGroupResponseObject(String name, String[] members, String[] occasions) {
  JsonObjectBuilder group = Json.createObjectBuilder();
  group.add(JSON_KEY_GROUP_NAME, name);

  JsonArrayBuilder membersArray = Json.createArrayBuilder();
  for (int i = 0; i < members.length; i++) {
    membersArray.add(members[i]);
  }
  group.add(JSON_KEY_MEMBERS_LIST, membersArray.build());

  JsonArrayBuilder occasionsArray = Json.createArrayBuilder();
  for (int i = 0; i < occasions.length; i++) {
    occasionsArray.add(occasions[i]);
  }
  group.add(JSON_KEY_OCCASIONS_LIST, occasionsArray.build());

  return group.build().toString();
}
 
Example #21
Source File: JsonValuejectionEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedCustomString")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedCustomString(@QueryParam("value") String value) {
    boolean pass = false;
    String msg;
    // iat
    String customValue = customString.getString();
    if(customValue == null || customValue.length() == 0) {
        msg = "customString value is null or empty, FAIL";
    }
    else if(customValue.equals(value)) {
        msg = "customString PASS";
        pass = true;
    }
    else {
        msg = String.format("customString: %s != %s", customValue, value);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example #22
Source File: Message.java    From sample-room-java with Apache License 2.0 6 votes vote down vote up
/**
 * Content is a simple string containing the chat message.
 * @return constructed message
 */
public static Message createChatMessage(String username, String message) {
    //  player,*,{...}
    //  {
    //    "type": "chat",
    //    "username": "username",
    //    "content": "<message>",
    //    "bookmark": "String representing last message seen"
    //  }

    JsonObjectBuilder payload = Json.createObjectBuilder();
    payload.add(TYPE, "chat");
    payload.add(USERNAME, username);
    payload.add(CONTENT, message);

    payload.add(BOOKMARK, PREFIX + bookmark.incrementAndGet());
    return new Message(Target.player, ALL, payload.build().toString());
}
 
Example #23
Source File: RtContainerTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * RtContainer can wait with no problem.
 * @throws Exception If something goes wrong.
 */
@Test
public void waitsOk() throws Exception {
    int retval = new RtContainer(
        Json.createObjectBuilder().add("Id", "123").build(),
        new AssertRequest(
            new Response(
                HttpStatus.SC_OK,
                Json.createObjectBuilder()
                    .add("StatusCode", 0)
                    .build().toString()
            ),
            new Condition(
                "Method should be a POST",
                req -> req.getRequestLine().getMethod().equals("POST")
            ),
        new Condition(
            "Resource path must be /123/wait",
            req ->  req.getRequestLine().getUri().endsWith("/wait")
        )
        ),
        URI.create("http://localhost:80/1.30/containers/123"),
        Mockito.mock(Docker.class)
    ).waitOn(null);
    assertEquals(0, retval);
}
 
Example #24
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
 public void testConnectionStatusWithNullValues() throws IOException, InitializationException {
     final ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 1, 0);

     final Map<PropertyDescriptor, String> properties = new HashMap<>();
     properties.put(SiteToSiteUtils.BATCH_SIZE, "4");
     properties.put(SiteToSiteStatusReportingTask.COMPONENT_NAME_FILTER_REGEX, "Awesome.*");
     properties.put(SiteToSiteStatusReportingTask.COMPONENT_TYPE_FILTER_REGEX, "(Connection)");
     properties.put(SiteToSiteStatusReportingTask.ALLOW_NULL_VALUES,"true");

     MockSiteToSiteStatusReportingTask task = initTask(properties, pgStatus);
     task.onTrigger(context);

     final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
     JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
     JsonObject object = jsonReader.readArray().getJsonObject(0);
     JsonValue destination = object.get("destinationName");
     assertEquals(destination, JsonValue.NULL);

}
 
Example #25
Source File: PiwikJsonArray.java    From matomo-java-tracker with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns a JSON encoded array string representing this object.
 * @return returns the current array as a JSON encode string
 */
@Override
public String toString(){
    JsonArrayBuilder ab = Json.createArrayBuilder();
    
    for (int x = 0; x < list.size(); ++x){
        JsonValue value = list.get(x);
        if (value instanceof EcommerceItem){
            ab.add(((EcommerceItem)value).toJsonArray());
        }
        else{
            ab.add(value);
        }
    }
    
    return ab.build().toString();
}
 
Example #26
Source File: LoginApp.java    From OrionAlpha with GNU General Public License v3.0 6 votes vote down vote up
private void initializeDB() {
    try (JsonReader reader = Json.createReader(new FileReader("Database.img"))) {
        JsonObject dbData = reader.readObject();
        
        int dbPort = dbData.getInt("dbPort", 3306);
        String dbName = dbData.getString("dbGameWorld", "orionalpha");
        String dbSource = dbData.getString("dbGameWorldSource", "127.0.0.1");
        String[] dbInfo = dbData.getString("dbGameWorldInfo", "root,").split(",");
        
        // Construct the instance of the Database
        Database.createInstance(dbName, dbSource, dbInfo[0], dbInfo.length == 1 ? "" : dbInfo[1], dbPort);
        
        // Load the initial instance of the Database
        Database.getDB().load();
        
        Logger.logReport("DB configuration parsed successfully");
    } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.err);
    }
}
 
Example #27
Source File: ResourceProcessor.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JsonReaderFactory jsonReaderFactory = Json.createReaderFactory(null);
    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(null);
    JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);

    File dir = new File("src/main/resources/hl7/fhir/us/davinci-pdex-plan-net/package/");
    for (File file : dir.listFiles()) {
        String fileName = file.getName();
        if (!fileName.endsWith(".json") || file.isDirectory()) {
            continue;
        }
        JsonObject jsonObject = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            JsonReader jsonReader = jsonReaderFactory.createReader(reader);
            jsonObject = jsonReader.readObject();

            JsonObjectBuilder jsonObjectBuilder = jsonBuilderFactory.createObjectBuilder(jsonObject);

            JsonObject text = jsonObject.getJsonObject("text");
            if (text != null) {
                JsonObjectBuilder textBuilder = jsonBuilderFactory.createObjectBuilder(text);
                String div = text.getString("div");
                div = div.replace("<p><pre>", "<pre>").replace("</pre></p>", "</pre>");
                textBuilder.add("div", div);
                jsonObjectBuilder.add("text", textBuilder);
            }

            if (!jsonObject.containsKey("version")) {
                System.out.println("file: " + file + " does not have a version");
                jsonObjectBuilder.add("version", "0.1.0");
            }

            jsonObject = jsonObjectBuilder.build();
        }
        try (FileWriter writer = new FileWriter(file)) {
            JsonWriter jsonWriter = jsonWriterFactory.createWriter(writer);
            jsonWriter.write(jsonObject);
        }
    }
}
 
Example #28
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private RobotType[] getAllTypes(SpanContext parent) {
	List<RobotType> types = new ArrayList<RobotType>();
	String result = doGeneralGetCall(urlFactory + "/robottypes", parent, References.CHILD_OF);
	JsonReader reader = Json.createReader(new StringReader(result));
	JsonArray array = reader.readArray();
	for (JsonValue jsonValue : array) {
		types.add(RobotType.fromJSon(jsonValue.asJsonObject()));
	}
	return types.toArray(new RobotType[0]);
}
 
Example #29
Source File: Common.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static JsonObject createRegistrationResponse(String clientdata, String regdata)
        throws UnsupportedEncodingException {
    JsonObject jo = Json.createObjectBuilder()
            .add(Constants.JSON_KEY_CLIENTDATA_LABEL, org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(clientdata.getBytes("UTF-8")))
            //                .add(Constants.JSON_KEY_SESSIONID_LABEL, sessionid)
            .add(Constants.JSON_KEY_REGISTRATIONDATA_LABEL, regdata)
            .build();
    return jo;
}
 
Example #30
Source File: ReturnWithAllClientHeadersFilter.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext clientRequestContext) throws IOException {
    JsonObjectBuilder allClientHeaders = Json.createObjectBuilder();
    MultivaluedMap<String, Object> clientHeaders = clientRequestContext.getHeaders();
    for (String headerName : clientHeaders.keySet()) {
        allClientHeaders.add(headerName, clientHeaders.getFirst(headerName).toString());
    }
    clientRequestContext.abortWith(Response.ok(allClientHeaders.build()).build());

}