List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree
public JsonNode readTree(URL source) throws IOException, JsonProcessingException
From source file:eu.modaclouds.sla.mediator.ViolationSubscriber.java
private String extractOutputMetric(GuaranteeTerm guarantee) { String slo = guarantee.getServiceLevelObjetive().getKpitarget().getCustomServiceLevel(); ObjectMapper mapper = new ObjectMapper(); String constraint = null;//from w w w . j a v a 2s. co m JsonNode rootNode = null; try { rootNode = mapper.readTree(slo); } catch (JsonProcessingException e) { throw new MediatorException("Error processing slo json", e); } catch (IOException e) { throw new MediatorException("Error processing slo json", e); } JsonNode constraintNode = rootNode.path(TemplateGenerator.CONSTRAINT); constraint = constraintNode.textValue(); int pos = constraint.indexOf(' '); String violation = constraint.substring(0, pos == -1 ? slo.length() : pos); return violation; }
From source file:org.jasig.cas.support.oauth.web.OAuth20RevokeTokenControllerTests.java
@Test public void verifyRevocationFail() throws Exception { final AccessToken accessToken = mock(AccessToken.class); when(accessToken.getId()).thenReturn(TOKEN_ID); final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class); when(centralOAuthService.getToken(TOKEN_ID)).thenReturn(accessToken); when(centralOAuthService.revokeToken(accessToken)).thenReturn(false); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", CONTEXT + OAuthConstants.REVOKE_URL); mockRequest.setParameter(OAuthConstants.TOKEN, TOKEN_ID); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.setCentralOAuthService(centralOAuthService); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertNull(modelAndView);/*from w w w . j av a 2 s .c o m*/ assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus()); assertEquals(CONTENT_TYPE, mockResponse.getContentType()); final ObjectMapper mapper = new ObjectMapper(); final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\"" + OAuthConstants.FAILED_TOKEN_REVOCATION_DESCRIPTION + "\"}"; final JsonNode expectedObj = mapper.readTree(expected); final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString()); assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText()); assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText()); }
From source file:com.ericsson.eiffel.remrem.semantics.validator.EiffelValidator.java
public EiffelValidator(String schemaResourceName, String eventType, List<String> requiredLinkTypes, List<String> optionalLinkTypes, List<String> allLinkTypes) { this.schemaResourceName = schemaResourceName; this.eventType = eventType; this.requiredLinkTypes = requiredLinkTypes; this.optionalLinkTypes = optionalLinkTypes; this.allLinkTypes = allLinkTypes; ObjectMapper mapper = new ObjectMapper(); JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); ClassLoader classLoader = getClass().getClassLoader(); try {/*from www. j ava 2 s . c o m*/ validationSchema = factory .getJsonSchema(mapper.readTree(classLoader.getResourceAsStream(schemaResourceName))); log.debug("Validation schema loaded: {}", schemaResourceName); } catch (Exception e) { String message = "Cannot parse JSON schema. The resource: " + schemaResourceName + ". " + e.getClass() + ": " + e.getMessage(); log.error(message, e); throw new IllegalArgumentException(message, e); } }
From source file:org.opendaylight.alto.core.northbound.route.networkmap.impl.AltoNorthboundNetworkmapTest.java
@Test public void testgetFilteredMap() throws ExecutionException, InterruptedException, IOException { //config mock AltoNorthboundRouteNetworkmap networkmap = new AltoNorthboundRouteNetworkmap(); AltoNorthboundRouteNetworkmap networkmapSpy = spy(networkmap); InstanceIdentifier<ContextTag> ctagIID = InstanceIdentifier.create(ContextTag.class); doReturn(ctagIID).when(networkmapSpy).getResourceByPath(eq(path), (ReadOnlyTransaction) anyObject()); doReturn(AddressTypeIpv4.class).when(networkmapSpy).getAddressTypeByName(eq("ipv4"), eq(path), (ReadOnlyTransaction) anyObject()); doReturn(AddressTypeIpv6.class).when(networkmapSpy).getAddressTypeByName(eq("ipv6"), eq(path), (ReadOnlyTransaction) anyObject()); AltoModelNetworkmapService networkmapService = mock(AltoModelNetworkmapService.class); Future<RpcResult<QueryOutput>> future = mock(Future.class); RpcResult<QueryOutput> rpcResult = mock(RpcResult.class); List<Class<? extends AddressTypeBase>> types = new ArrayList<Class<? extends AddressTypeBase>>() { {/*from w w w . jav a 2 s .c om*/ add(AddressTypeIpv4.class); add(AddressTypeIpv6.class); } }; List<Partition> partitionList = new LinkedList<>(); int index = 0; for (String pid : pids) { ++index; PartitionBuilder partitionBuilder = new PartitionBuilder(); partitionBuilder.setPid(new PidName(pid)); if (types.contains(AddressTypeIpv4.class)) { LinkedList<Ipv4Prefix> ipv4List = new LinkedList<Ipv4Prefix>(); ipv4List.add(new Ipv4Prefix("192.168." + index + ".0/24")); Ipv4PrefixListBuilder v4Builder = new Ipv4PrefixListBuilder(); v4Builder.setIpv4(ipv4List); partitionBuilder.addAugmentation(Ipv4PrefixList.class, v4Builder.build()); } if (types.contains(AddressTypeIpv6.class)) { LinkedList<Ipv6Prefix> ipv6List = new LinkedList<Ipv6Prefix>(); ipv6List.add(new Ipv6Prefix("2001:b8:ca2:" + index + "::0/64")); Ipv6PrefixListBuilder v6Builder = new Ipv6PrefixListBuilder(); v6Builder.setIpv6(ipv6List); partitionBuilder.addAugmentation(Ipv6PrefixList.class, v6Builder.build()); } partitionList.add(partitionBuilder.build()); } NetworkMapBuilder nmBuilder = new NetworkMapBuilder(); nmBuilder.setPartition(partitionList); NetworkmapResponseBuilder nmrBuilder = new NetworkmapResponseBuilder(); nmrBuilder.setNetworkMap(nmBuilder.build()); QueryOutputBuilder queryOutputBuilder = new QueryOutputBuilder(); queryOutputBuilder.setResponse(nmrBuilder.build()); when(rpcResult.getResult()).thenReturn(queryOutputBuilder.build()); when(future.get()).thenReturn(rpcResult); when(networkmapService.query((QueryInput) anyObject())).thenReturn(future); networkmapSpy.setMapService(networkmapService); networkmapSpy.setDataBroker(new DataBroker() { @Override public ReadOnlyTransaction newReadOnlyTransaction() { return null; } @Override public ReadWriteTransaction newReadWriteTransaction() { return null; } @Override public WriteTransaction newWriteOnlyTransaction() { return null; } @Override public ListenerRegistration<DataChangeListener> registerDataChangeListener( LogicalDatastoreType logicalDatastoreType, InstanceIdentifier<?> instanceIdentifier, DataChangeListener dataChangeListener, DataChangeScope dataChangeScope) { return null; } @Override public BindingTransactionChain createTransactionChain( TransactionChainListener transactionChainListener) { return null; } @Nonnull @Override public <T extends DataObject, L extends DataTreeChangeListener<T>> ListenerRegistration<L> registerDataTreeChangeListener( @Nonnull DataTreeIdentifier<T> dataTreeIdentifier, @Nonnull L l) { return null; } }); doReturn(new RFC7285NetworkMap.Meta()).when(networkmapSpy).buildMeta((InstanceIdentifier<?>) anyObject()); //start test networkmapSpy.init(); Response response = networkmapSpy.getFilteredMap(path, filter); String surex = response.getEntity().toString(); ObjectMapper mapper = new ObjectMapper(); JsonNode responseTree = mapper.readTree(surex); JsonNode networkmapTree = responseTree.get("network-map"); JsonNode PID1 = networkmapTree.get("PID1"); JsonNode ipv4Node = PID1.get("ipv4"); assertEquals("192.168.1.0/24", ipv4Node.get(0).asText()); }
From source file:org.opendaylight.alto.core.northbound.route.costmap.impl.AltoNorthboundCostmapTest.java
@Test public void testgetFilteredMap() throws IOException, ExecutionException, InterruptedException { //mock config final AltoNorthboundRouteCostmap costmap = new AltoNorthboundRouteCostmap(); AltoNorthboundRouteCostmap costmapSpy = spy(costmap); InstanceIdentifier<ContextTag> ctagIID = InstanceIdentifier.create(ContextTag.class); AltoModelCostmapService costmapService = mock(AltoModelCostmapService.class); Future<RpcResult<QueryOutput>> future = mock(Future.class); RpcResult<QueryOutput> rpcResult = mock(RpcResult.class); //build QueryOutput int order = 0; LinkedList<CostmapSource> costmapSources = new LinkedList<CostmapSource>(); for (String src : pid_source) { LinkedList<CostmapDestination> costmapDestinations = new LinkedList<CostmapDestination>(); for (String dst : pid_destination) { CostmapDestinationBuilder costmapDestinationBuilder = new CostmapDestinationBuilder(); costmapDestinationBuilder.setPidDestination(new PidName(dst)); costmapDestinationBuilder.setCost(createOrdinalCost(++order)); costmapDestinations.add(costmapDestinationBuilder.build()); }/* www . j av a 2 s . c om*/ CostmapSourceBuilder costmapSourceBuilder = new CostmapSourceBuilder(); costmapSourceBuilder.setPidSource(new PidName(src)); costmapSourceBuilder.setCostmapDestination(costmapDestinations); costmapSources.add(costmapSourceBuilder.build()); } CostTypeBuilder costType = new CostTypeBuilder(); costType.setCostMode(costmode); costType.setCostMetric(new CostMetric(costmetri)); CostmapResponseDataBuilder costmapResponseDataBuilder = new CostmapResponseDataBuilder(); costmapResponseDataBuilder.setCostType(costType.build()); costmapResponseDataBuilder.setCostmapSource(costmapSources); CostmapResponseBuilder costmapResponseBuilder = new CostmapResponseBuilder(); costmapResponseBuilder.setCostmapResponseData(costmapResponseDataBuilder.build()); QueryOutputBuilder queryOutput = new QueryOutputBuilder(); queryOutput.setResponse(costmapResponseBuilder.build()); when(rpcResult.getResult()).thenReturn(queryOutput.build()); when(future.get()).thenReturn(rpcResult); when(costmapService.query((QueryInput) anyObject())).thenReturn(future); costmapSpy.setMapService(costmapService); costmapSpy.setDataBroker(new DataBroker() { @Override public ReadOnlyTransaction newReadOnlyTransaction() { return null; } @Override public ReadWriteTransaction newReadWriteTransaction() { return null; } @Override public WriteTransaction newWriteOnlyTransaction() { return null; } @Override public ListenerRegistration<DataChangeListener> registerDataChangeListener( LogicalDatastoreType logicalDatastoreType, InstanceIdentifier<?> instanceIdentifier, DataChangeListener dataChangeListener, DataChangeScope dataChangeScope) { return null; } @Override public BindingTransactionChain createTransactionChain( TransactionChainListener transactionChainListener) { return null; } @Nonnull @Override public <T extends DataObject, L extends DataTreeChangeListener<T>> ListenerRegistration<L> registerDataTreeChangeListener( @Nonnull DataTreeIdentifier<T> dataTreeIdentifier, @Nonnull L l) { return null; } }); doReturn(ctagIID).when(costmapSpy).getResourceByPath(eq(path), (ReadOnlyTransaction) anyObject()); RFC7285CostMap.Meta meta = new RFC7285CostMap.Meta(); RFC7285CostType rfc7285costType = new RFC7285CostType(); rfc7285costType.metric = costmetri; rfc7285costType.mode = costmode; meta.costType = rfc7285costType; doReturn(meta).when(costmapSpy).buildMeta((InstanceIdentifier<?>) anyObject(), (RFC7285CostType) anyObject()); //start test costmapSpy.init(); Response response = costmapSpy.getFilteredMap(path, filter); String responseStr = response.getEntity().toString(); ObjectMapper mapper = new ObjectMapper(); JsonNode responseNode = mapper.readTree(responseStr); JsonNode costmapNode = responseNode.get("cost-map"); JsonNode PID1Node = costmapNode.get("PID1"); JsonNode PID2Node = PID1Node.get("PID2"); assertEquals("2", PID2Node.asText()); // assertEquals(responseStr,surex); }
From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_PurgeBuckets.java
private PurgeQueueBean createPurgeQEntry() throws JsonProcessingException, IOException { final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty()); final JsonNode v1_source = mapper .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_source.json")); return BeanTemplateUtils.build(PurgeQueueBean.class).with(PurgeQueueBean::_id, new ObjectId().toString()) .with(PurgeQueueBean::source, v1_source).with(PurgeQueueBean::status, PurgeStatus.submitted).done() .get();/*from w w w.j a v a 2s . c om*/ }
From source file:com.ericsson.eiffel.remrem.publish.service.EventTemplateHandler.java
public JsonNode eventTemplateParser(String jsonData, String eventName) { JsonNode updatedJson = null;/*from w w w . j av a 2 s.c om*/ JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); JsonNode rootNode = null; try { String eventTemplate = accessFileInSemanticJar(EVENT_TEMPLATE_PATH + eventName.toLowerCase() + ".json"); rootNode = mapper.readTree(jsonData); updatedJson = mapper.readValue(eventTemplate, JsonNode.class); } catch (IOException e) { log.error(e.getMessage(), e); } // For each key/value pair for parsing to template Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); while (fieldsIterator.hasNext()) { Map.Entry<String, JsonNode> field = fieldsIterator.next(); // Parse values to template // Check if POJO required for update in event template Pattern p = Pattern.compile(REGEXP_END_DIGITS); // if ends with [d+] Matcher m = p.matcher(field.getKey()); String myKey = "$." + templateParamHandler(field.getKey()); if (field.getValue().toString().equals("\"<%DELETE%>\"")) { updatedJson = jsonPathHandlerDelete(updatedJson, myKey); } else if (m.find()) { String myValue = field.getValue().toString(); try { // Fetch Class name in Event Schema String eventSchema = accessFileInSemanticJar(EVENT_SCHEMA_PATH + eventName + ".json"); // Filter javatype from Event Schema = class name JsonNode jsonFromSchema = JsonPath.using(configuration).parse(eventSchema.toString()) .read(schemaClassPathHandler(field.getKey().replaceAll(REGEXP_END_DIGITS, ""))); String myClassName = jsonFromSchema.toString().replace("[", "").replace("]", "").replace("\"", ""); // Ex ["com.ericsson.eiffel.semantics.events.PersistentLog"] to com.ericsson.eiffel.semantics.events.PersistentLog // Initiate Class via reflection and map values - POJO Class myClass = Class.forName(myClassName); Object mapped2Pojo = mapper.readValue(myValue, myClass); updatedJson = jsonPathHandlerSet(updatedJson, myKey, mapped2Pojo); } catch (ClassNotFoundException e) { // No POJO required for adding new item in Array (ie no key/value pairs) updatedJson = jsonPathHandlerSet(updatedJson, myKey, myValue.toString().replace("\"", "")); } catch (Exception e) { log.error(e.getMessage(), e); } } else { // No POJO needed for update Object myValue = field.getValue(); updatedJson = jsonPathHandlerSet(updatedJson, myKey, myValue); } } // while return updatedJson; }
From source file:com.ericsson.eiffel.remrem.publish.service.EventTemplateHandlerTest.java
private void testParser(String EventName) { try {//w w w.j a v a 2s . co m EventTemplateHandler eventTemplateHandler = new EventTemplateHandler(); String dataToBeParsed = FileUtils.readFileToString( new File(INPUT_FILE_PATH_DATA + "test_data_for_parsing_" + EventName + ".json"), "UTF-8"); String expectedDocument = FileUtils.readFileToString( new File(INPUT_FILE_PATH_EXPECTED_DATA + "expected_parsed_" + EventName + ".json"), "UTF-8"); ObjectMapper mapper = new ObjectMapper(); JsonNode expectedJson = mapper.readTree(expectedDocument); JsonNode actualParsedEventJson = eventTemplateHandler.eventTemplateParser(dataToBeParsed, EventName); LOG.info("expectedJsonString: " + expectedJson.toString()); LOG.info("actualParsedEventJson: " + actualParsedEventJson.toString()); JSONAssert.assertEquals(expectedJson.toString(), actualParsedEventJson.toString(), true); } catch (Exception e) { LOG.error(e.getMessage(), e); } }
From source file:com.gsma.mobileconnect.utils.JsonUtilsTest.java
@Test public void getErrorResponse_withNoError_shouldReturnNull() throws IOException { // GIVEN//from w ww.j av a2 s . c o m String json = "{ \"no-error\": \"value\", " + "\"error_description\": \"error_description\", " + "\"description\": \"description\", " + "\"error_uri\": \"error_uri\" }"; ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(json); // WHEN ErrorResponse errorResponse = JsonUtils.getErrorResponse(root); // THEN assertNull(errorResponse); }