List of usage examples for javax.json JsonObject getString
String getString(String name);
From source file:joachimeichborn.geotag.geocode.GoogleGeocoder.java
private String getStatus(final JsonObject aJsonRepresentation) { if (aJsonRepresentation == null || !aJsonRepresentation.containsKey(STATUS_KEY)) { logger.fine("JSON status cannot be obtained"); return ""; }/* w w w . j a v a2 s . c o m*/ return aJsonRepresentation.getString(STATUS_KEY); }
From source file:org.hyperledger.fabric_ca.sdk.HFCAIdentity.java
HFCAIdentity(JsonObject result) { this.enrollmentID = result.getString("id"); getHFCAIdentity(result); }
From source file:org.fuin.esc.eshttp.ESHttpJsonUnmarshaller.java
@Override public final Object unmarshal(final DeserializerRegistry registry, final SerializedDataType dataType, final EnhancedMimeType mimeType, final Object data) { if (data == null) { return null; }/*from w ww. ja v a 2s . c om*/ if (!(data instanceof JsonObject)) { throw new IllegalArgumentException( "Can only unmarshal JsonObject, but was: " + data + " [" + data.getClass().getName() + "]"); } final JsonObject jsonObj = (JsonObject) data; final String transferEncodingData = mimeType.getParameter("transfer-encoding"); if (transferEncodingData == null) { // JSON Object or Array final Deserializer deSer = registry.getDeserializer(dataType, mimeType); return deSer.unmarshal(jsonObj, mimeType); } final String base64str = jsonObj.getString(Base64Data.EL_ROOT_NAME); final byte[] bytes = Base64.decodeBase64(base64str); final Deserializer deSer = registry.getDeserializer(dataType, mimeType); return deSer.unmarshal(bytes, mimeType); }
From source file:net.e2.bw.idreg.client.keycloak.KeycloakClient.java
/** * Parses the JSON token received from the auth server upon issuing a token request. * The retuned token should contain the fields defined in section 2.1.6.2 of the specification. * * @param token the JSON token to parse// w w w . ja v a2s. c om * @return the parsed JSON token */ private AccessTokenData parseAndValidateTokenResponse(String token) throws AuthErrorException { // Parse the JSON result try (JsonReader rdr = Json.createReader(new StringReader(token))) { JsonObject json = rdr.readObject(); // Validate toke type String tokenType = json.getString("token_type"); if (!"bearer".equalsIgnoreCase(tokenType)) { throw new AuthErrorException("Invalid token type: " + tokenType); } // TODO: Validate various fields of ID token //JsonObject idToken = json.getJsonObject("id_token"); // Get user info from access token String accessToken = json.getString("access_token"); try { // Check that signature is valid upon parsing the JWT token Claims claims = Jwts.parser().setSigningKey(config.getPublicKey()).parseClaimsJws(accessToken) .getBody(); // Validate the JWT fields if (!config.getIssuer().equals(claims.getIssuer())) { throw new AuthErrorException("Invalid access token issuer " + claims.getIssuer()); } if (!config.getClientId().equals(claims.getAudience())) { throw new AuthErrorException("Invalid access token audience " + claims.getIssuer()); } if (claims.getExpiration().before(new Date())) { throw new AuthErrorException("JWT token expired at " + claims.getExpiration()); } // Read out user info AccessTokenData data = new AccessTokenData(); data.setName(toString(claims.get("name"))); data.setUserName(toString(claims.get("preferred_username"))); data.setEmail(toString(claims.get("email"))); data.setGivenName(toString(claims.get("given_name"))); data.setFamilyName(toString(claims.get("family_name"))); // Keycloak-specific roles encoding addRoles(data.getRealmRoles(), claims.get("realm_access")); if (claims.get("resource_access") != null) { addRoles(data.getResourceRoles(), ((Map) claims.get("resource_access")).get(config.getClientId())); } // Read out custom claims if (customClaims != null) { Arrays.stream(customClaims).filter(claims::containsKey) .forEach(c -> data.getCustomClaims().put(c, claims.get(c))); } return data; } catch (AuthErrorException ae) { throw ae; } catch (SignatureException se) { throw new AuthErrorException("Access token has invalid signature", se); } catch (Exception e) { throw new AuthErrorException("Error parsing access token", e); } } }
From source file:eu.forgetit.middleware.component.Condensator.java
public void imageClustering_bkp(Exchange exchange) { logger.debug("New message retrieved"); JsonObject headers = MessageTools.getHeaders(exchange); long taskId = headers.getInt("taskId"); scheduler.updateTask(taskId, TaskStatus.RUNNING, "IMAGE CLUSTERING", null); MessageTools.setHeaders(exchange, headers); JsonObject jsonBody = MessageTools.getBody(exchange); if (jsonBody != null) { try {// w ww .j av a2 s .com String jsonNofImagesElement = jsonBody.getString("numOfImages"); String minCLusteringImages = headers.getString("minClusteringImages"); int nofImages = 0; int minNofImages = 0; if (jsonNofImagesElement != null) nofImages = Integer.parseInt(jsonNofImagesElement); if (minCLusteringImages != null) minNofImages = Integer.parseInt(minCLusteringImages); else minNofImages = 0; String jsonImageAnalysisResult = jsonBody.getString("imageAnalysis-all"); if (jsonImageAnalysisResult != null) imageAnalysisResult = jsonImageAnalysisResult; logger.debug("Retrieved Image Analysis Result: " + imageAnalysisResult); String jsonMetadataDir = jsonBody.getString("sipMetadataDir"); if (jsonMetadataDir != null) sipMetadataDirPath = jsonMetadataDir; logger.debug("Retrieved SIP Metadata Directory: " + sipMetadataDirPath); if (nofImages >= minNofImages) { logger.debug("Executing Image Collection Clustering"); String response = service.request(imageAnalysisResult); logger.debug("Clustering result:\n" + response); File resultFile = new File(sipMetadataDirPath, "clustering.xml"); FileUtils.writeStringToFile(resultFile, response); JsonObjectBuilder job = Json.createObjectBuilder(); job.add("clustering", resultFile.getAbsolutePath()); for (Entry<String, JsonValue> entry : jsonBody.entrySet()) { job.add(entry.getKey(), entry.getValue()); } exchange.getIn().setBody(jsonBody.toString()); } else { logger.debug("Found only " + nofImages + " images, below threshold (" + minCLusteringImages + ")... skipping."); } } catch (NumberFormatException | IOException e) { e.printStackTrace(); } } else { JsonObjectBuilder job = Json.createObjectBuilder().add("taskStatus", TaskStatus.FAILED.toString()); for (Entry<String, JsonValue> entry : headers.entrySet()) { job.add(entry.getKey(), entry.getValue()); } MessageTools.setHeaders(exchange, headers); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAIdentity.java
private void getHFCAIdentity(JsonObject result) { type = result.getString("type"); if (result.containsKey("secret")) { this.secret = result.getString("secret"); }/*from w w w . j a va2s .c o m*/ maxEnrollments = result.getInt("max_enrollments"); affiliation = result.getString("affiliation"); JsonArray attributes = result.getJsonArray("attrs"); Collection<Attribute> attrs = new ArrayList<Attribute>(); if (attributes != null && !attributes.isEmpty()) { for (int i = 0; i < attributes.size(); i++) { JsonObject attribute = attributes.getJsonObject(i); Attribute attr = new Attribute(attribute.getString("name"), attribute.getString("value"), attribute.getBoolean("ecert", false)); attrs.add(attr); } } this.attrs = attrs; }
From source file:eu.forgetit.middleware.component.Contextualizer.java
public void testImageContextualization(Exchange exchange) throws ExecutionException { System.out.println("New message retrieved"); JsonObject jsonBody = MessageTools.getBody(exchange); if (jsonBody != null) { String userimg = jsonBody.getString("userimg"); System.out.println("Retrieved User image collection: " + userimg); String event = jsonBody.getString("event"); System.out.println("Retrieved event name: " + event); String location = jsonBody.getString("location"); System.out.println("Retrieved location of the event: " + location); String year = jsonBody.getString("year"); System.out.println("Retrieved year of the event: " + year); // ONE video per call if (userimg != null && !userimg.isEmpty()) { if (event != null && !event.isEmpty() && location != null && !location.isEmpty() && year != null && !year.isEmpty()) { System.out.println("Executing image contextualization for user image collection: " + userimg); String response = service.imgcontextual_request(userimg, event, location, year); System.out.println( "Image contextualization method for event: " + event + " result:\n" + response); } else { System.out.println("Unable to process textual information, wrong request"); }/*from w w w . ja v a2 s . co m*/ } else { System.out.println("Unable to process image collection, wrong request"); } } }
From source file:joachimeichborn.geotag.geocode.GoogleGeocoder.java
private String getMatchingContent(final String aAttribute, final JsonArray aResults, final LocationType... aLocationTypes) { for (final LocationType locationType : aLocationTypes) { for (final JsonObject component : aResults.getValuesAs(JsonObject.class)) { final JsonArray types = component.getJsonArray(TYPES_KEY); if (types.containsAll(locationType.getIdentifiers()) && component.containsKey(aAttribute)) { return component.getString(aAttribute); }/* w ww . ja v a2 s . co m*/ } } return null; }
From source file:info.dolezel.jarss.rest.v1.ws.UnreadNotificationEndpoint.java
@OnWebSocketMessage public void onMessage(Session session, String text) { EntityManager em = null;//from w w w.jav a2 s .co m EntityTransaction tx = null; try { JsonReader reader; JsonObject object; Token token; em = HibernateUtil.getEntityManager(); tx = em.getTransaction(); tx.begin(); reader = Json.createReader(new StringReader(text)); object = reader.readObject(); token = Token.loadToken(em, object.getString("token")); if (token == null) { tx.rollback(); Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.WARNING, "Invalid token provided over WebSocket"); session.close(); } else { synchronized (sessions) { sessions.put(session, token.getUser()); } synchronized (userSessions) { userSessions.put(token.getUser(), session); } } tx.commit(); } catch (Exception ex) { if (tx != null) tx.rollback(); Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.SEVERE, "Error processing incoming WebSocket message", ex); } finally { if (em != null) em.close(); } }
From source file:io.bibleget.VersionsSelect.java
public VersionsSelect() throws ClassNotFoundException { biblegetDB = BibleGetDB.getInstance(); String bibleVersionsStr = biblegetDB.getMetaData("VERSIONS"); JsonReader jsonReader = Json.createReader(new StringReader(bibleVersionsStr)); JsonObject bibleVersionsObj = jsonReader.readObject(); Set<String> versionsabbrev = bibleVersionsObj.keySet(); bibleVersions = new BasicEventList<>(); if (!versionsabbrev.isEmpty()) { for (String s : versionsabbrev) { String versionStr = bibleVersionsObj.getString(s); //store these in an array String[] array;/*from w ww.j a v a2 s .c o m*/ array = versionStr.split("\\|"); bibleVersions.add(new BibleVersion(s, array[0], array[1], StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage()))); } } versionsByLang = new SeparatorList<>(bibleVersions, new VersionComparator(), 1, 1000); int listLength = versionsByLang.size(); enabledFlags = new boolean[listLength]; ListIterator itr = versionsByLang.listIterator(); while (itr.hasNext()) { int idx = itr.nextIndex(); Object next = itr.next(); enabledFlags[idx] = !(next.getClass().getSimpleName().equals("GroupSeparator")); if (enabledFlags[idx]) { versionCount++; } else { versionLangs++; } } this.setModel(new DefaultEventListModel<>(versionsByLang)); this.setCellRenderer(new VersionCellRenderer()); this.setSelectionModel(new DisabledItemSelectionModel()); }