List of usage examples for com.fasterxml.jackson.databind JsonNode textValue
public String textValue()
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public Registration requestRegistrationAS() throws IOException { String clientName = "opPostmanTestRS"; // CLIENT_NAME_PREFIX + // System.currentTimeMillis(); String clientCredentials = "client_credentials"; String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\"" + clientCredentials + "\"], \"id_token_signed_response_alg\":\"" + "HS256" + "\"}"; // Registration URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AS); HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection(); httpConRegistration.setDoOutput(true); httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConRegistration.setRequestProperty("Content-Type", "application/json"); httpConRegistration.setRequestProperty("Accept", "application/json"); httpConRegistration.setRequestMethod("POST"); OutputStream outRegistration = httpConRegistration.getOutputStream(); outRegistration.write(requestBodyRegistration.getBytes()); outRegistration.close();/*from ww w . j a va 2 s . c o m*/ int responseCodeRegistration = httpConRegistration.getResponseCode(); log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration); if (responseCodeRegistration == 201) { // everything ok InputStream isR = httpConRegistration.getInputStream(); byte[] bisR = getBytesFromInputStream(isR); String jsonResponseRegistration = new String(bisR); log.info(jsonResponseRegistration); // extract the value of client_id (this value is called <c_id>in // the following) and the value of client_secret (called // <c_secret> in the following) from the JSON response ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisR); JsonNode actualObj = mapper.readTree(jp); JsonNode c_id = actualObj.get("client_id"); JsonNode c_secret = actualObj.get("client_secret"); if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null || c_secret.getNodeType() != JsonNodeType.STRING) { log.error("client_id: " + c_id); log.error("client_secret: " + c_secret); } else { // ok so far // Store <c_id> and <c_secret> for use during the token // acquisition log.info("client_id: " + c_id); log.info("client_secret: " + c_secret); return new Registration(c_id.textValue(), c_secret.textValue()); } } else { // error InputStream error = httpConRegistration.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConRegistration.disconnect(); return null; }
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public Registration requestRegistrationAM() throws IOException { Registration registration = null;/* w w w .ja va 2 s. c o m*/ String clientName = CLIENT_NAME_PREFIX + System.currentTimeMillis(); String clientCredentials = "client_credentials"; String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\"" + clientCredentials + "\"]}"; // Registration URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AM); HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection(); httpConRegistration.setDoOutput(true); httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConRegistration.setRequestProperty("Content-Type", "application/json"); httpConRegistration.setRequestProperty("Accept", "application/json"); httpConRegistration.setRequestMethod("POST"); OutputStream outRegistration = httpConRegistration.getOutputStream(); outRegistration.write(requestBodyRegistration.getBytes()); outRegistration.close(); int responseCodeRegistration = httpConRegistration.getResponseCode(); log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration); if (responseCodeRegistration == 201) { // everything ok InputStream isR = httpConRegistration.getInputStream(); byte[] bisR = getBytesFromInputStream(isR); String jsonResponseRegistration = new String(bisR); log.info(jsonResponseRegistration); // extract the value of client_id (this value is called <c_id>in // the following) and the value of client_secret (called // <c_secret> in the following) from the JSON response ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisR); JsonNode actualObj = mapper.readTree(jp); JsonNode c_id = actualObj.get("client_id"); JsonNode c_secret = actualObj.get("client_secret"); if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null || c_secret.getNodeType() != JsonNodeType.STRING) { log.error("client_id: " + c_id); log.error("client_secret: " + c_secret); } else { // ok so far // Store <c_id> and <c_secret> for use during the token // acquisition log.info("client_id: " + c_id); log.info("client_secret: " + c_secret); registration = new Registration(c_id.textValue(), c_secret.textValue()); } } else { // error InputStream error = httpConRegistration.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConRegistration.disconnect(); return registration; }
From source file:com.okta.swagger.codegen.AbstractOktaJavaClientCodegen.java
private void handleOktaLinkedOperations(Swagger swagger) { // we want to move any operations defined by the 'x-okta-operations' or 'x-okta-crud' vendor extension to the model Map<String, Model> modelMap = swagger.getDefinitions().entrySet().stream() .filter(e -> e.getValue().getVendorExtensions().containsKey("x-okta-operations") || e.getValue().getVendorExtensions().containsKey("x-okta-crud")) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); modelMap.forEach((k, model) -> {/* ww w. j a v a 2 s .c o m*/ List<ObjectNode> linkNodes = new ArrayList<>(); addAllIfNotNull(linkNodes, (List<ObjectNode>) model.getVendorExtensions().get("x-okta-operations")); addAllIfNotNull(linkNodes, (List<ObjectNode>) model.getVendorExtensions().get("x-okta-crud")); Map<String, CodegenOperation> operationMap = new HashMap<>(); linkNodes.forEach(n -> { String operationId = n.get("operationId").textValue(); // find the swagger path operation swagger.getPaths().forEach((pathName, path) -> { Optional<Map.Entry<HttpMethod, Operation>> operationEntry = path.getOperationMap().entrySet() .stream().filter(e -> e.getValue().getOperationId().equals(operationId)).findFirst(); if (operationEntry.isPresent()) { Operation operation = operationEntry.get().getValue(); CodegenOperation cgOperation = fromOperation(pathName, operationEntry.get().getKey().name().toLowerCase(), operation, swagger.getDefinitions(), swagger); boolean canLinkMethod = true; JsonNode aliasNode = n.get("alias"); if (aliasNode != null) { String alias = aliasNode.textValue(); cgOperation.vendorExtensions.put("alias", alias); if ("update".equals(alias)) { model.getVendorExtensions().put("saveable", true); } else if ("delete".equals(alias)) { model.getVendorExtensions().put("deletable", true); cgOperation.vendorExtensions.put("selfDelete", true); } else if ("read".equals(alias) || "create".equals(alias)) { canLinkMethod = false; } } // we do NOT link read or create methods, those need to be on the parent object if (canLinkMethod) { // now any params that match the models we need to use the model value directly // for example if the path contained {id} we would call getId() instead Map<String, String> argMap = createArgMap(n); List<CodegenParameter> cgOtherPathParamList = new ArrayList<>(); List<CodegenParameter> cgParamAllList = new ArrayList<>(); List<CodegenParameter> cgParamModelList = new ArrayList<>(); cgOperation.pathParams.forEach(param -> { if (argMap.containsKey(param.paramName)) { String paramName = argMap.get(param.paramName); cgParamModelList.add(param); if (model.getProperties() != null) { CodegenProperty cgProperty = fromProperty(paramName, model.getProperties().get(paramName)); param.vendorExtensions.put("fromModel", cgProperty); } else { System.err.println("Model '" + model.getTitle() + "' has no properties"); } } else { cgOtherPathParamList.add(param); } }); // remove the body param if the body is the object itself for (Iterator<CodegenParameter> iter = cgOperation.bodyParams.iterator(); iter .hasNext();) { CodegenParameter bodyParam = iter.next(); if (argMap.containsKey(bodyParam.paramName)) { cgOperation.vendorExtensions.put("bodyIsSelf", true); iter.remove(); } } // do not add the parrent path params to the list (they will be parsed from the href) SortedSet<String> pathParents = parentPathParams(n); cgOtherPathParamList.forEach(param -> { if (!pathParents.contains(param.paramName)) { cgParamAllList.add(param); } }); if (!pathParents.isEmpty()) { cgOperation.vendorExtensions.put("hasPathParents", true); cgOperation.vendorExtensions.put("pathParents", pathParents); } cgParamAllList.addAll(cgOperation.queryParams); cgParamAllList.addAll(cgOperation.bodyParams); // set all params to have more cgParamAllList.forEach(param -> param.hasMore = true); // then grab the last one and mark it as the last if (!cgParamAllList.isEmpty()) { CodegenParameter param = cgParamAllList.get(cgParamAllList.size() - 1); param.hasMore = false; } cgOperation.vendorExtensions.put("allParams", cgParamAllList); cgOperation.vendorExtensions.put("fromModelPathParams", cgParamModelList); addOptionalExtension(cgOperation, cgParamAllList); operationMap.put(cgOperation.operationId, cgOperation); // mark the operation as moved so we do NOT add it to the client operation.getVendorExtensions().put("moved", true); } } }); }); model.getVendorExtensions().put("operations", operationMap.values()); }); }
From source file:com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.JsonRenderedValueConverter.java
@Override public Object convertRenderedValue(String rendered) { if (NumberUtils.isNumber(rendered)) { if (rendered.contains(".")) { return NumberUtils.createDouble(rendered); }/*from www . j a va 2s .c o m*/ try { return NumberUtils.createInteger(rendered); } catch (NumberFormatException ignored) { return NumberUtils.createLong(rendered); } } else if (rendered.equals("true") || rendered.equals("false")) { return Boolean.parseBoolean(rendered); } else if (rendered.startsWith("{{") || (!rendered.startsWith("{") && !rendered.startsWith("["))) { return rendered; } JsonNode node; try { node = pipelineTemplateObjectMapper.readTree(rendered); } catch (IOException e) { throw new TemplateRenderException("template produced invalid json", e); } try { if (node.isArray()) { return pipelineTemplateObjectMapper.readValue(rendered, Collection.class); } if (node.isObject()) { return pipelineTemplateObjectMapper.readValue(rendered, HashMap.class); } if (node.isBoolean()) { return Boolean.parseBoolean(node.asText()); } if (node.isDouble()) { return node.doubleValue(); } if (node.canConvertToInt()) { return node.intValue(); } if (node.canConvertToLong()) { return node.longValue(); } if (node.isTextual()) { return node.textValue(); } if (node.isNull()) { return null; } } catch (IOException e) { throw new TemplateRenderException("template produced invalid json", e); } throw new TemplateRenderException("unknown rendered object type"); }
From source file:org.level28.android.moca.json.TwitterSearchDeserializer.java
/** * Deserialize a JSON search result from the given {@link InputStream}. * //from w w w. j av a 2 s .com * @param in * the input stream from which the JSON document should be parsed * @return a list of results with relevant search metadata * @throws JsonDeserializerException * if the JSON document is invalid */ @Override public TwitterSearchReply fromInputStream(InputStream in) throws JsonDeserializerException { JsonNode root; try { root = sJsonMapper.readTree(in); } catch (IOException e) { throw new JsonDeserializerException("Internal Jackson error: " + e.getMessage(), e); } // Root should be an object if (!root.isObject()) { throw new JsonDeserializerException("Root JsonNode is not an object!"); } JsonNode node, resultsArray; TwitterSearchReply reply = new TwitterSearchReply(); // Get all required attributes starting with the all-important results // array resultsArray = root.path("results"); if (resultsArray.isMissingNode() || !resultsArray.isArray()) { throw new JsonDeserializerException("Invalid search reply (results missing or not an array)"); } // We'll get to results deserialization later, continue to hunt down // required search reply fields // Original query (not really needed, just checked for sanity reasons) node = root.path("query"); if (node.isMissingNode() || !node.isTextual()) { throw new JsonDeserializerException("'query' missing or invalid"); } reply.setQuery(node.textValue()); // Refresh url for this query node = root.path("refresh_url"); if (node.isMissingNode() || !node.isTextual()) { throw new JsonDeserializerException("'refresh_url' missing or invalid"); } reply.setRefreshUrl(node.textValue()); // Maximum tweet id node = root.path("max_id"); if (node.isMissingNode() || !node.canConvertToLong()) { throw new JsonDeserializerException("'max_id' missing or invalid"); } reply.setMaxId(node.asLong()); // Starting tweet id node = root.path("since_id"); if (node.isMissingNode() || !node.canConvertToLong()) { throw new JsonDeserializerException("'since_id' missing or invalid"); } reply.setSinceId(node.asLong()); // Results per page node = root.path("results_per_page"); if (node.isMissingNode() || !node.isInt()) { throw new JsonDeserializerException("'results_per_page' missing or invalid"); } reply.setResultsPerPage(node.intValue()); // Current page node = root.path("page"); if (node.isMissingNode() || !node.isInt()) { throw new JsonDeserializerException("'page' missing or invalid"); } reply.setPage(node.intValue()); // Parse all results ArrayList<Tweet> tweets = Lists.newArrayList(); for (JsonNode child : resultsArray) { tweets.add(parseSingleTweet(child)); } reply.setResults(tweets); // Go for optional and low-priority attributes reply.setCompletedIn(root.path("completed_in").asDouble(666.0)); reply.setNextPage(root.path("next_page").textValue()); // Aaaaand we're done :-) return reply; }
From source file:com.ning.metrics.action.hdfs.data.JsonNodeComparable.java
@Override public int compareTo(Object o) { JsonNode thing = (JsonNode) o; if (isMissingNode() && !thing.isMissingNode()) { return -1; } else if (!isMissingNode() && thing.isMissingNode()) { return 1; }//from w w w .j a va2s . c o m int mySize = 0; Iterator<JsonNode> myIterator = elements(); while (myIterator.hasNext()) { mySize++; } int hisSize = 0; Iterator<JsonNode> hisIterator = thing.elements(); while (hisIterator.hasNext()) { hisSize++; } if (mySize != 0 || hisSize != 0) { if (mySize > hisSize) { return 1; } else if (mySize < hisSize) { return -1; } } // Looks like both nodes don't have children if (isValueNode() && thing.isValueNode()) { return textValue().compareTo(thing.textValue()); } else { if (equals(thing)) { return 0; } else { // Weak. When do we come here? return toString().compareTo(thing.toString()); } } }
From source file:com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.HandlebarsRenderer.java
@Override public Object renderGraph(String template, RenderContext context) { String rendered = render(template, context); // Short-circuit primitive values. // TODO rz - having trouble getting jackson to parse primitive values outside of unit tests if (NumberUtils.isNumber(rendered)) { if (rendered.contains(".")) { return NumberUtils.createDouble(rendered); }/*from w w w . ja v a 2 s .co m*/ try { return NumberUtils.createInteger(rendered); } catch (NumberFormatException ignored) { return NumberUtils.createLong(rendered); } } else if (rendered.equals("true") || rendered.equals("false")) { return Boolean.parseBoolean(rendered); } else if (!rendered.startsWith("{") && !rendered.startsWith("[")) { return rendered; } JsonNode node; try { node = pipelineTemplateObjectMapper.readTree(rendered); } catch (IOException e) { throw new TemplateRenderException("template produced invalid json", e); } try { if (node.isArray()) { return pipelineTemplateObjectMapper.readValue(rendered, Collection.class); } if (node.isObject()) { return pipelineTemplateObjectMapper.readValue(rendered, HashMap.class); } if (node.isBoolean()) { return Boolean.parseBoolean(node.asText()); } if (node.isDouble()) { return node.doubleValue(); } if (node.canConvertToInt()) { return node.intValue(); } if (node.canConvertToLong()) { return node.longValue(); } if (node.isTextual()) { return node.textValue(); } if (node.isNull()) { return null; } } catch (IOException e) { throw new TemplateRenderException("template produced invalid json", e); } throw new TemplateRenderException("unknown rendered object type"); }
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public String requestASToken(Registration registration, String[] adds) throws IOException { String asToken = null;/*from w w w .jav a2 s .com*/ // Token Acquisition // Create a HTTP request as in the following prototype and send // it via TLS to the AM // // Token Acquisition // Create a HTTP request as in the following prototype and send // it via TLS to the AM // Request // POST /iam-services/0.1/oidc/am/token HTTP/1.1 URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION); HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection(); httpConTokenAcquisition.setDoOutput(true); httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConTokenAcquisition.setRequestProperty("Accept", "application/json"); // httpConTokenAcquisition.setRequestProperty("Authorization", // "Basic Base64(<c_id>:<c_secret>"); String auth = registration.c_id + ":" + registration.c_secret; String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes())); httpConTokenAcquisition.setRequestProperty("Authorization", authb); httpConTokenAcquisition.setRequestMethod("POST"); String requestBodyTokenAcquisition = "grant_type=client_credentials"; if (adds == null || adds.length == 0) { // no additions } else { if (adds.length % 2 == 0) { for (int i = 0; i < (adds.length - 1); i += 2) { requestBodyTokenAcquisition += "&"; requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8"); requestBodyTokenAcquisition += "="; requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8"); } } else { log.warn( "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds)); } } OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream(); outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes()); outTokenAcquisition.close(); int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode(); log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": " + responseCodeoutTokenAcquisition); if (responseCodeoutTokenAcquisition == 200) { // everything ok InputStream isTA = httpConTokenAcquisition.getInputStream(); byte[] bisTA = getBytesFromInputStream(isTA); String jsonResponseTA = new String(bisTA); log.info(jsonResponseTA); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisTA); JsonNode actualObj = mapper.readTree(jp); JsonNode access_token = actualObj.get("access_token"); if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) { log.error("access_token: " + access_token); } else { // ok so far // access_token provides a JWT structure // see Understanding JWT // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html log.info("access_token: " + access_token); // http://jwt.io/ // TODO verify signature (e.g., use Jose4J) // Note: currently we assume signature is fine.. we just fetch // "as_token" String[] decAT = access_token.textValue().split("\\."); if (decAT == null || decAT.length != 3) { log.error("Cannot build JWT tripple structure for " + access_token); } else { assert (decAT.length == 3); // JWT structure // decAT[0]; // header // decAT[1]; // payload // decAT[2]; // signature String decAT1 = new String(Base64.getDecoder().decode(decAT[1])); JsonParser jpas = factory.createParser(decAT1); JsonNode payload = mapper.readTree(jpas); JsonNode as_token = payload.get("as_token"); if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) { log.error("as_token: " + as_token); } else { log.info("as_token: " + as_token); asToken = as_token.textValue(); } } } } else { // error InputStream error = httpConTokenAcquisition.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConTokenAcquisition.disconnect(); return asToken; }
From source file:com.unboundid.scim2.common.messages.PatchOperation.java
private void addSchemaUrnIfMissing(final ArrayNode schemas, final String schemaUrn) { for (JsonNode node : schemas) { if (node.isTextual() && node.textValue().equalsIgnoreCase(schemaUrn)) { return; }/*from w w w . j a va2s .co m*/ } schemas.add(schemaUrn); }
From source file:com.alliander.osgp.shared.usermanagement.KeycloakClient.java
private String determineSessionIdWithLoginClient(final ArrayNode sessionRepresentationArray) { final Iterator<JsonNode> elements = sessionRepresentationArray.elements(); final boolean sessionFound = false; while (!sessionFound && elements.hasNext()) { final JsonNode sessionRepresentation = elements.next(); final JsonNode sessionId = sessionRepresentation.get("id"); if (sessionId == null || !sessionId.isTextual()) { LOGGER.warn("sessionId is not a JSON text node for a user session"); continue; }// ww w . j a v a 2 s .c o m final JsonNode clients = sessionRepresentation.get("clients"); if (clients == null || !clients.isObject()) { LOGGER.warn("clients is not a JSON object node for a user session"); continue; } if (this.useSessionIdForClients(clients)) { return sessionId.textValue(); } } return null; }