Java Code Examples for javax.json.JsonReader#readObject()

The following examples show how to use javax.json.JsonReader#readObject() . 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: TestJsonMarshaller.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Test
public void testInnerMap() throws Exception {
    Marshaller marshaller = new JsonMarshaller();

    Map<String, Object> map = new HashMap<>();
    map.put(EventConstants.TIMESTAMP, EXPECTED_TIMESTAMP);
    map.put("test", "test");
    Map<String, Object> inner = new HashMap<>();
    inner.put("other", "other");
    map.put("inner", inner);

    String jsonString = marshaller.marshal(new Event(EXPECTED_TOPIC, map));

    System.out.println(jsonString);

    JsonReader reader = Json.createReader(new StringReader(jsonString));
    JsonObject jsonObject = reader.readObject();
    Assert.assertEquals("Timestamp string", "2016-02-02T15:59:40,634Z", jsonObject.getString("@timestamp"));
    long ts = jsonObject.getJsonNumber(EventConstants.TIMESTAMP).longValue();
    Assert.assertEquals("timestamp long", EXPECTED_TIMESTAMP, ts);

    Assert.assertEquals("test", jsonObject.getString("test"));

    JsonObject innerObject = jsonObject.getJsonObject("inner");
    Assert.assertEquals("other", innerObject.getString("other"));
}
 
Example 2
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 verifyInjectedIssuedAt2() 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 3
Source File: PublicKeyAsJWKTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
    description = "Validate that the embedded JWKS key is used to verify the JWT signature")
public void testKeyAsJWK() throws Exception {
    Reporter.log("testKeyAsJWK, expect HTTP_OK");

    PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey4k.pem");
    String kid = "publicKey4k";
    HashMap<String, Long> timeClaims = new HashMap<>();
    String token = TokenUtils.generateTokenString(privateKey, kid, "/Token1.json", null, timeClaims);

    String uri = baseURL.toExternalForm() + "jwks/endp/verifyKeyAsJWK";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("kid", kid)
        ;
    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 4
Source File: JobProcessor.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
String getStorageNames( JobDefinition od ) {
	String correlation = od.getCorrelation();
	String storageNames = "?";

	if ( !StringUtils.isEmpty( correlation ) && !correlation.equals( "null" ) ) {
		JsonReader reader = Json.createReader( new StringReader( correlation ) );
		JsonObject object = reader.readObject();
		if ( object.containsKey( "businessObject" ) ) {
			JsonObject ob = object.getJsonObject( "businessObject" );
			if ( ob.containsKey( "storageNames" ) ) {
				JsonArray a = ob.getJsonArray( "storageNames" );
				storageNames = "";
				for ( int i = 0; i < a.size(); i++ ) {
					storageNames += a.getString( i );
					if ( i != a.size() - 1 ) {
						storageNames += ",";
					}
				}
			}
		}
	}
	return storageNames;
}
 
Example 5
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 customStringArray claim is as expected")
public void verifyInjectedCustomStringArray() throws Exception {
    Reporter.log("Begin verifyInjectedCustomStringArray\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomStringArray";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", "value0", "value1", "value2")
        .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
Source File: RequiredClaimsTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_JWT,
        description = "Verify that the aud claim is as expected")
public void verifyAudience() throws Exception {
    Reporter.log("Begin verifyAudience\n");
    String uri = baseURL.toExternalForm() + "endp/verifyAudience";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.aud.name(), null)
            .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 File: ClaimValueInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    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();
    System.out.println(reply);
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 8
Source File: ClaimValueInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected customInteger claim is as expected")
public void verifyInjectedCustomInteger() throws Exception {
    Reporter.log("Begin verifyInjectedCustomInteger\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomInteger";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", 123456789)
        .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: RequiredClaimsTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_JWT,
        description = "Verify that the iat claim is as expected")
public void verifyIssuedAt() throws Exception {
    Reporter.log("Begin verifyIssuedAt\n");
    String uri = baseURL.toExternalForm() + "endp/verifyIssuedAt";
    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 10
Source File: StockListener.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Override
public void onMessage(Message message) {

	TextMessage textMessage = (TextMessage) message;

	try {
		System.out.println("A new stock information arrived: " + textMessage.getText());

		JsonReader jsonReader = Json.createReader(new StringReader(textMessage.getText()));
		JsonObject stockInformation = jsonReader.readObject();

		em.persist(new StockHistory(stockInformation));
	} catch (JMSException e) {
		e.printStackTrace();
	}
}
 
Example 11
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 token issuer claim is as expected")
public void verifyIssuerClaim2() throws Exception {
    Reporter.log("Begin verifyIssuerClaim");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuer";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.iss.name(), TCKConstants.TEST_ISSUER)
        .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 12
Source File: MessageResolver.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a JSON object from a string. 
 * 
 * @param jsonString A string that is to be decoded as a JSON.
 * @return JsonObject if the decoding was successful, or null if something went wrong (string is not a valid JSON etc.).  
 */
public JsonObject readJsonObject(String jsonString) {
	
	if (jsonString == null) {
		return null;
	}
	
	// make a JSON from the incoming String - any string that is not a valid JSON will throw exception
	JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
	
	JsonObject json;
	
	try {
		json = jsonReader.readObject();
	} catch (Exception e) {
		logger.severe("Exception during reading JSON object: " 
					+ e.getMessage());
		
		return null;
	} finally {
		jsonReader.close();
	}
	
	return json;
}
 
Example 13
Source File: clientUtilAuth.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String decodePreauth(String input, int returntype) {

        JsonReader jsonReader = Json.createReader(new StringReader(input));
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();

        if (returntype == 0) {
            return jsonObject.getString(CSConstants.JSON_USER_KEY_HANDLE);
        } else if (returntype == 1) {
            return jsonObject.getString(CSConstants.JSON_KEY_SESSIONID);
        } else if (returntype == 2) {
            return jsonObject.getString(CSConstants.JSON_KEY_CHALLENGE);
        } else if (returntype == 3) {
            return jsonObject.getString(CSConstants.JSON_KEY_VERSION);
        } else {
            return jsonObject.getString(CSConstants.JSON_KEY_APP_ID);
        }

    }
 
Example 14
Source File: TestJdbcAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws SQLException {
    System.setProperty("derby.stream.error.file", "target/derby.log");
    Marshaller marshaller = new JsonMarshaller();
    EmbeddedDataSource dataSource = new EmbeddedDataSource();
    dataSource.setDatabaseName("target/testDB");
    dataSource.setCreateDatabase("create");
    
    deleteTable(dataSource);
    
    JdbcAppender appender = new JdbcAppender();
    appender.marshaller = marshaller;
    appender.dataSource = dataSource;
    Dictionary<String, Object> config = new Hashtable<>();
    config.put("dialect", "derby");
    appender.open(config);
    
    Map<String, Object> data = new HashMap<>();
    data.put(EventConstants.TIMESTAMP, TIMESTAMP);
    Event event = new Event(TOPIC, data);
    appender.handleEvent(event);

    try (Connection con = dataSource.getConnection(); Statement statement = con.createStatement();) {
        ResultSet res = statement.executeQuery("select timestamp, content from " + TABLE_NAME);
        res.next();
        long dbTimeStamp = res.getLong(1);
        String json = res.getString(2);
        JsonReader reader = Json.createReader(new StringReader(json));
        JsonObject jsonO = reader.readObject();
        Assert.assertEquals("Timestamp db", TIMESTAMP, dbTimeStamp);
        Assert.assertEquals("Timestamp string", "2016-02-02T15:59:40,634Z",jsonO.getString("@timestamp"));
        Assert.assertEquals("timestamp long", TIMESTAMP, jsonO.getJsonNumber(EventConstants.TIMESTAMP).longValue());
        Assert.assertEquals("Topic", TOPIC, jsonO.getString(EventConstants.EVENT_TOPIC.replace('.','_')));
        Assert.assertFalse(res.next());
    }
}
 
Example 15
Source File: JsonpServlet.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    JsonReader jsonReader = Json.createReader(req.getReader());
    JsonObject jsonIn = jsonReader.readObject();
    JsonWriter jsonWriter = Json.createWriter(resp.getWriter());
    JsonObject jsonOut =
        Json.createObjectBuilder()
            .add("greeting", jsonIn.getString("greeting"))
            .add("fromServlet", "true")
            .build();
    jsonWriter.writeObject(jsonOut);
}
 
Example 16
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 5 votes vote down vote up
@GET
  @Path("/v1/getInfo/patients")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getPatients() {
      List<Patient> results = entityManager.createNamedQuery("Patient.getPatients", Patient.class).getResultList();
      Jsonb jsonb = JsonbBuilder.create();
      String patientBlob = "{\"ResultSet Output\": " + jsonb.toJson(results)
      + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";
      
      JsonReader jsonReader = Json.createReader(new StringReader(patientBlob));
          
      JsonObject jresponse  = jsonReader.readObject();
      jsonReader.close();
return Response.ok(jresponse).build();
  }
 
Example 17
Source File: JaxrsHttpReceiver.java    From sample.microservices.12factorapp with Apache License 2.0 5 votes vote down vote up
public String storeData(String data, String database) throws Exception {
    System.out.println("Storing data " + data);
    // Convert string to jsonObject
    InputStream is = new ByteArrayInputStream(data.getBytes());
    JsonReader reader = Json.createReader(is);
    JsonObject jsonData = reader.readObject();
    Entity<myObject> ent = Entity.entity(new myObject(jsonData), MediaType.APPLICATION_JSON);
    // Get response
    ResponseHandler responseHandler = new ResponseHandler("/" + database + "/");
    String response = responseHandler.invoke(RequestType.POST, ent);
    return response;
}
 
Example 18
Source File: Issue106IntegrationTest.java    From maven-confluence-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void addWikiPage() throws IOException {
    
    final String title = "test-wiki";
    
    findPages( title, (results) -> {
            if( results.size() == 1 ) {
                final JsonObject item0 = results.getJsonObject(0);
                Assert.assertThat( item0,  IsNull.notNullValue() );
                Assert.assertThat( item0.containsKey("id"), Is.is(true) );
                
                deletePage( item0.getString("id") );
            }
        
    });


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

    final HttpUrl.Builder url = new HttpUrl.Builder()
                                .scheme(SCHEME)
                                .host(HOST)
                                .port(PORT)
                                .addPathSegments("rest/api/content")
                                ;
    
    final MediaType storageFormat = MediaType.parse("application/json");
    
    JsonObject inputData = Json.createObjectBuilder()
            .add("type","page")
            .add("title",title)
            .add("space",Json.createObjectBuilder().add("key", "TEST"))
            .add("body", Json.createObjectBuilder()
                            .add("storage", Json.createObjectBuilder()
                                            .add("representation","wiki")
                                            .add("value","h1. TITLE H1")))
            .build();
    final RequestBody inputBody = RequestBody.create(storageFormat, 
            inputData.toString());
    
    final Request req = new Request.Builder()
            .header("Authorization", credential)
            .url( url.build() )  
            .post(inputBody)
            .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("id"), Is.is(true) );
        
    }
    
    
}
 
Example 19
Source File: EmployeeJSONReader.java    From journaldev with MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException {
	InputStream fis = new FileInputStream(JSON_FILE);
	
	//create JsonReader object
	JsonReader jsonReader = Json.createReader(fis);
	
	/**
	 * We can create JsonReader from Factory also
	JsonReaderFactory factory = Json.createReaderFactory(null);
	jsonReader = factory.createReader(fis);
	*/
	
	//get JsonObject from JsonReader
	JsonObject jsonObject = jsonReader.readObject();
	
	//we can close IO resource and JsonReader now
	jsonReader.close();
	fis.close();
	
	//Retrieve data from JsonObject and create Employee bean
	Employee emp = new Employee();
	
	emp.setId(jsonObject.getInt("id"));
	emp.setName(jsonObject.getString("name"));
	emp.setPermanent(jsonObject.getBoolean("permanent"));
	emp.setRole(jsonObject.getString("role"));
	
	//reading arrays from json
	JsonArray jsonArray = jsonObject.getJsonArray("phoneNumbers");
	long[] numbers = new long[jsonArray.size()];
	int index = 0;
	for(JsonValue value : jsonArray){
		numbers[index++] = Long.parseLong(value.toString());
	}
	emp.setPhoneNumbers(numbers);
	
	//reading inner object from json object
	JsonObject innerJsonObject = jsonObject.getJsonObject("address");
	Address address = new Address();
	address.setStreet(innerJsonObject.getString("street"));
	address.setCity(innerJsonObject.getString("city"));
	address.setZipcode(innerJsonObject.getInt("zipcode"));
	emp.setAddress(address);
	
	//print employee bean information
	System.out.println(emp);
	
}
 
Example 20
Source File: Tool.java    From bookish with MIT License 4 votes vote down vote up
public void process(String[] args) throws Exception {
		options = handleArgs(args);
		String metadataFilename = option("metadataFilename");
		inputDir = new File(metadataFilename).getParent();
		outputDir = option("o");

		Target target = (Target)optionO("target");

		ParrtIO.mkdir(outputDir+"/images");
		String snippetsDir = getBuildDir(metadataFilename)+"/snippets";
		ParrtIO.mkdir(snippetsDir);

		if ( metadataFilename.endsWith(".md") ) { // just one file
			generateArticle(metadataFilename, target);
			return;
		}

		// otherwise, read and use metadata
		JsonReader jsonReader = Json.createReader(new FileReader(metadataFilename));
		this.metadata = jsonReader.readObject();
//		System.out.println(metadata);

		Book book = createBook(target, metadata);

		// parse all documents first to get entity defs
		List<BookishParser.DocumentContext> trees = new ArrayList<>();
		List<Map<String, EntityDef>> entities = new ArrayList<>();
		List<List<ExecutableCodeDef>> codeBlocks = new ArrayList<>();
		JsonArray markdownFilenames = metadata.getJsonArray("chapters");
		for (JsonValue f : markdownFilenames) {
			String fname = stripQuotes(f.toString());
			book.filenames.add(fname);
			Pair<BookishParser.DocumentContext, BookishParser> results =
				parseChapter(inputDir, fname, book.chapCounter);
			BookishParser.DocumentContext tree = results.a;
			BookishParser parser = results.b;
			book.chapCounter++;
			trees.add(tree);
			entities.add(parser.entities);
			codeBlocks.add(parser.codeBlocks);
		}

		executeCodeSnippets(book, getBuildDir(metadataFilename), codeBlocks);

		// now walk all trees and translate
		generateBook(target, book, trees, entities);

		execCommandLine(String.format("cp -r %s/css %s", inputDir, outputDir));
		copyImages(book, inputDir, outputDir);
		execCommandLine(String.format("cp -r %s/css %s", inputDir, outputDir));
	}