List of usage examples for com.fasterxml.jackson.databind.node ObjectNode get
public JsonNode get(String paramString)
From source file:controllers.AnyplaceMapping.java
private static boolean isBuildingCoOwner(ObjectNode building, String userId) { JsonNode cws = null;/*from w ww. j av a 2s .c o m*/ if (building != null && (cws = building.get("co_owners")) != null) { Iterator<JsonNode> it = cws.elements(); while (it.hasNext()) { if (it.next().textValue().equals(userId)) { return true; } } } return false; }
From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java
/** * Refresh the access token using the refresh token the tokens in provided * authorization object will be updated//www . j a v a2 s .co m * * @param auth * @throws Exception */ private void refreshAuthorization(final Authorization auth) throws Exception { final String refresh_token = (auth != null) ? auth.getRefreshToken() : null; if (refresh_token == null) { throw new Exception("No refresh token available"); } final Config config = getAgentHost().getConfig(); final String client_id = config.get("google", "client_id"); final String client_secret = config.get("google", "client_secret"); // retrieve new access_token using the refresh_token final Map<String, String> params = new HashMap<String, String>(); params.put("client_id", client_id); params.put("client_secret", client_secret); params.put("refresh_token", refresh_token); params.put("grant_type", "refresh_token"); final String resp = HttpUtil.postForm(OAUTH_URI + "/token", params); final ObjectNode json = JOM.getInstance().readValue(resp, ObjectNode.class); if (!json.has("access_token")) { // TODO: give more specific error message throw new Exception("Retrieving new access token failed"); } // update authorization if (json.has("access_token")) { auth.setAccessToken(json.get("access_token").asText()); } if (json.has("expires_in")) { final Integer expires_in = json.get("expires_in").asInt(); final DateTime expires_at = calculateExpiresAt(expires_in); auth.setExpiresAt(expires_at); } }
From source file:com.unboundid.scim2.server.utils.SchemaChecker.java
/** * Remove any read-only attributes and/or sub-attributes that are present in * the provided SCIM resource. This should be performed on new and * replacement SCIM resources before schema checking since read-only * attributes should be ignored by the service provider on create with POST * and modify with PUT operations./*from w w w .j av a2 s.c o m*/ * * @param objectNode The SCIM resource to remove read-only attributes from. * This method will not alter the provided resource. * @return The new SCIM resource with the read-only attributes (if any) * removed. */ public ObjectNode removeReadOnlyAttributes(final ObjectNode objectNode) { ObjectNode copyNode = objectNode.deepCopy(); for (SchemaResource schemaExtension : resourceType.getSchemaExtensions().keySet()) { JsonNode extension = copyNode.get(schemaExtension.getId()); if (extension != null && extension.isObject()) { removeReadOnlyAttributes(schemaExtension.getAttributes(), (ObjectNode) extension); } } removeReadOnlyAttributes(commonAndCoreAttributes, copyNode); return copyNode; }
From source file:com.delphix.delphix.DelphixEngine.java
/** * Provision a VDB either a semantic point or a snapshot with the name of the new VDB being optional *//*ww w . jav a2 s .co m*/ @SuppressWarnings("unchecked") public String provisionVDB(String containerRef, String snapshotRef, String containerName, String repositoryRef, String mountBase) throws IOException, DelphixEngineException { String defaultParams = ""; if (snapshotRef.equals(CONTENT_LATEST_POINT) || snapshotRef.equals(CONTENT_LATEST_SNAPSHOT)) { defaultParams = getProvisionDefaultsContainer(containerRef, snapshotRef); } else { defaultParams = getProvisionDefaultsSnapshot(snapshotRef); } // Strip out null values from provision parameters defaultParams = defaultParams.replaceAll("(\"[^\"]+\":null,?|,?\"[^\"]+\":null)", ""); JsonNode params = MAPPER.readTree(defaultParams); // Set new VDB name if it is passed if (!containerName.isEmpty()) { ObjectNode containerNode = (ObjectNode) params.get("container"); containerNode.put("name", containerName); ObjectNode sourceConfigNode = (ObjectNode) params.get("sourceConfig"); sourceConfigNode.put("databaseName", containerName); sourceConfigNode.put("uniqueName", containerName); ObjectNode instanceNode = (ObjectNode) sourceConfigNode.get("instance"); instanceNode.put("instanceName", containerName); } // Set target repository if (!repositoryRef.isEmpty() && !repositoryRef.equals("default")) { ObjectNode sourceConfig = (ObjectNode) params.get("sourceConfig"); sourceConfig.put("repository", repositoryRef); DelphixRepository repository = getRepository(repositoryRef); // Handle provisioning to RAC if (repository.getRAC()) { sourceConfig.put("type", "OracleRACConfig"); if (sourceConfig.has("instance")) { sourceConfig.remove("instance"); } ArrayNode instances = sourceConfig.putArray("instances"); ArrayList<DelphixClusterNode> clusterNodes = listClusterNodes(); int i = 1; for (DelphixClusterNode node : clusterNodes) { ObjectNode instance = MAPPER.createObjectNode(); instance.put("type", "OracleRACInstance"); instance.put("instanceNumber", i); ObjectNode containerNode = (ObjectNode) params.get("container"); instance.put("instanceName", containerNode.get("name").asText() + i); instance.put("node", node.getReference()); instances.add(instance); i++; } } } // Set the base mount point if (!mountBase.isEmpty()) { ObjectNode sourceConfig = (ObjectNode) params.get("source"); sourceConfig.put("mountBase", mountBase); } JsonNode result; ObjectNode sourceNode = (ObjectNode) params.get("source"); // Hack for RAC support if (sourceNode.has("redoLogSizeInMB")) { sourceNode.remove("redoLogSizeInMB"); } try { result = enginePOST(PATH_PROVISION, params.toString()); } catch (DelphixEngineException e) { // Handle the case where some of the fields in the defaults are read // only by removing those fields if (e.getMessage().contains("This field is read-only")) { JsonNode errors = MAPPER.readTree(e.getMessage()); List<String> list1 = IteratorUtils.toList(errors.fieldNames()); for (String field1 : list1) { List<String> list2 = IteratorUtils.toList(errors.get(field1).fieldNames()); for (String field2 : list2) { // Field1 is the outer field and field2 is the inner // field ObjectNode node = (ObjectNode) params.get(field1); // Remove the inner field node.remove(field2); } } result = enginePOST(PATH_PROVISION, params.toString()); } else { throw e; } } return result.get(FIELD_JOB).asText(); }
From source file:org.lendingclub.mercator.newrelic.NewRelicScanner.java
private void scanAlertPolicies() { Instant startTime = Instant.now(); ObjectNode alertPolicies = getNewRelicClient().getAlertPolicies(); Preconditions.checkNotNull(getProjector().getNeoRxClient(), "neorx client must be set"); String cypher = "WITH {json} as data " + "UNWIND data.policies as policy " + "MERGE ( s:NewRelicAlertPolicy { nr_policyId: toString(policy.id), nr_accountId:{accountId} } ) " + "ON CREATE SET s.name = policy.name, s.policyCreatedTs = policy.created_at, s.policyUpdatedTs = policy.updated_at, " + "s.createTs = timestamp(), s.updateTs = timestamp() " + "ON MATCH SET s.policyUpdatedTs = policy.updated_at, s.updateTs = timestamp() "; getProjector().getNeoRxClient().execCypher(cypher, "json", alertPolicies, "accountId", clientSupplier.get().getAccountId()); Instant endTime = Instant.now(); logger.info("Updating neo4j with the latest information about {} NewRelic alert policies took {} secs", alertPolicies.get("policies").size(), Duration.between(startTime, endTime).getSeconds()); }
From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java
/** * Update an existing event.//from ww w. j a v a2s .co m * * @param event * JSON structure containing the calendar event (event must have * an id) * @param calendarId * Optional calendar id. the primary calendar is used by default * @return updatedEvent JSON structure with the updated event * @throws Exception * the exception */ @Override public ObjectNode updateEvent(@Name("event") final ObjectNode event, @Optional @Name("calendarId") String calendarId) throws Exception { // initialize optional parameters if (calendarId == null) { calendarId = getState().get("email", String.class); } // convert from Eve to Google event toGoogleEvent(event); // read id from event final String id = event.get("id").asText(); if (id == null) { throw new Exception("Parameter 'id' missing in event"); } // built url final String url = CALENDAR_URI + calendarId + "/events/" + id; // perform POST request final ObjectMapper mapper = JOM.getInstance(); final String body = mapper.writeValueAsString(event); final Map<String, String> headers = getAuthorizationHeaders(); headers.put("Content-Type", "application/json"); final String resp = HttpUtil.put(url, body, headers); final ObjectNode updatedEvent = mapper.readValue(resp, ObjectNode.class); // check for errors if (updatedEvent.has("error")) { final ObjectNode error = (ObjectNode) updatedEvent.get("error"); throw new JSONRPCException(error); } // convert from Google to Eve event toEveEvent(event); return updatedEvent; }
From source file:com.attribyte.essem.DefaultResponseGenerator.java
@Override public boolean generateGraph(GraphQuery graphQuery, Response esResponse, EnumSet<Option> options, RateUnit rateUnit, HttpServletResponse response) throws IOException { ObjectNode jsonObject = mapper.readTree(parserFactory.createParser(esResponse.getBody().toByteArray())); ObjectNode responseObject = JsonNodeFactory.instance.objectNode(); List<String> fields = ImmutableList.copyOf(graphQuery.searchRequest.fields); ObjectNode targetMeta = JsonNodeFactory.instance.objectNode(); ArrayNode targetGraphs = responseObject.putArray("graphs"); if (graphQuery.range.expression != null) { targetMeta.put("range", graphQuery.range.expression); }// w w w . j av a 2 s . c o m if (graphQuery.range.startTimestamp > 0L) { targetMeta.put("rangeStartTimestamp", graphQuery.range.startTimestamp); } if (graphQuery.range.endTimestamp > 0L) { targetMeta.put("rangeEndTimestamp", graphQuery.range.endTimestamp); } JsonNode aggregations = jsonObject.get("aggregations"); if (aggregations != null && aggregations.isObject()) { ArrayNode metaFields = targetMeta.putArray("fields"); metaFields.add("timestamp"); metaFields.add("samples"); for (String field : fields) { metaFields.add(field); } if (graphQuery.downsampleInterval != null) { targetMeta.put("downsampledTo", graphQuery.downsampleInterval); } if (graphQuery.downsampleFunction != null) { targetMeta.put("downsampledWith", graphQuery.downsampleFunction); } String error = parseGraphAggregation(aggregations, fields, rateUnit, targetMeta, targetGraphs); if (error == null) { generateGraph(responseObject, response); return true; } else { response.sendError(500, error); return false; } } else { ArrayNode metaFields = targetMeta.putArray("fields"); metaFields.add("timestamp"); metaFields.add("samples"); for (String field : fields) { if (!graphIgnoreProperties.contains(field)) { metaFields.add(field); } } parseGraph(jsonObject, fields, rateUnit, targetMeta, targetGraphs); generateGraph(responseObject, response); return true; } }
From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_LibraryJars.java
@Test public void test_updateV1SourceStatus() throws JsonProcessingException, IOException, InterruptedException, ExecutionException, ParseException { @SuppressWarnings("unchecked") ICrudService<JsonNode> v1_share_db = this._service_context.getCoreManagementDbService() .getUnderlyingPlatformDriver(ICrudService.class, Optional.of("social.share")).get(); final DBCollection dbc = v1_share_db.getUnderlyingPlatformDriver(DBCollection.class, Optional.empty()) .get();//from w w w .j a v a 2 s . com v1_share_db.deleteDatastore().get(); IManagementCrudService<SharedLibraryBean> library_db = this._service_context.getCoreManagementDbService() .getSharedLibraryStore(); library_db.deleteDatastore().get(); final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty()); final ObjectNode v1_share_1 = (ObjectNode) mapper .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_share.json")); final DBObject v1_share_1_dbo = (DBObject) JSON.parse(v1_share_1.toString()); v1_share_1_dbo.put("_id", new ObjectId(v1_share_1.get("_id").asText())); assertEquals(0L, (long) v1_share_db.countObjects().get()); dbc.save(v1_share_1_dbo); //v1_share_db.storeObjects(Arrays.asList(v1_share_1)).get(); assertEquals(1L, (long) v1_share_db.countObjects().get()); final SharedLibraryBean share1 = IkanowV1SyncService_LibraryJars.getLibraryBeanFromV1Share(v1_share_1); assertEquals(0L, (long) library_db.countObjects().get()); library_db.storeObjects(Arrays.asList(share1)).get(); assertEquals(1L, (long) library_db.countObjects().get()); // No error - create { final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture( CompletableFuture.completedFuture(Unit.unit()), CompletableFuture.completedFuture(Arrays.asList(ErrorUtils.buildSuccessMessage("", "", "", ""))) // (single non error) ); final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top( "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true); assertEquals(false, res.get()); ObjectNode unchanged = (ObjectNode) v1_share_db.getRawService() .getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe")).get().get(); assertEquals(v1_share_1.without("_id").toString(), unchanged.without("_id").toString()); } // DB call throws exception { final CompletableFuture<?> error_out = new CompletableFuture<>(); error_out.completeExceptionally(new RuntimeException("test")); final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out); final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top( "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true); assertEquals(true, res.get()); JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe")) .get().get(); assertTrue(changed.get("description").asText() .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test")); // This shouldn't yet pe present assertFalse("Description error time travels: " + changed.get("description").asText(), changed.get("description").asText().contains("] (test) (unknown): ERROR: test")); } // db call throws exception, object doesn't exist (code coverage!) { final CompletableFuture<?> error_out = new CompletableFuture<>(); error_out.completeExceptionally(new RuntimeException("test")); final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out); final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top( "555d44e3347d336b3e8c4cbf", test_1, library_db, v1_share_db, true); assertEquals(false, res.get()); } // User errors (+update not create) { final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture( CompletableFuture.completedFuture(Unit.unit()), CompletableFuture.completedFuture( Arrays.asList(ErrorUtils.buildErrorMessage("test", "test", "test", "test"))) // (single non error) ); final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top( "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, false); assertEquals(true, res.get()); JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe")) .get().get(); SharedLibraryBean v2_version = library_db.getObjectById("v1_555d44e3347d336b3e8c4cbe").get().get(); assertTrue("v2 lib bean needed updating: " + v2_version.modified(), new Date().getTime() - v2_version.modified().getTime() < 5000L); // Still has the old error assertTrue("Description missing errors: " + changed.get("description").asText(), changed.get("description").asText() .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test")); // Now has the new error assertTrue("Description missing errors: " + changed.get("description").asText(), changed.get("description").asText().contains("] test (test): ERROR: test")); } }
From source file:org.xbmc.kore.jsonrpc.HostConnection.java
private <T> void handleTcpResponse(ObjectNode jsonResponse) { if (!jsonResponse.has(ApiMethod.ID_NODE)) { // It's a notification, notify observers String notificationName = jsonResponse.get(ApiNotification.METHOD_NODE).asText(); ObjectNode params = (ObjectNode) jsonResponse.get(ApiNotification.PARAMS_NODE); if (notificationName.equals(Player.OnPause.NOTIFICATION_NAME)) { final Player.OnPause apiNotification = new Player.OnPause(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override//ww w. j a va2 s. c om public void run() { observer.onPause(apiNotification); } }); } } else if (notificationName.equals(Player.OnPlay.NOTIFICATION_NAME)) { final Player.OnPlay apiNotification = new Player.OnPlay(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onPlay(apiNotification); } }); } } else if (notificationName.equals(Player.OnSeek.NOTIFICATION_NAME)) { final Player.OnSeek apiNotification = new Player.OnSeek(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onSeek(apiNotification); } }); } } else if (notificationName.equals(Player.OnSpeedChanged.NOTIFICATION_NAME)) { final Player.OnSpeedChanged apiNotification = new Player.OnSpeedChanged(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onSpeedChanged(apiNotification); } }); } } else if (notificationName.equals(Player.OnStop.NOTIFICATION_NAME)) { final Player.OnStop apiNotification = new Player.OnStop(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onStop(apiNotification); } }); } } else if (notificationName.equals(System.OnQuit.NOTIFICATION_NAME)) { final System.OnQuit apiNotification = new System.OnQuit(params); for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) { Handler handler = systemNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onQuit(apiNotification); } }); } } else if (notificationName.equals(System.OnRestart.NOTIFICATION_NAME)) { final System.OnRestart apiNotification = new System.OnRestart(params); for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) { Handler handler = systemNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onRestart(apiNotification); } }); } } else if (notificationName.equals(System.OnSleep.NOTIFICATION_NAME)) { final System.OnSleep apiNotification = new System.OnSleep(params); for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) { Handler handler = systemNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onSleep(apiNotification); } }); } } else if (notificationName.equals(Input.OnInputRequested.NOTIFICATION_NAME)) { final Input.OnInputRequested apiNotification = new Input.OnInputRequested(params); for (final InputNotificationsObserver observer : inputNotificationsObservers.keySet()) { Handler handler = inputNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onInputRequested(apiNotification); } }); } } LogUtils.LOGD(TAG, "Got a notification: " + jsonResponse.get("method").textValue()); } else { String methodId = jsonResponse.get(ApiMethod.ID_NODE).asText(); if (jsonResponse.has(ApiMethod.ERROR_NODE)) { // Error response callErrorCallback(methodId, new ApiException(ApiException.API_ERROR, jsonResponse)); } else { // Sucess response final MethodCallInfo<?> methodCallInfo = clientCallbacks.get(methodId); // LogUtils.LOGD(TAG, "Sending response to method: " + methodCallInfo.method.getMethodName()); if (methodCallInfo != null) { try { @SuppressWarnings("unchecked") final T result = (T) methodCallInfo.method.resultFromJson(jsonResponse); @SuppressWarnings("unchecked") final ApiCallback<T> callback = (ApiCallback<T>) methodCallInfo.callback; if ((methodCallInfo.handler != null) && (callback != null)) { methodCallInfo.handler.post(new Runnable() { @Override public void run() { callback.onSuccess(result); } }); } // We've replied, remove the client from the list synchronized (clientCallbacks) { clientCallbacks.remove(methodId); } } catch (ApiException e) { callErrorCallback(methodId, e); } } } } }
From source file:org.wrml.runtime.format.application.schema.json.JsonSchema.java
private void parseExtensions(final ObjectNode rootNode, final SyntaxLoader syntaxLoader) { // v3 uses the extends keyword if (rootNode.has(PropertyType.Extends.getName())) { final JsonNode extendsJsonNode = rootNode.get(PropertyType.Extends.getName()); if (extendsJsonNode instanceof ArrayNode) { final ArrayNode extendsArrayNode = (ArrayNode) extendsJsonNode; final Iterator<JsonNode> elements = extendsArrayNode.elements(); while (elements.hasNext()) { final JsonNode baseSchemaUriNode = elements.next(); final String baseSchemaUriString = baseSchemaUriNode.asText(); if (baseSchemaUriString != null && !baseSchemaUriString.isEmpty()) { final URI baseSchemaUri = syntaxLoader.parseSyntacticText(baseSchemaUriString, URI.class); if (baseSchemaUri != null) { _ExtendsSet.add(baseSchemaUri); }/*from w ww .j av a 2 s . c om*/ } } } else if (extendsJsonNode instanceof TextNode) { final String baseSchemaUriString = extendsJsonNode.asText(); if (baseSchemaUriString != null && !baseSchemaUriString.isEmpty()) { final URI baseSchemaUri = syntaxLoader.parseSyntacticText(baseSchemaUriString, URI.class); if (baseSchemaUri != null) { _ExtendsSet.add(baseSchemaUri); } } } } // v4 uses the allOf keyword if (rootNode.has(PropertyType.AllOf.getName())) { final JsonNode allOfJsonNode = rootNode.get(PropertyType.AllOf.getName()); // This element type MUST be an array if (allOfJsonNode instanceof ArrayNode) { final ArrayNode allOfArrayNode = (ArrayNode) allOfJsonNode; final Iterator<JsonNode> elements = allOfArrayNode.elements(); while (elements.hasNext()) { final JsonNode schemaNode = elements.next(); final JsonNode baseSchemaUriNode = schemaNode.get(PropertyType.$Ref.getName()); if (baseSchemaUriNode != null) { final URI baseSchemaUri = syntaxLoader.parseSyntacticText(baseSchemaUriNode.asText(), URI.class); if (baseSchemaUri != null) { _ExtendsSet.add(baseSchemaUri); } } } } } }