Java 类javax.json.JsonObject 实例源码

项目:sample-acmegifts    文件:OccasionResource.java   
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();
  }
项目:aceql-http    文件:ResultAnalyzer.java   
/**
    * 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;
}

   }
项目:microprofile-jwt-auth    文件:ClaimValueInjectionTest.java   
@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"));
}
项目:devtools-driver    文件:RemoteIOSWebDriver.java   
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;
}
项目:microprofile-jwt-auth    文件:ProviderInjectionTest.java   
@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"));
}
项目:microprofile-jwt-auth    文件:ClaimValueInjectionEndpoint.java   
@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;
}
项目:microprofile-jwt-auth    文件:PrimitiveInjectionEndpoint.java   
@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;
}
项目:devtools-driver    文件:DevtoolsDebugger.java   
/** 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.
}
项目:sample-acmegifts    文件:NotificationResource.java   
@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();
}
项目:microprofile-jwt-auth    文件:ClaimValueInjectionTest.java   
@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"));
}
项目:microprofile-jwt-auth    文件:ClaimValueInjectionTest.java   
@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"));
}
项目:microprofile-jwt-auth    文件:RequiredClaimsTest.java   
@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"));
}
项目:microprofile-jwt-auth    文件:PrimitiveInjectionEndpoint.java   
@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;
}
项目:devtools-driver    文件:CommandGenerationTest.java   
@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);
}
项目:microprofile-jwt-auth    文件:PrimitiveInjectionTest.java   
@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"));
}
项目:microprofile-jwt-auth    文件:JsonValueInjectionTest.java   
@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"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UserPrivilegesInfoTest.java   
/**
 * 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"));
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UserPrivilegesInfoTest.java   
/**
 * 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"));
}
项目:iopipe-java-core    文件:IOpipeServiceTest.java   
/**
 * 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());
}
项目:devtools-driver    文件:RemoteWebElement.java   
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();
  }
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:CreateGroupTest.java   
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"));
}
项目:microprofile-jwt-auth    文件:ClaimValueInjectionEndpoint.java   
@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;
}
项目:microprofile-jwt-auth    文件:PrimitiveInjectionTest.java   
@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"));
}
项目:microprofile-jwt-auth    文件:ProviderInjectionEndpoint.java   
@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;
}
项目:thornsec-core    文件:NetworkData.java   
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"));
        }
    }
项目:HueSense    文件:TempSensor.java   
@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);
    }
}
项目:microprofile-jwt-auth    文件:RequiredClaimsEndpoint.java   
@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;
}
项目:json_converter    文件:JsonConversion.java   
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");
        }
    }
}
项目:ide-plugins    文件:ApplicationsSWT.java   
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());
                    }
                }
            }
        }
    });
}
项目:cedato-api-client    文件:SupIterator.java   
/**
 * 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();
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:UpdateGroupTest.java   
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;
  }
项目:bluemix-liberty-microprofile-demo    文件:JsonUtil.java   
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;
}
项目:devtools-driver    文件:RemoteWebElement.java   
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);
  }
}
项目:oauth-filter-for-java    文件:JwtData.java   
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));
}
项目:javaee-calculator    文件:OperationsResource.java   
@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();

}
项目:scalable-coffee-shop    文件:EventDeserializer.java   
@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);
    }
}
项目:jb-hub-client    文件:RtPaginationIterator.java   
/**
 * 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());
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:ModifyAceTest.java   
/**
 * 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"));
}
项目:E-Clinic    文件:ReligionRestEndPoint.java   
@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();
}