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

The following examples show how to use javax.json.Json#createReader() . 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: rapid   File: Config.java    License: MIT License 6 votes vote down vote up
@GET
public Response listConfigs(@QueryParam("filters") String filters) throws UnsupportedEncodingException {

    WebTarget target = resource().path(CONFIGS);

    if (Objects.nonNull(filters))
        target = target.queryParam("filters", URLEncoder.encode(filters, "UTF-8"));

    Response response = getResponse(target);
    String raw = response.readEntity(String.class);

    try (JsonReader json = Json.createReader(new StringReader(raw))) {
        return Response.status(response.getStatus())
                .entity(json.read())
                .build();
    } finally {
        response.close();
    }
}
 
Example 2
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected aud claim using @Claim(standard) is as expected")
public void verifyInjectedAudienceStandard() throws Exception {
    Reporter.log("Begin verifyInjectedAudienceStandard\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedAudienceStandard";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.aud.name(), "s6BhdRkqt3")
        .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();
    System.out.println(reply);
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 3
Source Project: eplmp   File: AuthResource.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private String getSigningKeys(String url) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    JsonReader jsonReader = null;

    try {
        com.squareup.okhttp.Response response = client.newCall(request).execute();
        jsonReader = Json.createReader(new StringReader(response.body().string()));
        JsonObject object = jsonReader.readObject();
        JsonArray keys = object.getJsonArray("keys");
        return keys.toString();
    } catch (IOException | JsonParsingException e) {
        LOGGER.log(Level.SEVERE, null, e);
        return null;
    } finally {
        if (jsonReader != null) {
            jsonReader.close();
        }
    }
}
 
Example 4
/**
 * Called from Gluon CloudLink when a new object is added to a list. This implementation will add the object in the
 * database.
 *
 * @param listIdentifier the identifier of the list where the object is added to
 * @param objectIdentifier the identifier of the object that is added
 * @param payload the raw JSON payload of the object that is added
 * @return an empty response, as the response is ignored by Gluon CloudLink
 */
@POST
@Path("/add/{objectIdentifier}")
@Consumes(MediaType.APPLICATION_JSON + "; " + CHARSET)
@Produces(MediaType.APPLICATION_JSON + "; " + CHARSET)
public String addItem(@PathParam("listIdentifier") String listIdentifier,
                      @PathParam("objectIdentifier") String objectIdentifier,
                      String payload) {
    LOG.log(Level.INFO, "Added item with id " + objectIdentifier + " to list " + listIdentifier + ": " + payload);
    try (JsonReader jsonReader = Json.createReader(new StringReader(payload))) {
        JsonObject jsonObject = jsonReader.readObject();
        String title = jsonObject.containsKey("title") ? jsonObject.getString("title") : "";
        String text = jsonObject.containsKey("text") ? jsonObject.getString("text") : "";
        long creationDate = jsonObject.containsKey("creationDate") ? jsonObject.getJsonNumber("creationDate").longValue() : LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        noteService.create(objectIdentifier, title, text, creationDate);
        jsonObject.getString("title");
    }
    return "{}";
}
 
Example 5
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected jti claim is as expected")
public void verifyInjectedJTI() throws Exception {
    Reporter.log("Begin verifyInjectedJTI\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedJTI";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.jti.name(), "a-123")
        .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 6
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected sub claim is as expected")
public void verifyInjectedOptionalSubject() throws Exception {
    Reporter.log("Begin verifyInjectedOptionalSubject\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedOptionalSubject";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.sub.name(), "24400320")
        .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 7
Source Project: quarkus   File: RequiredClaimsUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the token iat claim is as expected
 *
 */
@Test()
public void verifyIssuedAt() {
    io.restassured.response.Response response = RestAssured.given().auth()
            .oauth2(token)
            .when()
            .queryParam(Claims.iat.name(), iatClaim)
            .queryParam(Claims.iss.name(), "https://server.example.com")
            .queryParam(Claims.auth_time.name(), authTimeClaim)
            .get("/endp/verifyIssuedAt").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 8
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
    description = "Validate that the embedded PEM key is used to sign the JWT")
public void testKeyAsPEM() throws Exception {
    Reporter.log("testKeyAsPEM, expect HTTP_OK");

    PrivateKey privateKey = TokenUtils.readECPrivateKey("/ecPrivateKey.pem");
    String kid = "/ecPrivateKey.pem";
    String token = TokenUtils.signClaims(privateKey, kid, "/Token1.json");

    String uri = baseURL.toExternalForm() + "endp/verifyKeyAsPEM";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        ;
    Response response = echoEndpointTarget.request(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
@Override
protected JsonMergePatch readInternal(Class<? extends JsonMergePatch> clazz, HttpInputMessage inputMessage)
        throws HttpMessageNotReadableException {

    try (JsonReader reader = Json.createReader(inputMessage.getBody())) {
        return Json.createMergePatch(reader.readValue());
    } catch (Exception e) {
        throw new HttpMessageNotReadableException(e.getMessage(), inputMessage);
    }
}
 
Example 10
Source Project: structlog4j   File: JsonTestUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Ensures message is valid JSON
 */
public void assertJsonMessage(List<LogEntry> entries, int entryIndex) {
    try {
        JsonReader reader = Json.createReader(new StringReader(entries.get(entryIndex).getMessage()));
        JsonStructure parsed = reader.read();
    } catch (Exception e) {
        throw new RuntimeException("Unable to parse: " + entries.get(entryIndex).getMessage(),e);
    }
}
 
Example 11
@RunAsClient
@Test(groups = TEST_GROUP_JAXRS,
      description = "Validate that an empty JWT in injected in the endpoint")
public void emptyToken() {
    String uri = baseURL.toExternalForm() + "endp/verifyEmptyToken";
    WebTarget echoEndpointTarget = ClientBuilder.newClient().target(uri);
    Response response = echoEndpointTarget.request(TEXT_PLAIN).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();
    Assert.assertTrue(reply.getBoolean("pass"));
}
 
Example 12
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 13
Source Project: eplmp   File: JWTokenFactory.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static JWTokenUserGroupMapping validateAuthToken(Key key, String jwt) {

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setVerificationKey(key)
                .setRelaxVerificationKeyValidation()
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
            String subject = jwtClaims.getSubject();

            try (JsonReader reader = Json.createReader(new StringReader(subject))) {
                JsonObject subjectObject = reader.readObject(); // JsonParsingException
                String login = subjectObject.getString(SUBJECT_LOGIN); // Npe
                String groupName = subjectObject.getString(SUBJECT_GROUP_NAME); // Npe

                if (login != null && !login.isEmpty() && groupName != null && !groupName.isEmpty()) {
                    return new JWTokenUserGroupMapping(jwtClaims, new UserGroupMapping(login, groupName));
                }
            }


        } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
            LOGGER.log(Level.FINE, "Cannot validate jwt token", e);
        }

        return null;

    }
 
Example 14
Source Project: karaf-decanter   File: JsonUnmarshaller.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> unmarshal(InputStream in) {
    JsonReader reader = Json.createReader(in);
    JsonObject jsonO = reader.readObject();
    HashMap<String, Object> map = new HashMap<>();
    for (String key : jsonO.keySet()) {
        map.put(key, unmarshalAttribute(jsonO.get(key)));
    }
    reader.close();
    return map;
}
 
Example 15
Source Project: BioSolr   File: HttpConnection.java    License: Apache License 2.0 5 votes vote down vote up
public JsonStructure getJson() throws IOException {
  http.setRequestMethod("GET");
  http.setRequestProperty("Accept", "application/json");
  try (InputStream in = http.getInputStream();
       JsonReader reader = Json.createReader(in)) {
    return reader.read();
  }
}
 
Example 16
Source Project: flowing-retail-old   File: EventHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void handleEvent(String eventAsJson) {
  JsonReader jsonReader = Json.createReader(new StringReader(eventAsJson));
  JsonObject event = jsonReader.readObject();
  jsonReader.close();

  String type = event.getString("type");
  String name = event.getString("name");
  
  String transactionId = null;
  if (event.containsKey("transactionId")) {
    transactionId = event.getString("transactionId");
  }

  System.out.println("[" + this.getClass().getSimpleName() + "] Received: " + type + " " + name);
  try {
    
    boolean handled = handleEvent(type, name, transactionId, event);
    if (handled) {
      System.out.println("[" + this.getClass().getSimpleName() + "] Handled: " + type + " " + name + " " + eventAsJson);
    }else {
      System.out.println("[" + this.getClass().getSimpleName() + "] Ignored " + type + " " + name + " " + eventAsJson);
    }
    
  } catch (Exception ex) {
    System.out.println(ex.getClass() + " '" + ex.getMessage() + "' while handling: " + eventAsJson);
    ex.printStackTrace();
  }    
}
 
Example 17
Source Project: javametrics   File: Metrics.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void processData(List<String> jsaonData) {
    for (Iterator<String> iterator = jsaonData.iterator(); iterator.hasNext();) {
        String jsonStr = iterator.next();
        JsonReader jsonReader = Json.createReader(new StringReader(jsonStr));
        try {
            JsonObject jsonObject = jsonReader.readObject();
            String topicName = jsonObject.getString("topic", null);
            switch (topicName) {
            case "http":
                handleHttpTopic(jsonObject.getJsonObject("payload"));
                break;
            case "cpu":
                JsonNumber system = jsonObject.getJsonObject("payload").getJsonNumber("system");
                JsonNumber process = jsonObject.getJsonObject("payload").getJsonNumber("process");

                os_cpu_used_ratio.set(Double.valueOf(system.doubleValue()));
                process_cpu_used_ratio.set(Double.valueOf(process.doubleValue()));
                break;
            default:
                break;
            }
        } catch (JsonException je) {
            // Skip this object, log the exception and keep trying with
            // the rest of the list
            // System.err.println("Error in json: \n" + jsonStr);
            // je.printStackTrace();
        }
    }
}
 
Example 18
Source Project: sample-acmegifts   File: Group.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static JsonObject stringToJsonObj(String input) {
  try {
    JsonReader jsonReader = Json.createReader(new StringReader(input));
    JsonObject output = jsonReader.readObject();
    jsonReader.close();
    return output;
  } catch (JsonParsingException e) {
    return null;
  }
}
 
Example 19
/**
 * 
 * @param title
 * @return
 * @throws IOException 
 */
void findPages( String title, java.util.function.Consumer<JsonArray> success ) throws IOException {

    final String credential = Credentials.basic("admin", "admin");

    final HttpUrl url =   new HttpUrl.Builder()
                                .scheme(SCHEME)
                                .host(HOST)
                                .port(PORT)
                                .addPathSegments("rest/api/")
                                .addPathSegment("content")                
                                .addQueryParameter("spaceKey", "TEST")
                                .addQueryParameter("title", title)
                                .build();
    final Request req = new Request.Builder()
            .header("Authorization", credential)
            .url( url )  
            .get()
            .build();
    
    final Response res = client.build().newCall(req).execute();

    Assert.assertThat( res, IsNull.notNullValue());
    Assert.assertThat( res.isSuccessful(), Is.is(true));
    final ResponseBody body = res.body();
    Assert.assertThat( body, IsNull.notNullValue());

    try( Reader r = body.charStream()) {
        
        final JsonReader rdr = Json.createReader(r);
        
        final JsonObject root = rdr.readObject();
        
        Assert.assertThat( root,  IsNull.notNullValue() );
        Assert.assertThat( root.containsKey("results"), Is.is(true) );
        
        final JsonArray results = root.getJsonArray("results");
        Assert.assertThat( results,  IsNull.notNullValue() );
        
        success.accept(results);
        
    }
    
}
 
Example 20
Source Project: AsciidocFX   File: LocationConfigBean.java    License: Apache License 2.0 2 votes vote down vote up
@Override
public void load(Path configPath, ActionEvent... actionEvent) {

    fadeOut(infoLabel, "Loading...");

    loadPathDefaults();

    Reader fileReader = IOHelper.fileReader(configPath);
    JsonReader jsonReader = Json.createReader(fileReader);

    JsonObject jsonObject = jsonReader.readObject();

    String stylesheetDefault = jsonObject.getString("stylesheetDefault", null);
    String stylesheetOverrides = jsonObject.getString("stylesheetOverrides", null);
    String mathjax = jsonObject.getString("mathjax", null);
    String kindlegen = jsonObject.getString("kindlegen", null);

    IOHelper.close(jsonReader, fileReader);

    threadService.runActionLater(() -> {

        if (Objects.nonNull(stylesheetDefault)) {
            this.setStylesheetDefault(stylesheetDefault);
        }

        if (Objects.nonNull(stylesheetOverrides)) {
            this.setStylesheetOverrides(stylesheetOverrides);
        }

        if (Objects.nonNull(mathjax)) {
            this.setMathjax(mathjax);
        }

        if (Objects.nonNull(kindlegen)) {
            this.setKindlegen(kindlegen);
        }

        fadeOut(infoLabel, "Loaded...");

    });

}