Java Code Examples for javax.json.JsonObject#getString()
The following examples show how to use
javax.json.JsonObject#getString() .
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: JsonConverter.java From junit-json-params with Apache License 2.0 | 6 votes |
/** * Convert the supplied {@code source} object according to the supplied * {@code context}. * * @param source the source object to convert; may be {@code null} * @param context the parameter context where the converted object will be * used; never {@code null} * @return the converted object; may be {@code null} but only if the target * type is a reference type * @throws ArgumentConversionException if an error occurs during the * conversion */ @Override public Object convert(Object source, ParameterContext context) { if (!(source instanceof JsonObject)) { throw new ArgumentConversionException("Not a JsonObject"); } JsonObject json = (JsonObject) source; String name = context.getParameter().getName(); Class<?> type = context.getParameter().getType(); if (type == String.class) { return json.getString(name); } else if (type == int.class) { return json.getInt(name); } else if (type == boolean.class) { return json.getBoolean(name); } throw new ArgumentConversionException("Can't convert to type: '" + type.getName() + "'"); }
Example 2
Source File: ReplicatedMultipleFailbackTest.java From activemq-artemis with Apache License 2.0 | 6 votes |
private static Map<String, Pair<String, String>> decodeNetworkTopologyJson(String networkTopologyJson) { if (networkTopologyJson == null || networkTopologyJson.isEmpty()) { return Collections.emptyMap(); } try (JsonReader jsonReader = Json.createReader(new StringReader(networkTopologyJson))) { final JsonArray nodeIDs = jsonReader.readArray(); final int nodeCount = nodeIDs.size(); Map<String, Pair<String, String>> networkTopology = new HashMap<>(nodeCount); for (int i = 0; i < nodeCount; i++) { final JsonObject nodePair = nodeIDs.getJsonObject(i); final String nodeID = nodePair.getString("nodeID"); final String live = nodePair.getString("live"); final String backup = nodePair.getString("backup", null); networkTopology.put(nodeID, new Pair<>(live, backup)); } return networkTopology; } }
Example 3
Source File: CollaborativeWebSocketModuleImpl.java From eplmp with Eclipse Public License 1.0 | 6 votes |
private void onCollaborativeWithdrawInvitationMessage(String sender, Session session, WebSocketMessage webSocketMessage) { CollaborativeRoom room = CollaborativeRoom.getByKeyName(webSocketMessage.getString("key")); JsonObject broadcastMessage = webSocketMessage.getJsonObject("broadcastMessage"); String context = broadcastMessage.getString("context"); String pendingUser = webSocketMessage.getString("remoteUser"); if (room.getMasterName().equals(sender)) { // the master sent the invitation room.removePendingUser(pendingUser); // Send chat message JsonObjectBuilder b = Json.createObjectBuilder() .add("type", CHAT_MESSAGE) .add("remoteUser", sender) .add("sender", sender) .add("message", "/withdrawInvitation") .add("context", context); WebSocketMessage message = new WebSocketMessage(b.build()); webSocketSessionsManager.broadcast(pendingUser, message); broadcastNewContext(room); } }
Example 4
Source File: CadfEndpoint.java From FHIR with Apache License 2.0 | 6 votes |
public static CadfEndpoint parse(JsonObject jsonObject) throws FHIRException { CadfEndpoint.Builder builder = CadfEndpoint.builder(); String url = jsonObject.getString("url"); if (url != null) { builder.url(url); } String name = jsonObject.getString("name"); if (name != null) { builder.name(name); } String port = jsonObject.getString("port"); if (port != null) { builder.port(port); } return builder.build(); }
Example 5
Source File: NvdParser.java From dependency-track with Apache License 2.0 | 6 votes |
private VulnerableSoftware generateVulnerableSoftware(final QueryManager qm, final JsonObject cpeMatch, final Vulnerability vulnerability) { final String cpe23Uri = cpeMatch.getString("cpe23Uri"); final String versionEndExcluding = cpeMatch.getString("versionEndExcluding", null); final String versionEndIncluding = cpeMatch.getString("versionEndIncluding", null); final String versionStartExcluding = cpeMatch.getString("versionStartExcluding", null); final String versionStartIncluding = cpeMatch.getString("versionStartIncluding", null); VulnerableSoftware vs = qm.getVulnerableSoftwareByCpe23(cpe23Uri, versionEndExcluding, versionEndIncluding, versionStartExcluding, versionStartIncluding); if (vs != null) { return vs; } try { vs = ModelConverter.convertCpe23UriToVulnerableSoftware(cpe23Uri); vs.setVulnerable(cpeMatch.getBoolean("vulnerable", true)); vs.setVersionEndExcluding(versionEndExcluding); vs.setVersionEndIncluding(versionEndIncluding); vs.setVersionStartExcluding(versionStartExcluding); vs.setVersionStartIncluding(versionStartIncluding); //Event.dispatch(new IndexEvent(IndexEvent.Action.CREATE, qm.detach(VulnerableSoftware.class, vs.getId()))); return vs; } catch (CpeParsingException | CpeEncodingException e) { LOGGER.warn("An error occurred while parsing: " + cpe23Uri + " - The CPE is invalid and will be discarded."); } return null; }
Example 6
Source File: Data.java From FHIR with Apache License 2.0 | 6 votes |
public static Data parse(JsonObject jsonObject) { Data.Builder builder = Data.builder(); JsonValue t = jsonObject.get("resource_type"); if (t != null) { String resourceType = jsonObject.getString("resource_type"); builder.resourceType(resourceType); } t = jsonObject.get("id"); if (t != null) { String id = jsonObject.getString("id"); builder.id(id); } t = jsonObject.get("version_id"); if (t != null) { String versionId = jsonObject.getString("version_id"); builder.versionId(versionId); } return builder.build(); }
Example 7
Source File: JoseJsonTest.java From thorntail with Apache License 2.0 | 6 votes |
@Test public void testJwsJson() throws Exception { Jose jose = JoseLookup.lookup().get(); String signedData = client.target("http://localhost:8080/sign") .request(MediaType.TEXT_PLAIN) .post(Entity.entity(jose.sign("Hello"), MediaType.TEXT_PLAIN), String.class); Assert.assertEquals("Hello", jose.verify(signedData)); // Now confirm it is actually JWS JSON JsonReader jsonReader = Json.createReader(new StringReader(signedData)); JsonObject jwsJson = jsonReader.readObject(); // Flattened JWS JSON (single recipient only) Assert.assertEquals(3, jwsJson.size()); Assert.assertNotNull(jwsJson.get("protected")); Assert.assertNotNull(jwsJson.get("signature")); String encodedPayload = jwsJson.getString("payload"); Assert.assertEquals("Hello", new String(Base64.getUrlDecoder().decode(encodedPayload))); }
Example 8
Source File: CamundaBpmnOrderEventHandler.java From flowing-retail-old with Apache License 2.0 | 6 votes |
private Order parseOrder(JsonObject orderJson) { Order order = new Order(); // Order Service is NOT interested in customer id - ignore: JsonObject customerJson = orderJson.getJsonObject("customer"); orderJson.getString("customerId"); Customer customer = new Customer() // .setName(customerJson.getString("name")) // .setAddress(customerJson.getString("address")); order.setCustomer(customer); JsonArray jsonArray = orderJson.getJsonArray("items"); for (JsonObject itemJson : jsonArray.getValuesAs(JsonObject.class)) { order.addItem( // new OrderItem() // .setArticleId(itemJson.getString("articleId")) // .setAmount(itemJson.getInt("amount"))); } return order; }
Example 9
Source File: WeiboUser.java From albert with MIT License | 5 votes |
private void init(JsonObject json) throws WeiboException { if (json != null) { try { id = json.getJsonNumber("id").longValue(); screenName = json.getString("screen_name"); name = json.getString("name"); province = Integer.parseInt(json.getString("province")); city = Integer.parseInt(json.getString("city")); location = json.getString("location"); description = WeiboResponseUtil.withNonBmpStripped(json.getString("description")); url = json.getString("url"); profileImageUrl = json.getString("profile_image_url"); domain = json.getString("domain"); gender = json.getString("gender"); followersCount = json.getInt("followers_count"); friendsCount = json.getInt("friends_count"); favouritesCount = json.getInt("favourites_count"); statusesCount = json.getInt("statuses_count"); createdAt = WeiboResponseUtil.parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); following = json.getBoolean("following"); verified = json.getBoolean("verified"); verifiedType = json.getInt("verified_type"); verifiedReason = json.getString("verified_reason"); allowAllActMsg = json.getBoolean("allow_all_act_msg"); allowAllComment = json.getBoolean("allow_all_comment"); followMe = json.getBoolean("follow_me"); avatarLarge = json.getString("avatar_large"); onlineStatus = json.getInt("online_status"); biFollowersCount = json.getInt("bi_followers_count"); if (!json.getString("remark").isEmpty()) { remark = json.getString("remark"); } lang = json.getString("lang"); weihao = json.getString("weihao"); } catch (JsonException jsone) { throw new WeiboException(jsone.getMessage() + ":" + json.toString(), jsone); } } }
Example 10
Source File: U2FRegistrationResponse.java From fido2 with GNU Lesser General Public License v2.1 | 5 votes |
/** * The constructor of this class takes the U2F registration response parameters * in the form of stringified Json. The method parses the Json to extract needed * fileds compliant with the u2fversion specified. * @param u2fversion - Version of the U2F protocol being communicated in; * example : "U2F_V2" * @param regresponseJson - U2F Reg Response params in stringified Json form * @throws SKFEException * - In case of any error */ public U2FRegistrationResponse(String u2fversion, String regresponseJson) throws SKFEException { // Input checks if ( u2fversion==null || u2fversion.trim().isEmpty() ) { skfsLogger.logp(skfsConstants.SKFE_LOGGER,Level.SEVERE, classname, "U2FRegistrationResponse", skfsCommon.getMessageProperty("FIDO-ERR-5001"), " u2f version"); throw new SKFEException(skfsCommon.getMessageProperty("FIDO-ERR-5001") + " username"); } if ( regresponseJson==null || regresponseJson.trim().isEmpty() ) { skfsLogger.logp(skfsConstants.SKFE_LOGGER,Level.SEVERE, classname, "U2FRegistrationResponse", skfsCommon.getMessageProperty("FIDO-ERR-5001"), " regresponseJson"); throw new SKFEException(skfsCommon.getMessageProperty("FIDO-ERR-5001") + " regresponseJson"); } // u2f protocol version specific processing. if ( u2fversion.equalsIgnoreCase(U2F_VERSION_V2) ) { // Parse the reg response json string try (JsonReader jsonReader = Json.createReader(new StringReader(regresponseJson))) { JsonObject jsonObject = jsonReader.readObject(); browserdata = jsonObject.getString(skfsConstants.JSON_KEY_CLIENTDATA); registrationdata = jsonObject.getString(skfsConstants.JSON_KEY_REGSITRATIONDATA); } catch (Exception ex) { skfsLogger.logp(skfsConstants.SKFE_LOGGER,Level.SEVERE, classname, "U2FAuthenticationResponse", skfsCommon.getMessageProperty("FIDO-ERR-5011"), ex.getLocalizedMessage()); throw new SKFEException(skfsCommon.getMessageProperty("FIDO-ERR-5011") + ex.getLocalizedMessage()); } // Generate new browser data bd = new BrowserData(this.browserdata, BrowserData.REGISTRATION_RESPONSE); } else { skfsLogger.logp(skfsConstants.SKFE_LOGGER,Level.SEVERE, classname, "U2FRegistrationResponse", skfsCommon.getMessageProperty("FIDO-ERR-5002"), " version passed=" + u2fversion); throw new SKFEException(skfsCommon.getMessageProperty("FIDO-ERR-5002") + " version passed=" + u2fversion); } }
Example 11
Source File: WeiboResponseUtil.java From albert with MIT License | 5 votes |
public static boolean getBoolean(String key, JsonObject json) throws JsonException { String str = json.getString(key); if (null == str || "".equals(str) || "null".equals(str)) { return false; } return Boolean.valueOf(str); }
Example 12
Source File: HFCAClient.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
/** * Register a user. * * @param request Registration request with the following fields: name, role. * @param registrar The identity of the registrar (i.e. who is performing the registration). * @return the enrollment secret. * @throws RegistrationException if registration fails. * @throws InvalidArgumentException */ public String register(RegistrationRequest request, User registrar) throws RegistrationException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); } if (Utils.isNullOrEmpty(request.getEnrollmentID())) { throw new InvalidArgumentException("EntrollmentID cannot be null or empty"); } if (registrar == null) { throw new InvalidArgumentException("Registrar should be a valid member"); } logger.debug(format("register url: %s, registrar: %s", url, registrar.getName())); setUpSSL(); try { String body = request.toJson(); JsonObject resp = httpPost(url + HFCA_REGISTER, body, registrar); String secret = resp.getString("secret"); if (secret == null) { throw new Exception("secret was not found in response"); } logger.debug(format("register url: %s, registrar: %s done.", url, registrar)); return secret; } catch (Exception e) { RegistrationException registrationException = new RegistrationException(format("Error while registering the user %s url: %s %s ", registrar, url, e.getMessage()), e); logger.error(registrar); throw registrationException; } }
Example 13
Source File: MultipleReadinessFailedTest.java From microprofile-health with Apache License 2.0 | 5 votes |
/** * Verifies the readiness health integration with CDI at the scope of a server runtime */ @Test @RunAsClient public void testFailureResponsePayload() { Response response = getUrlReadyContents(); // status code Assert.assertEquals(response.getStatus(),503); JsonObject json = readJson(response); // response size JsonArray checks = json.getJsonArray("checks"); Assert.assertEquals(checks.size(), 2, "Expected two check responses"); for (JsonObject check : checks.getValuesAs(JsonObject.class)) { String id = check.getString("name"); switch (id) { case "successful-check": verifySuccessStatus(check); break; case "failed-check": verifyFailureStatus(check); break; default: Assert.fail("Unexpected response payload structure"); } } assertOverallFailure(json); }
Example 14
Source File: BattleResultDto.java From logbook with MIT License | 5 votes |
/** * コンストラクター * * @param object JSON Object * @param mapCellNo マップ上のマス * @param mapBossCellNo ボスマス * @param eventId EventId * @param isStart 出撃 * @param battle 戦闘 */ public BattleResultDto(JsonObject object, int mapCellNo, int mapBossCellNo, int eventId, boolean isStart, BattleDto battle) { this.battleDate = Calendar.getInstance().getTime(); this.questName = object.getString("api_quest_name"); this.rank = object.getString("api_win_rank"); this.mapCellNo = mapCellNo; this.start = isStart; this.boss = (mapCellNo == mapBossCellNo) || (eventId == 5); this.enemyName = object.getJsonObject("api_enemy_info").getString("api_deck_name"); this.dropShip = object.containsKey("api_get_ship"); this.dropItem = object.containsKey("api_get_useitem"); if (this.dropShip || this.dropItem) { if (this.dropShip) { this.dropType = object.getJsonObject("api_get_ship").getString("api_ship_type"); this.dropName = object.getJsonObject("api_get_ship").getString("api_ship_name"); } else { String name = UseItem.get(object.getJsonObject("api_get_useitem").getInt("api_useitem_id")); this.dropType = "アイテム"; this.dropName = StringUtils.defaultString(name); } } else { this.dropType = ""; this.dropName = ""; } this.battle = battle; }
Example 15
Source File: ListHandler.java From gluon-samples with BSD 3-Clause "New" or "Revised" License | 5 votes |
@RequestMapping(value = "/update/{objectIdentifier}", method = RequestMethod.POST) public void updateItem(@PathVariable("listIdentifier") String listIdentifier, @PathVariable("objectIdentifier") String objectIdentifier, @RequestBody String payload) { try (JsonReader jsonReader = Json.createReader(new StringReader(payload))) { JsonObject jsonObject = jsonReader.readObject(); String title = jsonObject.containsKey("title") ? jsonObject.getString("title") : ""; long creationDate = jsonObject.containsKey("creationDate") ? jsonObject.getJsonNumber("creationDate").longValue() : LocalDateTime.now().toEpochSecond(ZoneOffset.UTC); service.updateItem(objectIdentifier, title, creationDate); } }
Example 16
Source File: CenterSocket.java From OrionAlpha with GNU General Public License v3.0 | 4 votes |
public void init(JsonObject data) { this.addr = data.getString("ip", "127.0.0.1"); this.port = data.getInt("port", 8383); this.worldName = data.getString("worldName", "OrionAlpha"); }
Example 17
Source File: GnpsJsonParser.java From mzmine2 with GNU General Public License v2.0 | 4 votes |
public SpectralDBEntry getDBEntry(JsonObject main) { // extract dps DataPoint[] dps = getDataPoints(main); if (dps == null) return null; // extract meta data Map<DBEntryField, Object> map = new EnumMap<>(DBEntryField.class); for (DBEntryField f : DBEntryField.values()) { String id = f.getGnpsJsonID(); if (id != null && !id.isEmpty()) { try { Object o = null; if (f.getObjectClass() == Double.class || f.getObjectClass() == Integer.class || f.getObjectClass() == Float.class) { o = main.getJsonNumber(id); } else { o = main.getString(id, null); if (o != null && o.equals("N/A")) o = null; } // add value if (o != null) { if (o instanceof JsonNumber) { if (f.getObjectClass().equals(Integer.class)) { o = ((JsonNumber) o).intValue(); } else { o = ((JsonNumber) o).doubleValue(); } } // add map.put(f, o); } } catch (Exception e) { logger.log(Level.WARNING, "Cannot convert value to its type", e); } } } return new SpectralDBEntry(map, dps); }
Example 18
Source File: JobExecutionResponse.java From FHIR with Apache License 2.0 | 4 votes |
public static JobExecutionResponse parse(InputStream in) throws FHIROperationException { try (JsonReader jsonReader = JSON_READER_FACTORY.createReader(in, StandardCharsets.UTF_8)) { JsonObject jsonObject = jsonReader.readObject(); JobExecutionResponse.Builder builder = JobExecutionResponse.builder(); if (jsonObject.containsKey("jobName")) { String jobName = jsonObject.getString("jobName"); builder.jobName(jobName); } if (jsonObject.containsKey("instanceId")) { Integer instanceId = jsonObject.getInt("instanceId"); builder.instanceId(instanceId); } if (jsonObject.containsKey("appName")) { String appName = jsonObject.getString("appName"); builder.appName(appName); } if (jsonObject.containsKey("batchStatus")) { String batchStatus = jsonObject.getString("batchStatus"); builder.batchStatus(batchStatus); } if (jsonObject.containsKey("exitStatus")) { String exitStatus = jsonObject.getString("exitStatus"); builder.exitStatus(exitStatus); } if (jsonObject.containsKey("jobXMLName")) { String jobXMLName = jsonObject.getString("jobXMLName"); builder.jobXMLName(jobXMLName); } if (jsonObject.containsKey("instanceName")) { String instanceName = jsonObject.getString("instanceName"); builder.instanceName(instanceName); } if (jsonObject.containsKey("lastUpdatedTime")) { String lastUpdatedTime = jsonObject.getString("lastUpdatedTime"); builder.lastUpdatedTime(lastUpdatedTime); } if (jsonObject.containsKey("_links")) { JsonArray arr = jsonObject.getJsonArray("_links"); ListIterator<JsonValue> iter = arr.listIterator(); while (iter.hasNext()) { JsonValue v = iter.next(); JsonObject vObj = v.asJsonObject(); if (vObj.containsKey("rel") && vObj.containsKey("href")) { String rel = vObj.getString("rel"); String href = vObj.getString("href"); builder.link(rel, href); } } } if (jsonObject.containsKey("submitter")) { String submitter = jsonObject.getString("submitter"); builder.submitter(submitter); } if (jsonObject.containsKey("instanceState")) { String instanceState = jsonObject.getString("instanceState"); builder.instanceState(instanceState); } if (jsonObject.containsKey("jobParameters")) { JsonObject obj = jsonObject.getJsonObject("jobParameters"); JobParameter.Parser.parse(builder, obj); } return builder.build(); } catch (Exception e) { throw new FHIROperationException("Problem parsing the Bulk Export Job's response from the server", e); } }
Example 19
Source File: OrderInfo.java From scalable-coffee-shop with Apache License 2.0 | 4 votes |
public OrderInfo(JsonObject jsonObject) { this(UUID.fromString(jsonObject.getString("orderId")), CoffeeType.fromString(jsonObject.getString("type")), jsonObject.getString("beanOrigin")); }
Example 20
Source File: LoginResourceTest.java From sample-acmegifts with Eclipse Public License 1.0 | 4 votes |
/** Tests the login function with a JWT in the wrong group. We should not be able to log in. */ @Test public void testLoginWrongJwtGroup() throws Exception { // Add a user. String loginAuthHeader = "Bearer " + new JWTVerifier() .createJWT("unauthenticated", new HashSet<String>(Arrays.asList("login"))); User user = new User(null, "Niels", "Bohr", "nBohr", "@nBohr", "nBohrWishListLink", "myPassword"); Response response = processRequest(userServiceURL, "POST", user.getJson(), loginAuthHeader); assertEquals( "HTTP response code should have been " + Status.OK.getStatusCode() + ".", Status.OK.getStatusCode(), response.getStatus()); String authHeader = response.getHeaderString("Authorization"); new JWTVerifier().validateJWT(authHeader); JsonObject responseJson = toJsonObj(response.readEntity(String.class)); String dbId = responseJson.getString(User.JSON_KEY_USER_ID); user.setId(dbId); // Find user in the database. BasicDBObject dbUser = (BasicDBObject) database.getCollection("users").findOne(new ObjectId(dbId)); assertTrue("User rFeynman was NOT found in database.", dbUser != null); assertTrue("User rFeynman does not contain expected data.", user.isEqual(dbUser)); // Test 1: Login user. JsonObjectBuilder loginPayload = Json.createObjectBuilder(); loginPayload.add(User.JSON_KEY_USER_NAME, user.userName); loginPayload.add(User.JSON_KEY_USER_PASSWORD, user.password); // Use the JWT that we got back from the logged-in use to log in a new user. // This should not succeed. response = processRequest(userServiceLoginURL, "POST", loginPayload.build().toString(), authHeader); assertEquals( "HTTP response code should have been " + Status.UNAUTHORIZED.getStatusCode() + ".", Status.UNAUTHORIZED.getStatusCode(), response.getStatus()); }