Java Code Examples for javax.json.JsonObject

The following are top voted examples for showing how to use javax.json.JsonObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: microprofile-jwt-auth   File: ProviderInjectionTest.java   View source code 10 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected jti claim is as expected")
public void verifyInjectedJTI2() 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 2
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   View source code 8 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected raw token claim using @Claim(standard) is as expected")
public void verifyInjectedRawTokenStandard() throws Exception {
    Reporter.log("Begin verifyInjectedRawTokenStandard\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedRawTokenStandard";
    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 3
Project: aceql-http   File: ResultAnalyzer.java   View source code 7 votes vote down vote up
/**
    * Says if status is OK
    * @return true if status is OK
    */
   public boolean isStatusOk() {

if (jsonResult == null || jsonResult.isEmpty()) {
    return false;
}

try {
    JsonReader reader = Json.createReader(new StringReader(jsonResult));
    JsonStructure jsonst = reader.read();

    JsonObject object = (JsonObject) jsonst;
    JsonString status = (JsonString) object.get("status");

    if (status != null && status.getString().equals("OK")) {
	return true;
    } else {
	return false;
    }
} catch (Exception e) {
    this.parseException = e;
    invalidJsonStream = true;
    return false;
}

   }
 
Example 4
Project: devtools-driver   File: RemoteIOSWebDriver.java   View source code 7 votes vote down vote up
public List<Cookie> getCookies() {
  List<Cookie> res = new ArrayList<>();
  JsonObject o = inspector.sendCommand(Page.getCookies());
  JsonArray cookies = o.getJsonArray("cookies");
  if (cookies != null) {
    for (int i = 0; i < cookies.size(); i++) {
      JsonObject cookie = cookies.getJsonObject(i);
      String name = cookie.getString("name");
      String value = cookie.getString("value");
      String domain = cookie.getString("domain");
      String path = cookie.getString("path");
      Date expiry = new Date(cookie.getJsonNumber("expires").longValue());
      boolean isSecure = cookie.getBoolean("secure");
      Cookie c = new Cookie(name, value, domain, path, expiry, isSecure);
      res.add(c);
    }
    return res;
  } else {
    // TODO
  }
  return null;
}
 
Example 5
Project: microprofile-jwt-auth   File: ClaimValueInjectionEndpoint.java   View source code 7 votes vote down vote up
@GET
@Path("/verifyInjectedOptionalSubject")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedOptionalSubject(@QueryParam("sub") String subject) {
    boolean pass = false;
    String msg;
    // sub
    Optional<String> optSubValue = optSubject.getValue();
    if(optSubValue == null || !optSubValue.isPresent()) {
        msg = Claims.sub.name()+" value is null or missing, FAIL";
    }
    else if(optSubValue.get().equals(subject)) {
        msg = Claims.sub.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.sub.name(), optSubValue, subject);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example 6
Project: microprofile-jwt-auth   File: PrimitiveInjectionEndpoint.java   View source code 7 votes vote down vote up
@GET
@Path("/verifyInjectedSUB")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedSUB(@QueryParam("sub") String sub) {
    boolean pass = false;
    String msg;
    // sUB
    String subValue = this.subject;
    if (subValue == null || subValue.length() == 0) {
        msg = Claims.sub.name() + "value is null or empty, FAIL";
    }
    else if (subValue.equals(sub)) {
        msg = Claims.sub.name() + " PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.sub.name(), subValue, sub);
    }
    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
Example 7
Project: devtools-driver   File: DevtoolsDebugger.java   View source code 7 votes vote down vote up
/** Notify listener that a message has been received */
protected final void notifyMessageReceived(JsonObject message) {
  // If there's no id, it's an event message.
  if (message.containsKey("id")) {
    int commandId = message.getInt("id");
    CommandFuture future = idToFuture.remove(commandId);
    if (future != null) {
      future.set(message);
    }
    // Or, it's a result object if it has a method.
  } else if (message.containsKey("method")) {
    DevtoolsEvent event = DevtoolsEvent.fromJson(message);
    for (Consumer<DevtoolsEvent> listener : eventListeners) {
      listener.accept(event);
    }
  } // Drop the message if we cannot identify it.
}
 
Example 8
Project: sample-acmegifts   File: OccasionResource.java   View source code 7 votes vote down vote up
Response buildPostRunResponse(OccasionResponse occasionResponse) {

    Throwable notificationThrowable = occasionResponse.getNotificationThrowable();
    String requestResponse = occasionResponse.getNotificationType();
    if (notificationThrowable != null) {
      logger.fine("Throwable message: " + notificationThrowable.getMessage());
    }
    JsonBuilderFactory factory = Json.createBuilderFactory(null);
    JsonObjectBuilder builder = factory.createObjectBuilder();
    JsonObject responseBody = null;
    if (requestResponse.equals(OccasionResponse.NOTIFICATION_TYPE_LOG)
        || requestResponse.equals(OccasionResponse.NOTIFICATION_TYPE_TWEET)) {
      responseBody = builder.add(JSON_KEY_OCCASION_POST_RUN_SUCCESS, requestResponse).build();
    } else {
      responseBody = builder.add(JSON_KEY_OCCASION_POST_RUN_ERROR, requestResponse).build();
    }
    return Response.ok(responseBody, MediaType.APPLICATION_JSON).build();
  }
 
Example 9
Project: sample-acmegifts   File: NotificationResource.java   View source code 6 votes vote down vote up
@POST
@Path("/")
@Consumes("application/json")
public Response notify(JsonObject payload) {

  // Validate the JWT.  At this point, anyone can submit a notification if they
  // have a valid JWT.
  try {
    validateJWT();
  } catch (JWTException jwte) {
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  String notification = payload.getString(JSON_KEY_NOTIFICATION);
  logger.info(notification);

  return Response.ok().build();
}
 
Example 10
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   View source code 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI,
    description = "Verify that the injected token issuer claim is as expected")
public void verifyIssuerClaim() 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 11
Project: microprofile-jwt-auth   File: ClaimValueInjectionTest.java   View source code 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 12
Project: microprofile-jwt-auth   File: RequiredClaimsTest.java   View source code 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_JWT,
        description = "Verify that the aud claim is as expected")
public void verifyOptionalAudience() throws Exception {
    Reporter.log("Begin verifyOptionalAudience\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyOptionalAudience";
    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 13
Project: microprofile-jwt-auth   File: PrimitiveInjectionEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyInjectedUPN")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedUPN(@QueryParam("upn") String upn) {
    boolean pass = false;
    String msg;
    // uPN
    String upnValue = this.upn;
    if (upnValue == null || upnValue.length() == 0) {
        msg = Claims.upn.name() + "value is null or empty, FAIL";
    }
    else if (upnValue.equals(upn)) {
        msg = Claims.upn.name() + " PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.upn.name(), upnValue, upn);
    }
    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
Example 14
Project: devtools-driver   File: CommandGenerationTest.java   View source code 6 votes vote down vote up
@Test
public void testGeneratedMessageWithTypes() {
  JsonArray canonicalArguments =
      Json.createArrayBuilder()
          .add(Runtime.callArgument().withValue("val").withObjectId("567").properties())
          .add(Runtime.callArgument().withValue(3).withObjectId("789").properties())
          .build();
  ImmutableList<Runtime.CallArgument> argumentsList =
      ImmutableList.of(
          Runtime.callArgument().withValue("val").withObjectId("567"),
          Runtime.callArgument().withValue(3).withObjectId("789"));
  DevtoolsCommand first =
      Runtime.callFunctionOn("123", "function funky() { return 2; }")
          .withArguments(argumentsList)
          .withDoNotPauseOnExceptionAndMuteConsole(true)
          .withGeneratePreview(false);

  JsonObject firstParams = first.params();
  assertThat(firstParams.getJsonArray("arguments")).isEqualTo(canonicalArguments);
}
 
Example 15
Project: microprofile-jwt-auth   File: PrimitiveInjectionTest.java   View source code 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    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 16
Project: microprofile-jwt-auth   File: JsonValueInjectionTest.java   View source code 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected iat claim is as expected from Token2")
public void verifyInjectedIssuedAt2() throws Exception {
    Reporter.log("Begin verifyInjectedIssuedAt2\n");
    HashMap<String, Long> timeClaims = new HashMap<>();
    String token2 = TokenUtils.generateTokenString("/Token2.json", null, timeClaims);
    Long iatClaim = timeClaims.get(Claims.auth_time.name());
    Long authTimeClaim = timeClaims.get(Claims.auth_time.name());
    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 " + 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 17
Project: sling-org-apache-sling-launchpad-integration-tests   File: UserPrivilegesInfoTest.java   View source code 6 votes vote down vote up
/**
 * Checks whether the current user has been granted privileges
 * to update the membership of the specified group.
 */
@Test 
public void testCanUpdateGroupMembers() throws IOException, JsonException {
	testGroupId = H.createTestGroup();
	testUserId = H.createTestUser();

	//1. Verify non admin user can not update group membership
	String getUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".privileges-info.json";

	//fetch the JSON for the test page to verify the settings.
	Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");

	String json = H.getAuthenticatedContent(testUserCreds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
	assertNotNull(json);
	JsonObject jsonObj = JsonUtil.parseObject(json);
	
	//normal user can not remove group
	assertEquals(false, jsonObj.getBoolean("canUpdateGroupMembers"));
}
 
Example 18
Project: sling-org-apache-sling-launchpad-integration-tests   File: UserPrivilegesInfoTest.java   View source code 6 votes vote down vote up
/**
 * Checks whether the current user has been granted privileges
 * to update the properties of the specified group.
 */
@Test 
public void testCanUpdateGroupProperties() throws IOException, JsonException {
	testGroupId = H.createTestGroup();
	testUserId = H.createTestUser();

	//1. Verify non admin user can not update group properties
	String getUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".privileges-info.json";

	//fetch the JSON for the test page to verify the settings.
	Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");

	String json = H.getAuthenticatedContent(testUserCreds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
	assertNotNull(json);
	JsonObject jsonObj = JsonUtil.parseObject(json);
	
	//normal user can not update group properties
	assertEquals(false, jsonObj.getBoolean("canUpdateProperties"));
}
 
Example 19
Project: iopipe-java-core   File: IOpipeServiceTest.java   View source code 6 votes vote down vote up
/**
 * Tests throwing of an exception with a cause.
 *
 * @since 2017/12/15
 */
@Test
public void testThrowWithCause()
{
	AtomicBoolean requestmade = new AtomicBoolean(),
		haserror = new AtomicBoolean();
	
	super.runTest("testThrowWithCause", false,
		() -> testConfig(true, (__r) ->
		{
			requestmade.set(true);
			if (((JsonObject)__r.bodyValue()).containsKey("errors"))
				haserror.set(true);
		}),
		super::baseThrowWithCause);
	
	assertTrue("requestmade", requestmade.get());
	assertTrue("haserror", haserror.get());
}
 
Example 20
Project: devtools-driver   File: RemoteWebElement.java   View source code 6 votes vote down vote up
public RemoteWebElement findElementByXpath(String xpath) throws Exception {
  String f =
      "(function(xpath, element) { var result = "
          + JsAtoms.xpath("xpath", "element")
          + ";"
          + "return result;})";
  JsonObject response =
      getInspectorResponse(
          f,
          false,
          callArgument().withValue(xpath),
          callArgument().withObjectId(getRemoteObject().getId()));
  RemoteObject ro = inspector.cast(response);
  if (ro == null) {
    throw new NoSuchElementException("cannot find element by Xpath " + xpath);
  } else {
    return ro.getWebElement();
  }
}
 
Example 21
Project: sling-org-apache-sling-launchpad-integration-tests   File: CreateGroupTest.java   View source code 6 votes vote down vote up
public void testCreateGroup() throws IOException, JsonException {
       String postUrl = HTTP_BASE_URL + "/system/userManager/group.create.html";

	testGroupId = "testGroup" + random.nextInt();
	List<NameValuePair> postParams = new ArrayList<NameValuePair>();
	postParams.add(new NameValuePair(":name", testGroupId));
	postParams.add(new NameValuePair("marker", testGroupId));
	assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null);

	//fetch the group profile json to verify the settings
	String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".json";
	Credentials creds = new UsernamePasswordCredentials("admin", "admin");
	String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
	assertNotNull(json);
	JsonObject jsonObj = JsonUtil.parseObject(json);
	assertEquals(testGroupId, jsonObj.getString("marker"));
}
 
Example 22
Project: microprofile-jwt-auth   File: ClaimValueInjectionEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyInjectedRawTokenStandard")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedRawTokenStandard(@QueryParam("raw_token") String rt) {
    boolean pass = false;
    String msg;
    // raw_token
    String rawTokenValue = rawTokenStandard.getValue();
    if(rawTokenValue == null || rawTokenValue.length() == 0) {
        msg = Claims.raw_token.name()+"value is null or empty, FAIL";
    }
    else if(rawTokenValue.equals(rt)) {
        msg = Claims.raw_token.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.raw_token.name(), rawTokenValue, rt);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example 23
Project: microprofile-jwt-auth   File: PrimitiveInjectionTest.java   View source code 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 24
Project: microprofile-jwt-auth   File: ProviderInjectionEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyInjectedOptionalAuthTime")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedOptionalAuthTime(@QueryParam("auth_time") Long authTime) {
    boolean pass = false;
    String msg;
    // auth_time
    Optional<Long> optAuthTimeValue = this.authTime.get();
    if(optAuthTimeValue == null || !optAuthTimeValue.isPresent()) {
        msg = Claims.auth_time.name()+" value is null or missing, FAIL";
    }
    else if(optAuthTimeValue.get().equals(authTime)) {
        msg = Claims.auth_time.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.auth_time.name(), optAuthTimeValue, authTime);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example 25
Project: thornsec-core   File: NetworkData.java   View source code 6 votes vote down vote up
public void read(JsonObject data) {
		String include = data.getString("include", null);
		if (include != null) {
			readInclude(include);
		} else {
			this.ipClass = data.getString("class", "a");
//			this.domain = data.getString("domain", null);
			this.dns = data.getString("dns", "8.8.8.8");
			this.ip = data.getString("ip", null);
			this.adBlocking = data.getString("adblocking", "no");
			this.gpg = data.getString("gpg", null);
			this.autoGenPasswds = data.getString("autogenpasswds", "false"); //Default to false
			this.adminEmail = data.getString("adminemail", null);
			this.vpnOnly = data.getString("vpnonly", "no");
			defaultServerData = new ServerData("");
			defaultServerData.read(data);
			servers = new HashMap<String, ServerData>();
			readServers(data.getJsonObject("servers"));
			devices = new HashMap<String, DeviceData>();
			readDevices(data.getJsonObject("devices"));
		}
	}
 
Example 26
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletUpdateTest.java   View source code 6 votes vote down vote up
public void testMixinTypes() throws IOException, JsonException {
    
    // create a node without mixin node types
    final Map <String, String> props = new HashMap <String, String> ();
    props.put("jcr:primaryType","nt:unstructured");
    final String location = testClient.createNode(postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX, props);
    
    // assert no mixins
    String content = getContent(location + ".json", CONTENT_TYPE_JSON);
    JsonObject json = JsonUtil.parseObject(content);
    assertFalse("jcr:mixinTypes not expected to be set", json.containsKey("jcr:mixinTypes"));
    
    // add mixin
    props.clear();
    props.put("jcr:mixinTypes", "mix:versionable");
    testClient.createNode(location, props);
    
    content = getContent(location + ".json", CONTENT_TYPE_JSON);
    json = JsonUtil.parseObject(content);
    assertTrue("jcr:mixinTypes expected after setting them", json.containsKey("jcr:mixinTypes"));
    
    Object mixObject = json.get("jcr:mixinTypes");
    assertTrue("jcr:mixinTypes must be an array", mixObject instanceof JsonArray);
    
    JsonArray mix = (JsonArray) mixObject;
    assertTrue("jcr:mixinTypes must have a single entry", mix.size() == 1);
    assertEquals("jcr:mixinTypes must have correct value", "mix:versionable", mix.getString(0));

    // remove mixin
    props.clear();
    props.put("jcr:[email protected]", "-");
    testClient.createNode(location, props);

    content = getContent(location + ".json", CONTENT_TYPE_JSON);
    json = JsonUtil.parseObject(content);
    final boolean noMixins = !json.containsKey("jcr:mixinTypes") || json.getJsonArray("jcr:mixinTypes").size() == 0;
    assertTrue("no jcr:mixinTypes expected after clearing it", noMixins);
}
 
Example 27
Project: HueSense   File: TempSensor.java   View source code 6 votes vote down vote up
@Override
public void updateSensor(JsonObject obj) throws UpdateException {
    try {
        setName(obj.getString("name"));

        JsonObject state = obj.getJsonObject("state");

        int t = state.getInt("temperature");
        BigDecimal temp = new BigDecimal(t).movePointLeft(2);

        SimpleDateFormat sdf = new SimpleDateFormat(Constants.HUEDATEFORMAT);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date time = sdf.parse(state.getString("lastupdated"));

        SensorValue<BigDecimal> val = new SensorValue<>(time, temp);
        updateValue(val);

        JsonObject conf = obj.getJsonObject("config");
        setOn(conf.getBoolean("on"));
        setBattery(conf.getInt("battery"));
        setReachable(conf.getBoolean("reachable"));

    } catch (ParseException | NullPointerException | ClassCastException ex) {
        throw new UpdateException("Error updating temp sensor", ex);
    }
}
 
Example 28
Project: microprofile-jwt-auth   File: RequiredClaimsEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyJTI")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyJTI(@QueryParam("jti") String jwtID) {
    boolean pass = false;
    String msg;
    // jti
    String jtiValue = rawTokenJson.getTokenID();
    if (jtiValue == null || jtiValue.length() == 0) {
        msg = Claims.jti.name() + "value is null or empty, FAIL";
    }
    else if (jtiValue.equals(jwtID)) {
        msg = Claims.jti.name() + " PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.jti.name(), jtiValue, jwtID);
    }
    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
Example 29
Project: json_converter   File: JsonConversion.java   View source code 6 votes vote down vote up
private void convert(JsonObject json) {
    int i =0;
    builder.append("Json.createObjectBuilder()\n");
    for (Map.Entry<String, JsonValue> entry : json.entrySet()) {
        builder.append(spaces() + indent() + ".add(");
        String key = entry.getKey();
        JsonValue value = entry.getValue();
        builder.append('"');
        builder.append(key);
        builder.append('"');
        builder.append(", ");
        builder.append(new JsonConversion(indent + INDENT_INCREMENT).execute(value));
        builder.append(")");
        if(i++ != json.size() -1 ){
            builder.append("\n");
        }
    }
}
 
Example 30
Project: ide-plugins   File: ApplicationsSWT.java   View source code 6 votes vote down vote up
private void restoreDialog(List<Application> list) {
    display.asyncExec(() -> { 
            composite.getParent().setCursor(new Cursor(display, SWT.CURSOR_ARROW));
            enableControls(true);
            if (list != null && ! list.isEmpty()) {
                applicationsList.addAll(list);
                currentAppBox.setItems(list.stream().map(Application::getName).toArray(size -> new String[size]));

            if (jsonConfig != null && !jsonConfig.isEmpty()) {
                JsonObject object = Json.createReader(new StringReader(jsonConfig)).readObject()
                        .getJsonObject("gluonCredentials");
                if (object != null) {
                    existingApp = list.stream()
                        .filter(app -> app.getIdentifier().equals(object.getString("applicationKey")) &&
                                app.getSecret().equals(object.getString("applicationSecret")))
                        .findFirst()
                        .orElse(null);
                    if (existingApp != null) {
                        currentAppBox.setText(existingApp.getName());
                    }
                }
            }
        }
    });
}
 
Example 31
Project: cedato-api-client   File: SupIterator.java   View source code 6 votes vote down vote up
/**
 * Check json has navigation next link.
 * @return True if json has navigation next link,
 *          Else if json hasn't navigation next link
 */
private boolean navigationNext() {
    final AtomicBoolean next = new AtomicBoolean(false);
    final JsonObject data;
    try {
        data = this.temp.get()
                        .json()
                        .getJsonObject("data");
    } catch (final IOException error) {
        throw new UncheckedIOException(error);
    }
    try {
        final JsonObject navigation = data.getJsonObject("navigation");
        next.set(navigation != null
            && navigation
            .getString("next", null) != null);
    } catch (final ClassCastException exception) {
        // Do nothing
    }
    return next.get();
}
 
Example 32
Project: sling-org-apache-sling-launchpad-integration-tests   File: UpdateGroupTest.java   View source code 5 votes vote down vote up
JsonArray getTestGroupMembers(Credentials creds) throws IOException, JsonException {
      String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + testGroupId + ".json";
assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data
      String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
      assertNotNull(json);
      JsonObject jsonObj = JsonUtil.parseObject(json);
      JsonArray members = jsonObj.getJsonArray("members");
      return members;
  }
 
Example 33
Project: bluemix-liberty-microprofile-demo   File: JsonUtil.java   View source code 5 votes vote down vote up
public static LocalDate getDate(String key, JsonObject json) {
   	LocalDate result = null;
	if (json.containsKey(key)) {
		JsonString value = json.getJsonString(key);
		if (value != null) {
			result = date(value.getString());
		}
	}
	return result;
}
 
Example 34
Project: devtools-driver   File: RemoteWebElement.java   View source code 5 votes vote down vote up
private void clickAtom() {
  try {
    String f = "(function(arg) { var text = " + JsAtoms.tap("arg") + "; return text;})";
    JsonObject response =
        getInspectorResponse(f, true, callArgument().withObjectId(getRemoteObject().getId()));
    inspector.cast(response);
  } catch (Exception e) {
    throw new WebDriverException(e);
  }
}
 
Example 35
Project: oauth-filter-for-java   File: JwtData.java   View source code 5 votes vote down vote up
JwtData(JsonObject jsonObject)
{
    _jsonObject = jsonObject;

    String scopesInToken = JsonUtils.getString(_jsonObject, "scope");
    String[] presentedScopes = scopesInToken == null ? NO_SCOPES : scopesInToken.split("\\s+");
    
    _scopes = new HashSet<>(Arrays.asList(presentedScopes));
}
 
Example 36
Project: javaee-calculator   File: OperationsResource.java   View source code 5 votes vote down vote up
@POST
@Path("multiplication")
public JsonObject multiplication(JsonObject input){
    int a = input.getJsonNumber("a").intValue();
    int b = input.getJsonNumber("b").intValue();
    int result = this.operations.multiply(a, b);
    return Json.createObjectBuilder().
            add("result", result).
            build();

}
 
Example 37
Project: scalable-coffee-shop   File: EventDeserializer.java   View source code 5 votes vote down vote up
@Override
public CoffeeEvent deserialize(final String topic, final byte[] data) {
    try (ByteArrayInputStream input = new ByteArrayInputStream(data)) {
        final JsonObject jsonObject = Json.createReader(input).readObject();
        final Class<? extends CoffeeEvent> eventClass = (Class<? extends CoffeeEvent>) Class.forName(jsonObject.getString("class"));
        return eventClass.getConstructor(JsonObject.class).newInstance(jsonObject.getJsonObject("data"));
    } catch (Exception e) {
        logger.severe("Could not deserialize event: " + e.getMessage());
        throw new SerializationException("Could not deserialize event", e);
    }
}
 
Example 38
Project: jb-hub-client   File: RtPaginationIterator.java   View source code 5 votes vote down vote up
/**
 * Get json project.
 * @return Project json
 * @throws Exception If fails
 */
private JsonObject json() throws Exception {
    if (this.json.get() == null) {
        this.json.set(this.fetch());
    } else {
        if (!(this.json.get().size() > this.number.get())) {
            this.number.set(0);
            this.json.set(this.fetch());
        }
    }
    return this.json
        .get()
        .getJsonObject(this.number.getAndIncrement());
}
 
Example 39
Project: sling-org-apache-sling-launchpad-integration-tests   File: ModifyAceTest.java   View source code 5 votes vote down vote up
/**
 * Test to verify adding an ACE in the first position of 
 * the ACL
 */
@Test 
public void testAddAceOrderByFirst() throws IOException, JsonException {
	createAceOrderTestFolderWithOneAce();
	
	testGroupId = H.createTestGroup();

	addOrUpdateAce(testFolderUrl, testGroupId, true, "first");

	//fetch the JSON for the acl to verify the settings.
	String getUrl = testFolderUrl + ".acl.json";

	Credentials creds = new UsernamePasswordCredentials("admin", "admin");
	String json = H.getAuthenticatedContent(creds, getUrl, HttpTest.CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
	assertNotNull(json);

	JsonObject jsonObject = JsonUtil.parseObject(json);
	assertEquals(2, jsonObject.size());

	JsonObject group = jsonObject.getJsonObject(testGroupId);
	assertNotNull(group);
	assertEquals(testGroupId, group.getString("principal"));
               assertEquals(0, group.getInt("order"));
	JsonObject user =  jsonObject.getJsonObject(testUserId);
               assertNotNull(user);
               assertEquals(testUserId, user.getString("principal"));
               assertEquals(1, user.getInt("order"));
}
 
Example 40
Project: E-Clinic   File: ReligionRestEndPoint.java   View source code 5 votes vote down vote up
@GET
@Path("find/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response find(@PathParam("id") @Valid String id) {
    JsonObject build = null;
    try {
        Religion get = religionService.get(Integer.valueOf(id));
        build = Json.createObjectBuilder().add("id", get.getReligionId()).add("name", get.getName()).build();

    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity(build == null ? "No data found" : build).build();
}